xmcp 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -70,7 +70,7 @@ data:
70
70
  `;return n&&(o+=`id: ${n}
71
71
  `),o+=`data: ${JSON.stringify(i)}
72
72
 
73
- `,t.enqueue(r.encode(o)),!0}catch(t){return this.onerror?.(t),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),Response.json({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 i,n,o,a,s,l=t.headers.get("accept");if(!l?.includes("application/json")||!l.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!uZ(t.headers.get("content-type")))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");if(r?.parsedBody===void 0)try{let r=await dj(t,this._maxRequestBodySize);if(r.tooLarge){let t=dI(this._maxRequestBodySize);return this.onerror?.(Error(t)),this.createJsonErrorResponse(413,-32e3,t)}i=JSON.parse(r.text)}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else i=r.parsedBody;if(Array.isArray(i)&&i.length>100)return this.onerror?.(Error("Invalid Request: Batch must not exceed 100 messages")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Batch must not exceed 100 messages");try{n=Array.isArray(i)?i.map(t=>ad.parse(t)):[ad.parse(i)]}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let c=n.some(t=>aC.safeParse(t).success);if(c){if(this._initialized&&void 0!==this.sessionId)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(n.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),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(!c){let r=this.validateSession(t);if(r)return r;let i=this.validateProtocolVersion(t);if(i)return i}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");try{o=await this._checkScopeChallenge(n,r?.authInfo)}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(500,-32603,"Internal server error")}if(o)return o;if(!n.some(t=>cX(t))){for(let i of n)this.onmessage?.(i,{authInfo:r?.authInfo,request:t});return new Response(null,{status:202})}let u=crypto.randomUUID(),d=n.find(t=>aC.safeParse(t).success),p=d?d.params.protocolVersion:t.headers.get("mcp-protocol-version")??"2025-03-26";if(this._enableJsonResponse)return new Promise(i=>{for(let t of(this._streamMapping.set(u,{resolveJson:i,cleanup:()=>{this._streamMapping.delete(u)}}),n))cX(t)&&this._requestToStreamMapping.set(t.id,u);for(let i of n)this.onmessage?.(i,{authInfo:r?.authInfo,request:t})});let m=new TextEncoder,h=new ReadableStream({start:t=>{a=t},cancel:()=>{void 0!==s&&clearInterval(s),this._streamMapping.get(u)?.controller===a&&this._streamMapping.delete(u)}}),f={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};for(let t of(void 0!==this.sessionId&&(f["mcp-session-id"]=this.sessionId),n))cX(t)&&(this._streamMapping.set(u,{controller:a,encoder:m,cleanup:()=>{void 0!==s&&clearInterval(s),this._streamMapping.delete(u);try{a.close()}catch{}}}),this._requestToStreamMapping.set(t.id,u));for(let i of(await this.writePrimingEvent(a,m,u,p),n)){let n,o;cX(i)&&this._eventStore&&this.supportsEmptySSEData(p)&&(n=()=>{this.closeSSEStream(i.id)},o=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(i,{authInfo:r?.authInfo,request:t,closeSSEStream:n,closeStandaloneSSEStream:o})}return this._streamMapping.get(u)?.controller===a&&(s=this.startKeepAlive(a,m)),new Response(h,{status:200,headers:f})}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(t)})}}async handleDeleteRequest(t){let r=this.validateSession(t);if(r)return r;let i=this.validateProtocolVersion(t);if(i)return i;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(t){if(void 0===this.sessionIdGenerator)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=t.headers.get("mcp-session-id");return r?r!==this.sessionId?(this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")):void 0:(this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required"))}validateProtocolVersion(t){let r=t.headers.get("mcp-protocol-version");if(null!==r&&!this._supportedProtocolVersions.includes(r)){let t=`Bad Request: Unsupported protocol version: ${r} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(Error(t)),this.createJsonErrorResponse(400,-32e3,t)}}async close(){if(!this._closed){for(let{cleanup:t}of(this._closed=!0,this._streamMapping.values()))t();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(t){let r=this._requestToStreamMapping.get(t);if(!r)return;let i=this._streamMapping.get(r);i&&i.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,r){let i=r?.relatedRequestId;if((c0(t)||c1(t))&&(i=t.id),void 0===i){let r;if(c0(t)||c1(t))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");this._eventStore&&(r=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let i=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===i)return;i.controller&&i.encoder&&(void 0===r||!i.replayedEventIds?.has(r))&&this.writeSSEEvent(i.controller,i.encoder,t,r);return}let n=this._requestToStreamMapping.get(i);if(!n)throw Error(`No connection established for request ID: ${String(i)}`);let o=this._streamMapping.get(n);if(!this._enableJsonResponse){let r;this._eventStore&&(r=await this._eventStore.storeEvent(n,t),o=this._streamMapping.get(n)),o?.controller&&o?.encoder&&(void 0===r||!o.replayedEventIds?.has(r))&&this.writeSSEEvent(o.controller,o.encoder,t,r)}if(c0(t)||c1(t)){this._requestResponseMap.set(i,t);let r=[...this._requestToStreamMapping.entries()].filter(([t,r])=>r===n).map(([t])=>t);if(r.every(t=>this._requestResponseMap.has(t))){if(!o){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(i)}`);if(!this._eventStore){for(let t of(this.onerror?.(Error(`Response for request ID ${String(i)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)),r))this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t);return}for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t);return}if(this._enableJsonResponse&&o.resolveJson){let t={"Content-Type":"application/json"};void 0!==this.sessionId&&(t["mcp-session-id"]=this.sessionId);let i=r.map(t=>this._requestResponseMap.get(t));1===i.length?o.resolveJson(Response.json(i[0],{status:200,headers:t})):o.resolveJson(Response.json(i,{status:200,headers:t})),o.cleanup()}else o.cleanup();for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t)}}}};function dL(t){if(null===t||"object"!=typeof t||Array.isArray(t))return null;let{method:r,id:i}=t;return"string"!=typeof r?null:"string"==typeof i||"number"==typeof i?i:null}function dN(t,r,i,n,o=null){return Response.json({jsonrpc:"2.0",error:{code:r,message:i,...void 0!==n&&{data:n}},id:o},{status:t})}function dz(t,r=null){return dN(t.httpStatus,t.code,t.message,t.data,r)}function dM(t){return t instanceof Error?t:Error(String(t))}function dZ(t=null){return dN(500,-32603,"Internal server error",void 0,t)}function dU(t){if(void 0!==t.transport)throw Error("The factory returned an instance that is still serving another request. Return a new instance for each request.")}function dF(t){return{protocolVersionHeader:t.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:t.headers.get("mcp-method")??void 0,mcpNameHeader:t.headers.get("mcp-name")??void 0}}async function dH(t,r,i=!0,n=4194304){let o,a=t.method.toUpperCase(),s=r,l=t,c=!1;if("POST"===a){if(void 0===s){let r;i&&(l=t.clone());try{let i=await dj(t,n);if(i.tooLarge)return{step:"body-too-large"};r=i.text}catch{return{step:"unreadable-body"}}try{o=0===r.length?void 0:JSON.parse(r)}catch{c=!0}c||void 0===o||(s=o)}else o=s;if(c||void 0===o)return{step:"no-json-body",forwardRequest:l}}return{step:"classified",outcome:function(t){if("POST"!==(t={...t,...void 0!==t.protocolVersionHeader&&{protocolVersionHeader:uc(t.protocolVersionHeader)},...void 0!==t.mcpMethodHeader&&{mcpMethodHeader:uc(t.mcpMethodHeader)},...void 0!==t.mcpNameHeader&&{mcpNameHeader:uc(t.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let r=t.body;if(Array.isArray(r)){if(0===r.length)return ua("jsonrpc-shape","empty-batch",400,new c_(cv.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let t of r){if(cW(uu(t)?t.params:void 0))return ua("jsonrpc-shape","batch-with-modern-element",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(cX(t)||cQ(t)||c0(t)||c1(t)))return ua("jsonrpc-shape","batch-with-invalid-element",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return c0(r)||c1(r)?{kind:"legacy",reason:"response"}:uu(r)&&cX(r)?function(t,r){let i=r.params,n=r.method,o=t.protocolVersionHeader,a=void 0!==o&&o>=lQ;if("initialize"===n&&!function(t){if(!cW(t))return!1;let r=cG(t);if(void 0===r||!(r>=lQ))return!1;let i=cB(t);return void 0!==i&&0===cK(i).length}(i)){if(a)return us("initialize-with-modern-header",o,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let t=uu(i)&&"string"==typeof i.protocolVersion?i.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==t&&{requestedVersion:t}}}if(cW(i)){let a=cB(i),s=(void 0===a?[]:cK(a))[0];if(void 0!==s)return ua("envelope","envelope-invalid",400,new c_(cv.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${s.key}: ${s.problem}`,{envelope:s}),!0);let l=cG(i);return void 0!==o&&void 0!==l&&o!==l?us("header-body-version-mismatch",o,`the body envelope names protocol version ${l} but the MCP-Protocol-Version header names ${o}`):void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?us("method-header-mismatch",t.mcpMethodHeader,`the body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:r,classification:ud(l)}}if(a){let t=cB(i),r=cK(t??{}).filter(t=>"missing"===t.problem).map(t=>t.key),n=void 0===t?["_meta"]:r.length>0?r:[oG];return ua("envelope","modern-header-without-claim",400,new c_(cv.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${o}, but the request is missing the required per-request envelope key(s): ${n.join(", ")}`,{envelope:{missing:n}}),!0)}return{kind:"legacy",reason:"no-claim",...void 0!==o&&{requestedVersion:o}}}(t,r):uu(r)&&cQ(r)?function(t,r){let i=r.params,n=r.method,o=t.protocolVersionHeader,a=void 0!==o&&o>=lQ;if(cW(i)){let a=cG(i);if(void 0===a){let t=cB(i),r=(void 0===t?[]:cK(t)).find(t=>t.key===oG)??{key:oG,problem:"expected a protocol version string"};return ua("envelope","notification-envelope-invalid",400,new c_(cv.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${r.key}: ${r.problem}`,{envelope:r}),!0)}if(void 0!==o&&o!==a)return us("notification-header-body-version-mismatch",o,`the notification envelope names protocol version ${a} but the MCP-Protocol-Version header names ${o}`);let s=ud(a);return"modern"===s.era&&void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?us("notification-method-header-mismatch",t.mcpMethodHeader,`the notification body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:r,classification:s}}return a?void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?us("notification-method-header-mismatch",t.mcpMethodHeader,`the notification body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:r,classification:{era:"modern",revision:o}}:{kind:"legacy",reason:"notification",...void 0!==o&&{requestedVersion:o}}}(t,r):ua("jsonrpc-shape","invalid-json-rpc-body",400,new c_(cv.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:a,...dF(t),...void 0!==o&&{body:o}}),body:o,parsedBody:s,forwardRequest:l}}function dD(t){let{tags:r,enabled:i,...n}=t;return{...n,_meta:void 0===r?n._meta:{...n._meta,"xmcp/tags":r}}}let dV=new class{add(t,r){this.resources.set(t,r)}getAll(){return this.resources}clear(){this.resources.clear()}has(t){return this.resources.has(t)}constructor(){var t,r;t="resources",r=new Map,t in this?Object.defineProperty(this,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):this[t]=r}},dJ=(t,r)=>{globalThis[t]=r},dB=t=>globalThis[t];function dW({name:t,fallback:r=!0}){let i=Symbol.for(`xmcp-context-${t}`),n=Symbol.for(`xmcp-context-${t}-fallback-store`);if(dB(i))return dB(i);let o=new x,a=globalThis[n]??{current:null};dJ(n,a);let s={provider:(t,i)=>(r&&(a.current=t),o.run(t,i)),getContext:()=>{let i=o.getStore();if(i)return i;if(r&&a.current)return a.current;throw Error(`getContext() can only be used within the ${t} context.`)},setContext:i=>{let n=o.getStore()??(r?a.current:null);if(!n)throw Error(`setContext() can only be used within the ${t} context.`);Object.assign(n,i)}};return dJ(i,s),s}let dG=dW({name:"http-request-context"});dG.setContext;let dK=dG.getContext,dY=dG.provider,dX=dW({name:"request-context",fallback:!1}),dQ=dW({name:"client-info-context"});dQ.setContext;let d0=dQ.getContext;dQ.provider;let d1=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),d2=t=>{if(!d1(t)||"string"!=typeof t.name||"string"!=typeof t.version)return;let r={name:t.name,version:t.version};return"string"==typeof t.title&&(r.title=t.title),"string"==typeof t.websiteUrl&&(r.websiteUrl=t.websiteUrl),"string"==typeof t.description&&(r.description=t.description),r},d9=t=>{if(t&&"initialize"===t.method&&d1(t.params))return d2(t.params.clientInfo)},d4=(t,r)=>{let i=r.toLowerCase();for(let[r,n]of Object.entries(t)){if(r.toLowerCase()!==i)continue;let t=Array.isArray(n)?n[0]:n;if("string"!=typeof t)break;let o=t.trim();return o.length>0?o:void 0}},d5=new Set(["message","mode","requestedSchema"]),d3=new Set(["elicitationId","message","mode","url"]),d6=new Set(["properties","required","type"]),d7=new Set(["default","description","format","maxLength","minLength","title","type"]),d8=new Set(["default","description","enum","enumNames","title","type"]),pe=new Set(["default","description","title","type"]),pt=new Set(["default","description","maximum","minimum","title","type"]),pr=new Set(["date","date-time","email","uri"]);async function pi(t,r,i){let n=function(t){let r=t.mode??"form";if("url"===r)return function(t){let r;po(t,"Elicitation request must be a plain object."),pn(t,d3,"URL elicitation"),pa(t.message,"URL elicitation requires a string message."),ps(t.elicitationId,"URL elicitation requires a non-empty elicitationId."),ps(t.url,"URL elicitation requires a non-empty URL.");try{r=new URL(t.url)}catch{throw Error("URL elicitation requires a valid http or https URL.")}if("http:"!==r.protocol&&"https:"!==r.protocol)throw Error("URL elicitation requires a valid http or https URL.")}(t),t;if("form"!==r)throw Error(`Unsupported elicitation mode "${String(t.mode)}". Expected "form" or "url".`);return function(t){po(t,"Elicitation request must be a plain object."),pn(t,d5,"Form elicitation"),pa(t.message,"Form elicitation requires a string message.");let r=t.requestedSchema;if(po(r,"Form elicitation requires a flat object schema."),pn(r,d6,"Form elicitation schema"),"object"!==r.type)throw Error('Form elicitation schema must use type "object".');for(let[t,i]of(po(r.properties,"Form elicitation schema requires a properties object."),Object.entries(r.properties)))!function(t,r){if(po(r,`Form elicitation field "${t}" must be a plain object.`),pl(r.title,`Form elicitation field "${t}" title must be a string.`),pl(r.description,`Form elicitation field "${t}" description must be a string.`),"string"===r.type&&"enum"in r){var i,n;if(pn(r,d8,`Form elicitation field "${t}"`),pu(r.enum,`Form elicitation field "${t}" enum values must be strings.`),i=r.enumNames,n=`Form elicitation field "${t}" enumNames must be strings.`,void 0!==i&&pu(i,n),void 0!==r.enumNames&&r.enumNames.length!==r.enum.length)throw Error(`Form elicitation field "${t}" enumNames length must match enum length.`);if(pl(r.default,`Form elicitation field "${t}" default must be a string.`),void 0!==r.default&&!r.enum.includes(r.default))throw Error(`Form elicitation field "${t}" default must be one of its enum values.`);return}if("string"===r.type&&!("enum"in r)){pn(r,d7,`Form elicitation field "${t}"`),pc(r.minLength,`Form elicitation field "${t}" minLength must be a number.`),pc(r.maxLength,`Form elicitation field "${t}" maxLength must be a number.`),pl(r.default,`Form elicitation field "${t}" default must be a string.`);let i=r.format;if(pl(i,`Form elicitation field "${t}" format must be a string.`),void 0!==i&&!pr.has(i))throw Error(`Form elicitation field "${t}" format must be one of: ${Array.from(pr).join(", ")}.`);return}if("boolean"===r.type){if(pn(r,pe,`Form elicitation field "${t}"`),void 0!==r.default&&"boolean"!=typeof r.default)throw Error(`Form elicitation field "${t}" default must be a boolean.`);return}if("number"===r.type||"integer"===r.type){pn(r,pt,`Form elicitation field "${t}"`),pc(r.minimum,`Form elicitation field "${t}" minimum must be a number.`),pc(r.maximum,`Form elicitation field "${t}" maximum must be a number.`),pc(r.default,`Form elicitation field "${t}" default must be a number.`);return}throw Error(`Form elicitation field "${t}" uses unsupported type "${String(r.type)}". Supported types are string, boolean, number, integer, and string enums.`)}(t,i);if(void 0!==r.required){if(!Array.isArray(r.required)||r.required.some(t=>"string"!=typeof t))throw Error("Form elicitation schema required fields must be a string array.");for(let t of r.required)if(!(t in r.properties))throw Error(`Form elicitation schema required field "${t}" is not defined in properties.`)}}(t),{...t,mode:"form"}}(r);try{let r=await t.mcpReq.elicitInput(n,i);return{...r,content:r.content??void 0}}catch(t){if(t instanceof lG&&t.code===lW.MethodNotSupportedByProtocolVersion)throw Error("extra.elicit() is not available on protocol revision 2026-07-28: server-initiated elicitation was replaced by multi round-trip requests. Return inputRequired({ ... }) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw t}}function pn(t,r,i){let n=Object.keys(t).filter(t=>!r.has(t));if(0!==n.length)throw Error(`${i} includes unsupported key(s): ${n.join(", ")}.`)}function po(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}function pa(t,r){if("string"!=typeof t)throw Error(r)}function ps(t,r){if("string"!=typeof t||0===t.trim().length)throw Error(r)}function pl(t,r){if(void 0!==t&&"string"!=typeof t)throw Error(r)}function pc(t,r){if(void 0!==t&&"number"!=typeof t)throw Error(r)}function pu(t,r){if(!Array.isArray(t)||t.some(t=>"string"!=typeof t))throw Error(r)}let pd=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),pp=new Set(["task","toolChoice","tools"]),pm=new Set(["text","image","audio"]);async function ph(t,r,i){let n=function(t){pf(t,"Sampling request must be a plain object.");let r=Object.keys(t),i=r.filter(t=>pp.has(t));if(i.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${i.join(", ")}.`);let n=r.filter(t=>!pd.has(t));if(n.length>0)throw Error(`Sampling request includes unsupported key(s): ${n.join(", ")}.`);if(!Array.isArray(t.messages)||0===t.messages.length)throw Error("Sampling requires at least one message.");for(let[r,i]of t.messages.entries())!function(t,r){if(pf(r,`Sampling message at index ${t} must be a plain object.`),"user"!==r.role&&"assistant"!==r.role)throw Error(`Sampling message at index ${t} requires role "user" or "assistant".`);let i=r.content;pf(i,`Sampling message at index ${t} requires a content object.`);let n=i.type;if("string"!=typeof n||!pm.has(n))throw Error(`Sampling message at index ${t} uses unsupported content type "${String(n)}". Supported types are text, image, and audio.`);if("text"===n&&"string"!=typeof i.text)throw Error(`Sampling message at index ${t} requires string text content.`);if(("image"===n||"audio"===n)&&("string"!=typeof i.data||"string"!=typeof i.mimeType))throw Error(`Sampling message at index ${t} requires base64 data and a mimeType.`)}(r,i);if("number"!=typeof t.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return t}(r);try{return await t.mcpReq.requestSampling(n,i)}catch(t){if(t instanceof lG&&t.code===lW.MethodNotSupportedByProtocolVersion)throw Error("extra.sample() is not available on protocol revision 2026-07-28: server-initiated sampling was replaced by multi round-trip requests. Return inputRequired({ ... }) with inputRequired.createMessage(...) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw t}}function pf(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}let pg={text:t=>"string"!=typeof t.text?{valid:!1,error:'Text content must have a "text" property of type string'}:{valid:!0},image:t=>"string"!=typeof t.data?{valid:!1,error:'Image content must have a "data" property of type string (base64-encoded image)'}:"string"!=typeof t.mimeType?{valid:!1,error:'Image content must have a "mimeType" property of type string'}:{valid:!0},audio:t=>"string"!=typeof t.data?{valid:!1,error:'Audio content must have a "data" property of type string (base64-encoded audio)'}:"string"!=typeof t.mimeType?{valid:!1,error:'Audio content must have a "mimeType" property of type string'}:{valid:!0},resource_link:t=>"string"!=typeof t.name?{valid:!1,error:'Resource link content must have a "name" property of type string'}:"string"!=typeof t.uri?{valid:!1,error:'Resource link content must have a "uri" property of type string'}:void 0!==t.title&&"string"!=typeof t.title?{valid:!1,error:'Resource link "title" property must be a string if provided'}:void 0!==t.description&&"string"!=typeof t.description?{valid:!1,error:'Resource link "description" property must be a string if provided'}:void 0!==t.mimeType&&"string"!=typeof t.mimeType?{valid:!1,error:'Resource link "mimeType" property must be a string if provided'}:{valid:!0}};function py(t){if(!t||"object"!=typeof t)return{valid:!1,error:"Content must be an object"};if("string"!=typeof t.type)return{valid:!1,error:'Content must have a "type" property of type string'};if(void 0!==t._meta&&(null===t._meta||"object"!=typeof t._meta))return{valid:!1,error:'Content "_meta" property must be an object if provided'};let r=pg[t.type];return r?r(t):{valid:!0}}function pv(t,r,i,n){if(null===t||"object"!=typeof t||Array.isArray(t))throw Error(`Tool "${i}" ${n}: expected a plain object.`);let o=new Set(Object.keys(r)),a=Object.keys(t).filter(t=>!o.has(t));if(a.length>0)throw Error(`Tool "${i}" ${n}: unrecognized key(s): ${a.join(", ")}`);for(let[o,a]of Object.entries(r))try{a.parse(t[o])}catch(t){throw Error(`Tool "${i}" ${n}: ${t?.message??`invalid field "${o}"`}`)}}function p_(t){return!!(t&&"object"==typeof t&&Object.keys(t).some(t=>t.startsWith("ui/")))}function pb(t){let r=t.mcpReq.envelope,i=d2(r?.[oK]);if(!i)try{let t,r=dK();i=r.clientInfo??(t=r.headers,d2({name:d4(t,"x-mcp-client-name"),version:d4(t,"x-mcp-client-version"),title:d4(t,"x-mcp-client-title"),websiteUrl:d4(t,"x-mcp-client-website-url"),description:d4(t,"x-mcp-client-description")}))}catch{}if(!i)try{i=d0().clientInfo}catch{}return i}function pS(t){let r=[...t];return(t,i,n)=>(function(t,r,i){let n,o=new Map;if(t.http){let t=dK(),r=Object.fromEntries(Object.entries(t.headers).map(([t,r])=>[t,Array.isArray(r)?Object.freeze([...r]):r]));n=Object.freeze({id:t.id,headers:Object.freeze(r)})}return dX.provider(Object.freeze({clientInfo:r?Object.freeze({...r}):void 0,http:n,authInfo:t.http?.authInfo,signal:t.mcpReq.signal,set(t,r){o.set(t,r)},get:t=>o.get(t),async progress(r,i){let n=t.mcpReq._meta?.progressToken;void 0!==n&&await t.mcpReq.notify({method:"notifications/progress",params:{progressToken:n,progress:r,...void 0===i?{}:{total:i}}})},log:(r,i)=>t.mcpReq.log(r,i)}),i)})(i,pb(i),async()=>{if(0===r.length)return n();let i=Object.freeze({...function(){try{return dX.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),...t,params:Object.freeze({...t.params})}),o=-1,a=async t=>{if(t<=o)throw Error("MCP middleware next() can only be called once");o=t;let s=r[t];return s?s(i,()=>a(t+1)):n()};return a(0)})}let pw=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function pR(t){return t.endsWith(".tsx")}let pk=Symbol("Let zodToJsonSchema decide on which parser to use"),px={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};(E=L||(L={})).assertEqual=t=>{},E.assertIs=function(t){},E.assertNever=function(t){throw Error()},E.arrayToEnum=t=>{let r={};for(let i of t)r[i]=i;return r},E.getValidEnumValues=t=>{let r=E.objectKeys(t).filter(r=>"number"!=typeof t[t[r]]),i={};for(let n of r)i[n]=t[n];return E.objectValues(i)},E.objectValues=t=>E.objectKeys(t).map(function(r){return t[r]}),E.objectKeys="function"==typeof Object.keys?t=>Object.keys(t):t=>{let r=[];for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&r.push(i);return r},E.find=(t,r)=>{for(let i of t)if(r(i))return i},E.isInteger="function"==typeof Number.isInteger?t=>Number.isInteger(t):t=>"number"==typeof t&&Number.isFinite(t)&&Math.floor(t)===t,E.joinValues=function(t,r=" | "){return t.map(t=>"string"==typeof t?`'${t}'`:t).join(r)},E.jsonStringifyReplacer=(t,r)=>"bigint"==typeof r?r.toString():r,(N||(N={})).mergeShapes=(t,r)=>({...t,...r});let pC=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),p$=t=>{switch(typeof t){case"undefined":return pC.undefined;case"string":return pC.string;case"number":return Number.isNaN(t)?pC.nan:pC.number;case"boolean":return pC.boolean;case"function":return pC.function;case"bigint":return pC.bigint;case"symbol":return pC.symbol;case"object":if(Array.isArray(t))return pC.array;if(null===t)return pC.null;if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return pC.promise;if("undefined"!=typeof Map&&t instanceof Map)return pC.map;if("undefined"!=typeof Set&&t instanceof Set)return pC.set;if("undefined"!=typeof Date&&t instanceof Date)return pC.date;return pC.object;default:return pC.unknown}},pT=L.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"]);class pP extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=t=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};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(t){return t.message},i={_errors:[]},n=t=>{for(let o of t.issues)if("invalid_union"===o.code)o.unionErrors.map(n);else if("invalid_return_type"===o.code)n(o.returnTypeError);else if("invalid_arguments"===o.code)n(o.argumentsError);else if(0===o.path.length)i._errors.push(r(o));else{let t=i,n=0;for(;n<o.path.length;){let i=o.path[n],a=n===o.path.length-1;if("_errors"===i){a&&t._errors.push(r(o)),n++;continue}Object.prototype.hasOwnProperty.call(t,i)||("__proto__"===i?Object.defineProperty(t,i,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):t[i]={_errors:[]}),t=t[i],a&&t._errors.push(r(o)),n++}}};return n(this),i}static assert(t){if(!(t instanceof pP))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(t=t=>t.message){let r=Object.create(null),i=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(t(n))}else i.push(t(n));return{formErrors:i,fieldErrors:r}}get formErrors(){return this.flatten()}}pP.create=t=>new pP(t);let pE=(t,r)=>{let i;switch(t.code){case pT.invalid_type:i=t.received===pC.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case pT.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,L.jsonStringifyReplacer)}`;break;case pT.unrecognized_keys:i=`Unrecognized key(s) in object: ${L.joinValues(t.keys,", ")}`;break;case pT.invalid_union:i="Invalid input";break;case pT.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${L.joinValues(t.options)}`;break;case pT.invalid_enum_value:i=`Invalid enum value. Expected ${L.joinValues(t.options)}, received '${t.received}'`;break;case pT.invalid_arguments:i="Invalid function arguments";break;case pT.invalid_return_type:i="Invalid function return type";break;case pT.invalid_date:i="Invalid date";break;case pT.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(i=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(i=`${i} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?i=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?i=`Invalid input: must end with "${t.validation.endsWith}"`:L.assertNever(t.validation):i="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case pT.too_small:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type||"bigint"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case pT.too_big:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case pT.custom:i="Invalid input";break;case pT.invalid_intersection_types:i="Intersection results could not be merged";break;case pT.not_multiple_of:i=`Number must be a multiple of ${t.multipleOf}`;break;case pT.not_finite:i="Number must be finite";break;default:i=r.defaultError,L.assertNever(t)}return{message:i}};(O=z||(z={})).errToObj=t=>"string"==typeof t?{message:t}:t||{},O.toString=t=>"string"==typeof t?t:t?.message;let pO=t=>{let{data:r,path:i,errorMaps:n,issueData:o}=t,a=[...i,...o.path||[]],s={...o,path:a};if(void 0!==o.message)return{...o,path:a,message:o.message};let l="";for(let t of n.filter(t=>!!t).slice().reverse())l=t(s,{data:r,defaultError:l}).message;return{...o,path:a,message:l}};function pI(t,r){let i=pO({issueData:r,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pE,void 0].filter(t=>!!t)});t.common.issues.push(i)}class pq{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(t,r){let i=[];for(let n of r){if("aborted"===n.status)return pj;"dirty"===n.status&&t.dirty(),i.push(n.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,r){let i=[];for(let t of r){let r=await t.key,n=await t.value;i.push({key:r,value:n})}return pq.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let n of r){let{key:r,value:o}=n;if("aborted"===r.status||"aborted"===o.status)return pj;"dirty"===r.status&&t.dirty(),"dirty"===o.status&&t.dirty(),"__proto__"!==r.value&&(void 0!==o.value||n.alwaysSet)&&(i[r.value]=o.value)}return{status:t.value,value:i}}}let pj=Object.freeze({status:"aborted"}),pA=t=>({status:"dirty",value:t}),pL=t=>({status:"valid",value:t}),pN=t=>"undefined"!=typeof Promise&&t instanceof Promise;class pz{constructor(t,r,i,n){this._cachedPath=[],this.parent=t,this.data=r,this._path=i,this._key=n}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}}let pM=(t,r)=>{if("valid"===r.status)return{success:!0,data:r.value};if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new pP(t.common.issues);return this._error=r,this._error}}};function pZ(t){if(!t)return{};let{errorMap:r,invalid_type_error:i,required_error:n,description:o}=t;if(r&&(i||n))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return r?{errorMap:r,description:o}:{errorMap:(r,o)=>{let{message:a}=t;return"invalid_enum_value"===r.code?{message:a??o.defaultError}:void 0===o.data?{message:a??n??o.defaultError}:"invalid_type"!==r.code?{message:o.defaultError}:{message:a??i??o.defaultError}},description:o}}class pU{get description(){return this._def.description}_getType(t){return p$(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:p$(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new pq,ctx:{common:t.parent.common,data:t.data,parsedType:p$(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(pN(r))throw Error("Synchronous parse encountered promise.");return r}_parseAsync(t){return Promise.resolve(this._parse(t))}parse(t,r){let i=this.safeParse(t,r);if(i.success)return i.data;throw i.error}safeParse(t,r){let i={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:p$(t)},n=this._parseSync({data:t,path:i.path,parent:i});return pM(i,n)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:p$(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:r});return"valid"===i.status?{value:i.value}:{issues:r.common.issues}}catch(t){t?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(t=>"valid"===t.status?{value:t.value}:{issues:r.common.issues})}async parseAsync(t,r){let i=await this.safeParseAsync(t,r);if(i.success)return i.data;throw i.error}async safeParseAsync(t,r){let i={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:p$(t)},n=this._parse({data:t,path:i.path,parent:i});return pM(i,await (pN(n)?n:Promise.resolve(n)))}refine(t,r){return this._refinement((i,n)=>{let o=t(i),a=()=>n.addIssue({code:pT.custom,..."string"==typeof r||void 0===r?{message:r}:"function"==typeof r?r(i):r});return"undefined"!=typeof Promise&&o instanceof Promise?o.then(t=>!!t||(a(),!1)):!!o||(a(),!1)})}refinement(t,r){return this._refinement((i,n)=>!!t(i)||(n.addIssue("function"==typeof r?r(i,n):r),!1))}_refinement(t){return new mk({schema:this,typeName:M.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:t=>this["~validate"](t)}}optional(){return mx.create(this,this._def)}nullable(){return mC.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ms.create(this)}promise(){return mR.create(this,this._def)}or(t){return mc.create([this,t],this._def)}and(t){return mp.create(this,t,this._def)}transform(t){return new mk({...pZ(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){return new m$({...pZ(this._def),innerType:this,defaultValue:"function"==typeof t?t:()=>t,typeName:M.ZodDefault})}brand(){return new mE({typeName:M.ZodBranded,type:this,...pZ(this._def)})}catch(t){return new mT({...pZ(this._def),innerType:this,catchValue:"function"==typeof t?t:()=>t,typeName:M.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return mO.create(this,t)}readonly(){return mI.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let pF=/^c[^\s-]{8,}$/i,pH=/^[0-9a-z]+$/,pD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pV=/^[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,pJ=/^[a-z0-9_-]{21}$/i,pB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pW=/^[-+]?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)?)??$/,pG=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,pK=/^(?:(?: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])$/,pY=/^(?:(?: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])$/,pX=/^(([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]))$/,pQ=/^(([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])$/,p0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,p1=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,p2="((\\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])))",p9=RegExp(`^${p2}$`);function p4(t){let r="[0-5]\\d";t.precision?r=`${r}\\.\\d{${t.precision}}`:null==t.precision&&(r=`${r}(\\.\\d+)?`);let i=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${r})${i}`}class p5 extends pU{_parse(t){var r,i,n,o;let a;if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==pC.string){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.string,received:r.parsedType}),pj}let s=new pq;for(let l of this._def.checks)if("min"===l.kind)t.data.length<l.value&&(pI(a=this._getOrReturnCtx(t,a),{code:pT.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("max"===l.kind)t.data.length>l.value&&(pI(a=this._getOrReturnCtx(t,a),{code:pT.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("length"===l.kind){let r=t.data.length>l.value,i=t.data.length<l.value;(r||i)&&(a=this._getOrReturnCtx(t,a),r?pI(a,{code:pT.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):i&&pI(a,{code:pT.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),s.dirty())}else if("email"===l.kind)pG.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"email",code:pT.invalid_string,message:l.message}),s.dirty());else if("emoji"===l.kind)p||(p=RegExp("^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),p.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"emoji",code:pT.invalid_string,message:l.message}),s.dirty());else if("uuid"===l.kind)pV.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"uuid",code:pT.invalid_string,message:l.message}),s.dirty());else if("nanoid"===l.kind)pJ.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"nanoid",code:pT.invalid_string,message:l.message}),s.dirty());else if("cuid"===l.kind)pF.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"cuid",code:pT.invalid_string,message:l.message}),s.dirty());else if("cuid2"===l.kind)pH.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"cuid2",code:pT.invalid_string,message:l.message}),s.dirty());else if("ulid"===l.kind)pD.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"ulid",code:pT.invalid_string,message:l.message}),s.dirty());else if("url"===l.kind)try{new URL(t.data)}catch{pI(a=this._getOrReturnCtx(t,a),{validation:"url",code:pT.invalid_string,message:l.message}),s.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"regex",code:pT.invalid_string,message:l.message}),s.dirty())):"trim"===l.kind?t.data=t.data.trim():"includes"===l.kind?t.data.includes(l.value,l.position)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),s.dirty()):"toLowerCase"===l.kind?t.data=t.data.toLowerCase():"toUpperCase"===l.kind?t.data=t.data.toUpperCase():"startsWith"===l.kind?t.data.startsWith(l.value)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:{startsWith:l.value},message:l.message}),s.dirty()):"endsWith"===l.kind?t.data.endsWith(l.value)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:{endsWith:l.value},message:l.message}),s.dirty()):"datetime"===l.kind?(function(t){let r=`${p2}T${p4(t)}`,i=[];return i.push(t.local?"Z?":"Z"),t.offset&&i.push("([+-]\\d{2}:?\\d{2})"),r=`${r}(${i.join("|")})`,RegExp(`^${r}$`)})(l).test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:"datetime",message:l.message}),s.dirty()):"date"===l.kind?p9.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:"date",message:l.message}),s.dirty()):"time"===l.kind?RegExp(`^${p4(l)}$`).test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:"time",message:l.message}),s.dirty()):"duration"===l.kind?pW.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"duration",code:pT.invalid_string,message:l.message}),s.dirty()):"ip"===l.kind?(r=t.data,!(("v4"===(i=l.version)||!i)&&pK.test(r)||("v6"===i||!i)&&pX.test(r))&&1&&(pI(a=this._getOrReturnCtx(t,a),{validation:"ip",code:pT.invalid_string,message:l.message}),s.dirty())):"jwt"===l.kind?!function(t,r){if(!pB.test(t))return!1;try{let[i]=t.split(".");if(!i)return!1;let n=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),o=JSON.parse(atob(n));if("object"!=typeof o||null===o||"typ"in o&&o?.typ!=="JWT"||!o.alg||r&&o.alg!==r)return!1;return!0}catch{return!1}}(t.data,l.alg)&&(pI(a=this._getOrReturnCtx(t,a),{validation:"jwt",code:pT.invalid_string,message:l.message}),s.dirty()):"cidr"===l.kind?(n=t.data,!(("v4"===(o=l.version)||!o)&&pY.test(n)||("v6"===o||!o)&&pQ.test(n))&&1&&(pI(a=this._getOrReturnCtx(t,a),{validation:"cidr",code:pT.invalid_string,message:l.message}),s.dirty())):"base64"===l.kind?p0.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"base64",code:pT.invalid_string,message:l.message}),s.dirty()):"base64url"===l.kind?p1.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"base64url",code:pT.invalid_string,message:l.message}),s.dirty()):L.assertNever(l);return{status:s.value,value:t.data}}_regex(t,r,i){return this.refinement(r=>t.test(r),{validation:r,code:pT.invalid_string,...z.errToObj(i)})}_addCheck(t){return new p5({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...z.errToObj(t)})}url(t){return this._addCheck({kind:"url",...z.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...z.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...z.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...z.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...z.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...z.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...z.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...z.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...z.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...z.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...z.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...z.errToObj(t)})}datetime(t){return"string"==typeof t?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:void 0===t?.precision?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...z.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return"string"==typeof t?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:void 0===t?.precision?null:t?.precision,...z.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...z.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...z.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...z.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...z.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...z.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...z.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...z.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...z.errToObj(r)})}nonempty(t){return this.min(1,z.errToObj(t))}trim(){return new p5({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new p5({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new p5({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>"datetime"===t.kind)}get isDate(){return!!this._def.checks.find(t=>"date"===t.kind)}get isTime(){return!!this._def.checks.find(t=>"time"===t.kind)}get isDuration(){return!!this._def.checks.find(t=>"duration"===t.kind)}get isEmail(){return!!this._def.checks.find(t=>"email"===t.kind)}get isURL(){return!!this._def.checks.find(t=>"url"===t.kind)}get isEmoji(){return!!this._def.checks.find(t=>"emoji"===t.kind)}get isUUID(){return!!this._def.checks.find(t=>"uuid"===t.kind)}get isNANOID(){return!!this._def.checks.find(t=>"nanoid"===t.kind)}get isCUID(){return!!this._def.checks.find(t=>"cuid"===t.kind)}get isCUID2(){return!!this._def.checks.find(t=>"cuid2"===t.kind)}get isULID(){return!!this._def.checks.find(t=>"ulid"===t.kind)}get isIP(){return!!this._def.checks.find(t=>"ip"===t.kind)}get isCIDR(){return!!this._def.checks.find(t=>"cidr"===t.kind)}get isBase64(){return!!this._def.checks.find(t=>"base64"===t.kind)}get isBase64url(){return!!this._def.checks.find(t=>"base64url"===t.kind)}get minLength(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}p5.create=t=>new p5({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...pZ(t)});class p3 extends pU{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){let r;if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==pC.number){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.number,received:r.parsedType}),pj}let i=new pq;for(let n of this._def.checks)"int"===n.kind?L.isInteger(t.data)||(pI(r=this._getOrReturnCtx(t,r),{code:pT.invalid_type,expected:"integer",received:"float",message:n.message}),i.dirty()):"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"multipleOf"===n.kind?0!==function(t,r){let i=(t.toString().split(".")[1]||"").length,n=(r.toString().split(".")[1]||"").length,o=i>n?i:n;return Number.parseInt(t.toFixed(o).replace(".",""))%Number.parseInt(r.toFixed(o).replace(".",""))/10**o}(t.data,n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):"finite"===n.kind?Number.isFinite(t.data)||(pI(r=this._getOrReturnCtx(t,r),{code:pT.not_finite,message:n.message}),i.dirty()):L.assertNever(n);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,z.toString(r))}gt(t,r){return this.setLimit("min",t,!1,z.toString(r))}lte(t,r){return this.setLimit("max",t,!0,z.toString(r))}lt(t,r){return this.setLimit("max",t,!1,z.toString(r))}setLimit(t,r,i,n){return new p3({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:z.toString(n)}]})}_addCheck(t){return new p3({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:z.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:z.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:z.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>"int"===t.kind||"multipleOf"===t.kind&&L.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let i of this._def.checks)if("finite"===i.kind||"int"===i.kind||"multipleOf"===i.kind)return!0;else"min"===i.kind?(null===r||i.value>r)&&(r=i.value):"max"===i.kind&&(null===t||i.value<t)&&(t=i.value);return Number.isFinite(r)&&Number.isFinite(t)}}p3.create=t=>new p3({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...pZ(t)});class p6 extends pU{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){let r;if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==pC.bigint)return this._getInvalidInput(t);let i=new pq;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):"multipleOf"===n.kind?t.data%n.value!==BigInt(0)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):L.assertNever(n);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.bigint,received:r.parsedType}),pj}gte(t,r){return this.setLimit("min",t,!0,z.toString(r))}gt(t,r){return this.setLimit("min",t,!1,z.toString(r))}lte(t,r){return this.setLimit("max",t,!0,z.toString(r))}lt(t,r){return this.setLimit("max",t,!1,z.toString(r))}setLimit(t,r,i,n){return new p6({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:z.toString(n)}]})}_addCheck(t){return new p6({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:z.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}p6.create=t=>new p6({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...pZ(t)});class p7 extends pU{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==pC.boolean){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.boolean,received:r.parsedType}),pj}return pL(t.data)}}p7.create=t=>new p7({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...pZ(t)});class p8 extends pU{_parse(t){let r;if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==pC.date){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.date,received:r.parsedType}),pj}if(Number.isNaN(t.data.getTime()))return pI(this._getOrReturnCtx(t),{code:pT.invalid_date}),pj;let i=new pq;for(let n of this._def.checks)"min"===n.kind?t.data.getTime()<n.value&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):"max"===n.kind?t.data.getTime()>n.value&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):L.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new p8({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:z.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:z.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return null!=t?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return null!=t?new Date(t):null}}p8.create=t=>new p8({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...pZ(t)});class me extends pU{_parse(t){if(this._getType(t)!==pC.symbol){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.symbol,received:r.parsedType}),pj}return pL(t.data)}}me.create=t=>new me({typeName:M.ZodSymbol,...pZ(t)});class mt extends pU{_parse(t){if(this._getType(t)!==pC.undefined){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.undefined,received:r.parsedType}),pj}return pL(t.data)}}mt.create=t=>new mt({typeName:M.ZodUndefined,...pZ(t)});class mr extends pU{_parse(t){if(this._getType(t)!==pC.null){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.null,received:r.parsedType}),pj}return pL(t.data)}}mr.create=t=>new mr({typeName:M.ZodNull,...pZ(t)});class mi extends pU{constructor(){super(...arguments),this._any=!0}_parse(t){return pL(t.data)}}mi.create=t=>new mi({typeName:M.ZodAny,...pZ(t)});class mn extends pU{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pL(t.data)}}mn.create=t=>new mn({typeName:M.ZodUnknown,...pZ(t)});class mo extends pU{_parse(t){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.never,received:r.parsedType}),pj}}mo.create=t=>new mo({typeName:M.ZodNever,...pZ(t)});class ma extends pU{_parse(t){if(this._getType(t)!==pC.undefined){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.void,received:r.parsedType}),pj}return pL(t.data)}}ma.create=t=>new ma({typeName:M.ZodVoid,...pZ(t)});class ms extends pU{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),n=this._def;if(r.parsedType!==pC.array)return pI(r,{code:pT.invalid_type,expected:pC.array,received:r.parsedType}),pj;if(null!==n.exactLength){let t=r.data.length>n.exactLength.value,o=r.data.length<n.exactLength.value;(t||o)&&(pI(r,{code:t?pT.too_big:pT.too_small,minimum:o?n.exactLength.value:void 0,maximum:t?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(null!==n.minLength&&r.data.length<n.minLength.value&&(pI(r,{code:pT.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),null!==n.maxLength&&r.data.length>n.maxLength.value&&(pI(r,{code:pT.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),r.common.async)return Promise.all([...r.data].map((t,i)=>n.type._parseAsync(new pz(r,t,r.path,i)))).then(t=>pq.mergeArray(i,t));let o=[...r.data].map((t,i)=>n.type._parseSync(new pz(r,t,r.path,i)));return pq.mergeArray(i,o)}get element(){return this._def.type}min(t,r){return new ms({...this._def,minLength:{value:t,message:z.toString(r)}})}max(t,r){return new ms({...this._def,maxLength:{value:t,message:z.toString(r)}})}length(t,r){return new ms({...this._def,exactLength:{value:t,message:z.toString(r)}})}nonempty(t){return this.min(1,t)}}ms.create=(t,r)=>new ms({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...pZ(r)});class ml extends pU{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let t=this._def.shape(),r=L.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==pC.object){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.object,received:r.parsedType}),pj}let{status:r,ctx:i}=this._processInputParams(t),{shape:n,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof mo&&"strip"===this._def.unknownKeys))for(let t in i.data)o.includes(t)||a.push(t);let s=[];for(let t of o){let r=n[t],o=i.data[t];s.push({key:{status:"valid",value:t},value:r._parse(new pz(i,o,i.path,t)),alwaysSet:t in i.data})}if(this._def.catchall instanceof mo){let t=this._def.unknownKeys;if("passthrough"===t)for(let t of a)s.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===t)a.length>0&&(pI(i,{code:pT.unrecognized_keys,keys:a}),r.dirty());else if("strip"===t);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let t=this._def.catchall;for(let r of a){let n=i.data[r];s.push({key:{status:"valid",value:r},value:t._parse(new pz(i,n,i.path,r)),alwaysSet:r in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let t=[];for(let r of s){let i=await r.key,n=await r.value;t.push({key:i,value:n,alwaysSet:r.alwaysSet})}return t}).then(t=>pq.mergeObjectSync(r,t)):pq.mergeObjectSync(r,s)}get shape(){return this._def.shape()}strict(t){return z.errToObj,new ml({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(r,i)=>{let n=this._def.errorMap?.(r,i).message??i.defaultError;return"unrecognized_keys"===r.code?{message:z.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new ml({...this._def,unknownKeys:"strip"})}passthrough(){return new ml({...this._def,unknownKeys:"passthrough"})}extend(t){return new ml({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ml({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new ml({...this._def,catchall:t})}pick(t){let r={};for(let i of L.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new ml({...this._def,shape:()=>r})}omit(t){let r={};for(let i of L.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new ml({...this._def,shape:()=>r})}deepPartial(){return function t(r){if(r instanceof ml){let i={};for(let n in r.shape){let o=r.shape[n];i[n]=mx.create(t(o))}return new ml({...r._def,shape:()=>i})}if(r instanceof ms)return new ms({...r._def,type:t(r.element)});if(r instanceof mx)return mx.create(t(r.unwrap()));if(r instanceof mC)return mC.create(t(r.unwrap()));if(r instanceof mm)return mm.create(r.items.map(r=>t(r)));else return r}(this)}partial(t){let r={};for(let i of L.objectKeys(this.shape)){let n=this.shape[i];t&&!t[i]?r[i]=n:r[i]=n.optional()}return new ml({...this._def,shape:()=>r})}required(t){let r={};for(let i of L.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let t=this.shape[i];for(;t instanceof mx;)t=t._def.innerType;r[i]=t}return new ml({...this._def,shape:()=>r})}keyof(){return mb(L.objectKeys(this.shape))}}ml.create=(t,r)=>new ml({shape:()=>t,unknownKeys:"strip",catchall:mo.create(),typeName:M.ZodObject,...pZ(r)}),ml.strictCreate=(t,r)=>new ml({shape:()=>t,unknownKeys:"strict",catchall:mo.create(),typeName:M.ZodObject,...pZ(r)}),ml.lazycreate=(t,r)=>new ml({shape:t,unknownKeys:"strip",catchall:mo.create(),typeName:M.ZodObject,...pZ(r)});class mc extends pU{_parse(t){let{ctx:r}=this._processInputParams(t),i=this._def.options;if(r.common.async)return Promise.all(i.map(async t=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await t._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(function(t){for(let r of t)if("valid"===r.result.status)return r.result;for(let i of t)if("dirty"===i.result.status)return r.common.issues.push(...i.ctx.common.issues),i.result;let i=t.map(t=>new pP(t.ctx.common.issues));return pI(r,{code:pT.invalid_union,unionErrors:i}),pj});{let t,n=[];for(let o of i){let i={...r,common:{...r.common,issues:[]},parent:null},a=o._parseSync({data:r.data,path:r.path,parent:i});if("valid"===a.status)return a;"dirty"!==a.status||t||(t={result:a,ctx:i}),i.common.issues.length&&n.push(i.common.issues)}if(t)return r.common.issues.push(...t.ctx.common.issues),t.result;let o=n.map(t=>new pP(t));return pI(r,{code:pT.invalid_union,unionErrors:o}),pj}}get options(){return this._def.options}}mc.create=(t,r)=>new mc({options:t,typeName:M.ZodUnion,...pZ(r)});let mu=t=>{if(t instanceof mv)return mu(t.schema);if(t instanceof mk)return mu(t.innerType());if(t instanceof m_)return[t.value];if(t instanceof mS)return t.options;if(t instanceof mw)return L.objectValues(t.enum);else if(t instanceof m$)return mu(t._def.innerType);else if(t instanceof mt)return[void 0];else if(t instanceof mr)return[null];else if(t instanceof mx)return[void 0,...mu(t.unwrap())];else if(t instanceof mC)return[null,...mu(t.unwrap())];else if(t instanceof mE)return mu(t.unwrap());else if(t instanceof mI)return mu(t.unwrap());else if(t instanceof mT)return mu(t._def.innerType);else return[]};class md extends pU{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==pC.object)return pI(r,{code:pT.invalid_type,expected:pC.object,received:r.parsedType}),pj;let i=this.discriminator,n=r.data[i],o=this.optionsMap.get(n);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}):(pI(r,{code:pT.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),pj)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,i){let n=new Map;for(let i of r){let r=mu(i.shape[t]);if(!r.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of r){if(n.has(o))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);n.set(o,i)}}return new md({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...pZ(i)})}}class mp extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=(t,n)=>{if("aborted"===t.status||"aborted"===n.status)return pj;let o=function t(r,i){let n=p$(r),o=p$(i);if(r===i)return{valid:!0,data:r};if(n===pC.object&&o===pC.object){let n=L.objectKeys(i),o=L.objectKeys(r).filter(t=>-1!==n.indexOf(t)),a={...r,...i};for(let n of(Object.prototype.hasOwnProperty.call(a,"__proto__")&&delete a.__proto__,o)){if("__proto__"===n)continue;let o=t(r[n],i[n]);if(!o.valid)return{valid:!1};a[n]=o.data}return{valid:!0,data:a}}if(n===pC.array&&o===pC.array){if(r.length!==i.length)return{valid:!1};let n=[];for(let o=0;o<r.length;o++){let a=t(r[o],i[o]);if(!a.valid)return{valid:!1};n.push(a.data)}return{valid:!0,data:n}}if(n===pC.date&&o===pC.date&&+r==+i)return{valid:!0,data:r};return{valid:!1}}(t.value,n.value);return o.valid?(("dirty"===t.status||"dirty"===n.status)&&r.dirty(),{status:r.value,value:o.data}):(pI(i,{code:pT.invalid_intersection_types}),pj)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([t,r])=>n(t,r)):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}mp.create=(t,r,i)=>new mp({left:t,right:r,typeName:M.ZodIntersection,...pZ(i)});class mm extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==pC.array)return pI(i,{code:pT.invalid_type,expected:pC.array,received:i.parsedType}),pj;if(i.data.length<this._def.items.length)return pI(i,{code:pT.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),pj;!this._def.rest&&i.data.length>this._def.items.length&&(pI(i,{code:pT.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let n=[...i.data].map((t,r)=>{let n=this._def.items[r]||this._def.rest;return n?n._parse(new pz(i,t,i.path,r)):null}).filter(t=>!!t);return i.common.async?Promise.all(n).then(t=>pq.mergeArray(r,t)):pq.mergeArray(r,n)}get items(){return this._def.items}rest(t){return new mm({...this._def,rest:t})}}mm.create=(t,r)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new mm({items:t,typeName:M.ZodTuple,rest:null,...pZ(r)})};class mh extends pU{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==pC.object)return pI(i,{code:pT.invalid_type,expected:pC.object,received:i.parsedType}),pj;let n=[],o=this._def.keyType,a=this._def.valueType;for(let t in i.data)n.push({key:o._parse(new pz(i,t,i.path,t)),value:a._parse(new pz(i,i.data[t],i.path,t)),alwaysSet:t in i.data});return i.common.async?pq.mergeObjectAsync(r,n):pq.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,i){return new mh(r instanceof pU?{keyType:t,valueType:r,typeName:M.ZodRecord,...pZ(i)}:{keyType:p5.create(),valueType:t,typeName:M.ZodRecord,...pZ(r)})}}class mf extends pU{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==pC.map)return pI(i,{code:pT.invalid_type,expected:pC.map,received:i.parsedType}),pj;let n=this._def.keyType,o=this._def.valueType,a=[...i.data.entries()].map(([t,r],a)=>({key:n._parse(new pz(i,t,i.path,[a,"key"])),value:o._parse(new pz(i,r,i.path,[a,"value"]))}));if(i.common.async){let t=new Map;return Promise.resolve().then(async()=>{for(let i of a){let n=await i.key,o=await i.value;if("aborted"===n.status||"aborted"===o.status)return pj;("dirty"===n.status||"dirty"===o.status)&&r.dirty(),t.set(n.value,o.value)}return{status:r.value,value:t}})}{let t=new Map;for(let i of a){let n=i.key,o=i.value;if("aborted"===n.status||"aborted"===o.status)return pj;("dirty"===n.status||"dirty"===o.status)&&r.dirty(),t.set(n.value,o.value)}return{status:r.value,value:t}}}}mf.create=(t,r,i)=>new mf({valueType:r,keyType:t,typeName:M.ZodMap,...pZ(i)});class mg extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==pC.set)return pI(i,{code:pT.invalid_type,expected:pC.set,received:i.parsedType}),pj;let n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(pI(i,{code:pT.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),null!==n.maxSize&&i.data.size>n.maxSize.value&&(pI(i,{code:pT.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let o=this._def.valueType;function a(t){let i=new Set;for(let n of t){if("aborted"===n.status)return pj;"dirty"===n.status&&r.dirty(),i.add(n.value)}return{status:r.value,value:i}}let s=[...i.data.values()].map((t,r)=>o._parse(new pz(i,t,i.path,r)));return i.common.async?Promise.all(s).then(t=>a(t)):a(s)}min(t,r){return new mg({...this._def,minSize:{value:t,message:z.toString(r)}})}max(t,r){return new mg({...this._def,maxSize:{value:t,message:z.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}mg.create=(t,r)=>new mg({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...pZ(r)});class my extends pU{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==pC.function)return pI(r,{code:pT.invalid_type,expected:pC.function,received:r.parsedType}),pj;function i(t,i){return pO({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pE,pE].filter(t=>!!t),issueData:{code:pT.invalid_arguments,argumentsError:i}})}function n(t,i){return pO({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pE,pE].filter(t=>!!t),issueData:{code:pT.invalid_return_type,returnTypeError:i}})}let o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof mR){let t=this;return pL(async function(...r){let s=new pP([]),l=await t._def.args.parseAsync(r,o).catch(t=>{throw s.addIssue(i(r,t)),s}),c=await Reflect.apply(a,this,l);return await t._def.returns._def.type.parseAsync(c,o).catch(t=>{throw s.addIssue(n(c,t)),s})})}{let t=this;return pL(function(...r){let s=t._def.args.safeParse(r,o);if(!s.success)throw new pP([i(r,s.error)]);let l=Reflect.apply(a,this,s.data),c=t._def.returns.safeParse(l,o);if(!c.success)throw new pP([n(l,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new my({...this._def,args:mm.create(t).rest(mn.create())})}returns(t){return new my({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new my({args:t||mm.create([]).rest(mn.create()),returns:r||mn.create(),typeName:M.ZodFunction,...pZ(i)})}}class mv extends pU{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})}}mv.create=(t,r)=>new mv({getter:t,typeName:M.ZodLazy,...pZ(r)});class m_ extends pU{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return pI(r,{received:r.data,code:pT.invalid_literal,expected:this._def.value}),pj}return{status:"valid",value:t.data}}get value(){return this._def.value}}function mb(t,r){return new mS({values:t,typeName:M.ZodEnum,...pZ(r)})}m_.create=(t,r)=>new m_({value:t,typeName:M.ZodLiteral,...pZ(r)});class mS extends pU{_parse(t){if("string"!=typeof t.data){let r=this._getOrReturnCtx(t),i=this._def.values;return pI(r,{expected:L.joinValues(i),received:r.parsedType,code:pT.invalid_type}),pj}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),i=this._def.values;return pI(r,{received:r.data,code:pT.invalid_enum_value,options:i}),pj}return pL(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 mS.create(t,{...this._def,...r})}exclude(t,r=this._def){return mS.create(this.options.filter(r=>!t.includes(r)),{...this._def,...r})}}mS.create=mb;class mw extends pU{_parse(t){let r=L.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==pC.string&&i.parsedType!==pC.number){let t=L.objectValues(r);return pI(i,{expected:L.joinValues(t),received:i.parsedType,code:pT.invalid_type}),pj}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let t=L.objectValues(r);return pI(i,{received:i.data,code:pT.invalid_enum_value,options:t}),pj}return pL(t.data)}get enum(){return this._def.values}}mw.create=(t,r)=>new mw({values:t,typeName:M.ZodNativeEnum,...pZ(r)});class mR extends pU{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==pC.promise&&!1===r.common.async?(pI(r,{code:pT.invalid_type,expected:pC.promise,received:r.parsedType}),pj):pL((r.parsedType===pC.promise?r.data:Promise.resolve(r.data)).then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}}mR.create=(t,r)=>new mR({type:t,typeName:M.ZodPromise,...pZ(r)});class mk extends pU{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=this._def.effect||null,o={addIssue:t=>{pI(i,t),t.fatal?r.abort():r.dirty()},get path(){return i.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===n.type){let t=n.transform(i.data,o);if(i.common.async)return Promise.resolve(t).then(async t=>{if("aborted"===r.value)return pj;let n=await this._def.schema._parseAsync({data:t,path:i.path,parent:i});return"aborted"===n.status?pj:"dirty"===n.status||"dirty"===r.value?pA(n.value):n});{if("aborted"===r.value)return pj;let n=this._def.schema._parseSync({data:t,path:i.path,parent:i});return"aborted"===n.status?pj:"dirty"===n.status||"dirty"===r.value?pA(n.value):n}}if("refinement"===n.type){let t=t=>{let r=n.refinement(t,o);if(i.common.async)return Promise.resolve(r);if(r instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return t};if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(i=>"aborted"===i.status?pj:("dirty"===i.status&&r.dirty(),t(i.value).then(()=>({status:r.value,value:i.value}))));{let n=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===n.status?pj:("dirty"===n.status&&r.dirty(),t(n.value),{status:r.value,value:n.value})}}if("transform"===n.type)if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(t=>"valid"!==t.status?pj:Promise.resolve(n.transform(t.value,o)).then(t=>({status:r.value,value:t})));else{let t=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if("valid"!==t.status)return pj;let a=n.transform(t.value,o);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}L.assertNever(n)}}mk.create=(t,r,i)=>new mk({schema:t,typeName:M.ZodEffects,effect:r,...pZ(i)}),mk.createWithPreprocess=(t,r,i)=>new mk({schema:r,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...pZ(i)});class mx extends pU{_parse(t){return this._getType(t)===pC.undefined?pL(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mx.create=(t,r)=>new mx({innerType:t,typeName:M.ZodOptional,...pZ(r)});class mC extends pU{_parse(t){return this._getType(t)===pC.null?pL(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mC.create=(t,r)=>new mC({innerType:t,typeName:M.ZodNullable,...pZ(r)});class m$ extends pU{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===pC.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}m$.create=(t,r)=>new m$({innerType:t,typeName:M.ZodDefault,defaultValue:"function"==typeof r.default?r.default:()=>r.default,...pZ(r)});class mT extends pU{_parse(t){let{ctx:r}=this._processInputParams(t),i={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return pN(n)?n.then(t=>({status:"valid",value:"valid"===t.status?t.value:this._def.catchValue({get error(){return new pP(i.common.issues)},input:i.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new pP(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}mT.create=(t,r)=>new mT({innerType:t,typeName:M.ZodCatch,catchValue:"function"==typeof r.catch?r.catch:()=>r.catch,...pZ(r)});class mP extends pU{_parse(t){if(this._getType(t)!==pC.nan){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.nan,received:r.parsedType}),pj}return{status:"valid",value:t.data}}}mP.create=t=>new mP({typeName:M.ZodNaN,...pZ(t)}),Symbol("zod_brand");class mE extends pU{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return this._def.type._parse({data:i,path:r.path,parent:r})}unwrap(){return this._def.type}}class mO extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let t=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?pj:"dirty"===t.status?(r.dirty(),pA(t.value)):this._def.out._parseAsync({data:t.value,path:i.path,parent:i})})();{let t=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?pj:"dirty"===t.status?(r.dirty(),{status:"dirty",value:t.value}):this._def.out._parseSync({data:t.value,path:i.path,parent:i})}}static create(t,r){return new mO({in:t,out:r,typeName:M.ZodPipeline})}}class mI extends pU{_parse(t){let r=this._def.innerType._parse(t),i=t=>("valid"===t.status&&(t.value=Object.freeze(t.value)),t);return pN(r)?r.then(t=>i(t)):i(r)}unwrap(){return this._def.innerType}}mI.create=(t,r)=>new mI({innerType:t,typeName:M.ZodReadonly,...pZ(r)}),ml.lazycreate,(I=M||(M={})).ZodString="ZodString",I.ZodNumber="ZodNumber",I.ZodNaN="ZodNaN",I.ZodBigInt="ZodBigInt",I.ZodBoolean="ZodBoolean",I.ZodDate="ZodDate",I.ZodSymbol="ZodSymbol",I.ZodUndefined="ZodUndefined",I.ZodNull="ZodNull",I.ZodAny="ZodAny",I.ZodUnknown="ZodUnknown",I.ZodNever="ZodNever",I.ZodVoid="ZodVoid",I.ZodArray="ZodArray",I.ZodObject="ZodObject",I.ZodUnion="ZodUnion",I.ZodDiscriminatedUnion="ZodDiscriminatedUnion",I.ZodIntersection="ZodIntersection",I.ZodTuple="ZodTuple",I.ZodRecord="ZodRecord",I.ZodMap="ZodMap",I.ZodSet="ZodSet",I.ZodFunction="ZodFunction",I.ZodLazy="ZodLazy",I.ZodLiteral="ZodLiteral",I.ZodEnum="ZodEnum",I.ZodEffects="ZodEffects",I.ZodNativeEnum="ZodNativeEnum",I.ZodOptional="ZodOptional",I.ZodNullable="ZodNullable",I.ZodDefault="ZodDefault",I.ZodCatch="ZodCatch",I.ZodPromise="ZodPromise",I.ZodBranded="ZodBranded",I.ZodPipeline="ZodPipeline",I.ZodReadonly="ZodReadonly",p5.create,p3.create,mP.create,p6.create,p7.create,p8.create,me.create,mt.create,mr.create,mi.create,mn.create,mo.create,ma.create,ms.create,ml.create,ml.strictCreate,mc.create,md.create,mp.create,mm.create,mh.create,mf.create,mg.create,my.create,mv.create,m_.create,mS.create,mw.create,mR.create,mk.create,mx.create,mC.create,mk.createWithPreprocess,mO.create;let mq=(t,r)=>{let i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];i++);return[(t.length-i).toString(),...r.slice(i)].join("/")};function mj(t){if("openAi"!==t.target)return{};let r=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===t.$refStrategy?mq(r,t.currentPath):r.join("/")}}function mA(t,r,i,n){n?.errorMessages&&i&&(t.errorMessage={...t.errorMessage,[r]:i})}function mL(t,r,i,n,o){t[r]=i,mA(t,r,n,o)}function mN(t,r){return m4(t.type._def,r)}let mz=/^[cC][^\s-]{8,}$/,mM=/^[0-9a-z]+$/,mZ=/^[0-9A-HJKMNP-TV-Z]{26}$/,mU=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,mF=()=>(void 0===k&&(k=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),k),mH=/^(?:(?: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])$/,mD=/^(([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])$/,mV=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mJ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mB=/^[a-zA-Z0-9_-]{21}$/,mW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function mG(t,r){let i={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":mL(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r);break;case"max":mL(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"email":switch(r.emailStrategy){case"format:email":mX(i,"email",n.message,r);break;case"format:idn-email":mX(i,"idn-email",n.message,r);break;case"pattern:zod":mQ(i,mU,n.message,r)}break;case"url":mX(i,"uri",n.message,r);break;case"uuid":mX(i,"uuid",n.message,r);break;case"regex":mQ(i,n.regex,n.message,r);break;case"cuid":mQ(i,mz,n.message,r);break;case"cuid2":mQ(i,mM,n.message,r);break;case"startsWith":mQ(i,RegExp(`^${mK(n.value,r)}`),n.message,r);break;case"endsWith":mQ(i,RegExp(`${mK(n.value,r)}$`),n.message,r);break;case"datetime":mX(i,"date-time",n.message,r);break;case"date":mX(i,"date",n.message,r);break;case"time":mX(i,"time",n.message,r);break;case"duration":mX(i,"duration",n.message,r);break;case"length":mL(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r),mL(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"includes":mQ(i,RegExp(mK(n.value,r)),n.message,r);break;case"ip":"v6"!==n.version&&mX(i,"ipv4",n.message,r),"v4"!==n.version&&mX(i,"ipv6",n.message,r);break;case"base64url":mQ(i,mJ,n.message,r);break;case"jwt":mQ(i,mW,n.message,r);break;case"cidr":"v6"!==n.version&&mQ(i,mH,n.message,r),"v4"!==n.version&&mQ(i,mD,n.message,r);break;case"emoji":mQ(i,mF(),n.message,r);break;case"ulid":mQ(i,mZ,n.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":mX(i,"binary",n.message,r);break;case"contentEncoding:base64":mL(i,"contentEncoding","base64",n.message,r);break;case"pattern:zod":mQ(i,mV,n.message,r)}break;case"nanoid":mQ(i,mB,n.message,r)}return i}function mK(t,r){return"escape"===r.patternStrategy?function(t){let r="";for(let i=0;i<t.length;i++)mY.has(t[i])||(r+="\\"),r+=t[i];return r}(t):t}let mY=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mX(t,r,i,n){t.format||t.anyOf?.some(t=>t.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,0===Object.keys(t.errorMessage).length&&delete t.errorMessage)),t.anyOf.push({format:r,...i&&n.errorMessages&&{errorMessage:{format:i}}})):mL(t,"format",r,i,n)}function mQ(t,r,i,n){t.pattern||t.allOf?.some(t=>t.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,0===Object.keys(t.errorMessage).length&&delete t.errorMessage)),t.allOf.push({pattern:m0(r,n),...i&&n.errorMessages&&{errorMessage:{pattern:i}}})):mL(t,"pattern",m0(r,n),i,n)}function m0(t,r){if(!r.applyRegexFlags||!t.flags)return t.source;let i={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=i.i?t.source.toLowerCase():t.source,o="",a=!1,s=!1,l=!1;for(let t=0;t<n.length;t++){if(a){o+=n[t],a=!1;continue}if(i.i){if(s){if(n[t].match(/[a-z]/)){l?(o+=n[t],o+=`${n[t-2]}-${n[t]}`.toUpperCase(),l=!1):"-"===n[t+1]&&n[t+2]?.match(/[a-z]/)?(o+=n[t],l=!0):o+=`${n[t]}${n[t].toUpperCase()}`;continue}}else if(n[t].match(/[a-z]/)){o+=`[${n[t]}${n[t].toUpperCase()}]`;continue}}if(i.m){if("^"===n[t]){o+=`(^|(?<=[\r
73
+ `,t.enqueue(r.encode(o)),!0}catch(t){return this.onerror?.(t),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),Response.json({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 i,n,o,a,s,l=t.headers.get("accept");if(!l?.includes("application/json")||!l.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!uZ(t.headers.get("content-type")))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");if(r?.parsedBody===void 0)try{let r=await dj(t,this._maxRequestBodySize);if(r.tooLarge){let t=dI(this._maxRequestBodySize);return this.onerror?.(Error(t)),this.createJsonErrorResponse(413,-32e3,t)}i=JSON.parse(r.text)}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else i=r.parsedBody;if(Array.isArray(i)&&i.length>100)return this.onerror?.(Error("Invalid Request: Batch must not exceed 100 messages")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Batch must not exceed 100 messages");try{n=Array.isArray(i)?i.map(t=>ad.parse(t)):[ad.parse(i)]}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let c=n.some(t=>aC.safeParse(t).success);if(c){if(this._initialized&&void 0!==this.sessionId)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(n.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),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(!c){let r=this.validateSession(t);if(r)return r;let i=this.validateProtocolVersion(t);if(i)return i}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");try{o=await this._checkScopeChallenge(n,r?.authInfo)}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(500,-32603,"Internal server error")}if(o)return o;if(!n.some(t=>cX(t))){for(let i of n)this.onmessage?.(i,{authInfo:r?.authInfo,request:t});return new Response(null,{status:202})}let u=crypto.randomUUID(),d=n.find(t=>aC.safeParse(t).success),p=d?d.params.protocolVersion:t.headers.get("mcp-protocol-version")??"2025-03-26";if(this._enableJsonResponse)return new Promise(i=>{for(let t of(this._streamMapping.set(u,{resolveJson:i,cleanup:()=>{this._streamMapping.delete(u)}}),n))cX(t)&&this._requestToStreamMapping.set(t.id,u);for(let i of n)this.onmessage?.(i,{authInfo:r?.authInfo,request:t})});let m=new TextEncoder,h=new ReadableStream({start:t=>{a=t},cancel:()=>{void 0!==s&&clearInterval(s),this._streamMapping.get(u)?.controller===a&&this._streamMapping.delete(u)}}),f={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};for(let t of(void 0!==this.sessionId&&(f["mcp-session-id"]=this.sessionId),n))cX(t)&&(this._streamMapping.set(u,{controller:a,encoder:m,cleanup:()=>{void 0!==s&&clearInterval(s),this._streamMapping.delete(u);try{a.close()}catch{}}}),this._requestToStreamMapping.set(t.id,u));for(let i of(await this.writePrimingEvent(a,m,u,p),n)){let n,o;cX(i)&&this._eventStore&&this.supportsEmptySSEData(p)&&(n=()=>{this.closeSSEStream(i.id)},o=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(i,{authInfo:r?.authInfo,request:t,closeSSEStream:n,closeStandaloneSSEStream:o})}return this._streamMapping.get(u)?.controller===a&&(s=this.startKeepAlive(a,m)),new Response(h,{status:200,headers:f})}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(t)})}}async handleDeleteRequest(t){let r=this.validateSession(t);if(r)return r;let i=this.validateProtocolVersion(t);if(i)return i;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(t){if(void 0===this.sessionIdGenerator)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=t.headers.get("mcp-session-id");return r?r!==this.sessionId?(this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")):void 0:(this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required"))}validateProtocolVersion(t){let r=t.headers.get("mcp-protocol-version");if(null!==r&&!this._supportedProtocolVersions.includes(r)){let t=`Bad Request: Unsupported protocol version: ${r} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(Error(t)),this.createJsonErrorResponse(400,-32e3,t)}}async close(){if(!this._closed){for(let{cleanup:t}of(this._closed=!0,this._streamMapping.values()))t();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(t){let r=this._requestToStreamMapping.get(t);if(!r)return;let i=this._streamMapping.get(r);i&&i.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,r){let i=r?.relatedRequestId;if((c0(t)||c1(t))&&(i=t.id),void 0===i){let r;if(c0(t)||c1(t))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");this._eventStore&&(r=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let i=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===i)return;i.controller&&i.encoder&&(void 0===r||!i.replayedEventIds?.has(r))&&this.writeSSEEvent(i.controller,i.encoder,t,r);return}let n=this._requestToStreamMapping.get(i);if(!n)throw Error(`No connection established for request ID: ${String(i)}`);let o=this._streamMapping.get(n);if(!this._enableJsonResponse){let r;this._eventStore&&(r=await this._eventStore.storeEvent(n,t),o=this._streamMapping.get(n)),o?.controller&&o?.encoder&&(void 0===r||!o.replayedEventIds?.has(r))&&this.writeSSEEvent(o.controller,o.encoder,t,r)}if(c0(t)||c1(t)){this._requestResponseMap.set(i,t);let r=[...this._requestToStreamMapping.entries()].filter(([t,r])=>r===n).map(([t])=>t);if(r.every(t=>this._requestResponseMap.has(t))){if(!o){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(i)}`);if(!this._eventStore){for(let t of(this.onerror?.(Error(`Response for request ID ${String(i)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)),r))this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t);return}for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t);return}if(this._enableJsonResponse&&o.resolveJson){let t={"Content-Type":"application/json"};void 0!==this.sessionId&&(t["mcp-session-id"]=this.sessionId);let i=r.map(t=>this._requestResponseMap.get(t));1===i.length?o.resolveJson(Response.json(i[0],{status:200,headers:t})):o.resolveJson(Response.json(i,{status:200,headers:t})),o.cleanup()}else o.cleanup();for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t)}}}};function dL(t){if(null===t||"object"!=typeof t||Array.isArray(t))return null;let{method:r,id:i}=t;return"string"!=typeof r?null:"string"==typeof i||"number"==typeof i?i:null}function dN(t,r,i,n,o=null){return Response.json({jsonrpc:"2.0",error:{code:r,message:i,...void 0!==n&&{data:n}},id:o},{status:t})}function dz(t,r=null){return dN(t.httpStatus,t.code,t.message,t.data,r)}function dM(t){return t instanceof Error?t:Error(String(t))}function dZ(t=null){return dN(500,-32603,"Internal server error",void 0,t)}function dU(t){if(void 0!==t.transport)throw Error("The factory returned an instance that is still serving another request. Return a new instance for each request.")}function dF(t){return{protocolVersionHeader:t.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:t.headers.get("mcp-method")??void 0,mcpNameHeader:t.headers.get("mcp-name")??void 0}}async function dH(t,r,i=!0,n=4194304){let o,a=t.method.toUpperCase(),s=r,l=t,c=!1;if("POST"===a){if(void 0===s){let r;i&&(l=t.clone());try{let i=await dj(t,n);if(i.tooLarge)return{step:"body-too-large"};r=i.text}catch{return{step:"unreadable-body"}}try{o=0===r.length?void 0:JSON.parse(r)}catch{c=!0}c||void 0===o||(s=o)}else o=s;if(c||void 0===o)return{step:"no-json-body",forwardRequest:l}}return{step:"classified",outcome:function(t){if("POST"!==(t={...t,...void 0!==t.protocolVersionHeader&&{protocolVersionHeader:uc(t.protocolVersionHeader)},...void 0!==t.mcpMethodHeader&&{mcpMethodHeader:uc(t.mcpMethodHeader)},...void 0!==t.mcpNameHeader&&{mcpNameHeader:uc(t.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let r=t.body;if(Array.isArray(r)){if(0===r.length)return ua("jsonrpc-shape","empty-batch",400,new c_(cv.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let t of r){if(cW(uu(t)?t.params:void 0))return ua("jsonrpc-shape","batch-with-modern-element",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(cX(t)||cQ(t)||c0(t)||c1(t)))return ua("jsonrpc-shape","batch-with-invalid-element",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return c0(r)||c1(r)?{kind:"legacy",reason:"response"}:uu(r)&&cX(r)?function(t,r){let i=r.params,n=r.method,o=t.protocolVersionHeader,a=void 0!==o&&o>=lQ;if("initialize"===n&&!function(t){if(!cW(t))return!1;let r=cG(t);if(void 0===r||!(r>=lQ))return!1;let i=cB(t);return void 0!==i&&0===cK(i).length}(i)){if(a)return us("initialize-with-modern-header",o,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let t=uu(i)&&"string"==typeof i.protocolVersion?i.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==t&&{requestedVersion:t}}}if(cW(i)){let a=cB(i),s=(void 0===a?[]:cK(a))[0];if(void 0!==s)return ua("envelope","envelope-invalid",400,new c_(cv.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${s.key}: ${s.problem}`,{envelope:s}),!0);let l=cG(i);return void 0!==o&&void 0!==l&&o!==l?us("header-body-version-mismatch",o,`the body envelope names protocol version ${l} but the MCP-Protocol-Version header names ${o}`):void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?us("method-header-mismatch",t.mcpMethodHeader,`the body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:r,classification:ud(l)}}if(a){let t=cB(i),r=cK(t??{}).filter(t=>"missing"===t.problem).map(t=>t.key),n=void 0===t?["_meta"]:r.length>0?r:[oG];return ua("envelope","modern-header-without-claim",400,new c_(cv.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${o}, but the request is missing the required per-request envelope key(s): ${n.join(", ")}`,{envelope:{missing:n}}),!0)}return{kind:"legacy",reason:"no-claim",...void 0!==o&&{requestedVersion:o}}}(t,r):uu(r)&&cQ(r)?function(t,r){let i=r.params,n=r.method,o=t.protocolVersionHeader,a=void 0!==o&&o>=lQ;if(cW(i)){let a=cG(i);if(void 0===a){let t=cB(i),r=(void 0===t?[]:cK(t)).find(t=>t.key===oG)??{key:oG,problem:"expected a protocol version string"};return ua("envelope","notification-envelope-invalid",400,new c_(cv.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${r.key}: ${r.problem}`,{envelope:r}),!0)}if(void 0!==o&&o!==a)return us("notification-header-body-version-mismatch",o,`the notification envelope names protocol version ${a} but the MCP-Protocol-Version header names ${o}`);let s=ud(a);return"modern"===s.era&&void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?us("notification-method-header-mismatch",t.mcpMethodHeader,`the notification body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:r,classification:s}}return a?void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?us("notification-method-header-mismatch",t.mcpMethodHeader,`the notification body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:r,classification:{era:"modern",revision:o}}:{kind:"legacy",reason:"notification",...void 0!==o&&{requestedVersion:o}}}(t,r):ua("jsonrpc-shape","invalid-json-rpc-body",400,new c_(cv.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:a,...dF(t),...void 0!==o&&{body:o}}),body:o,parsedBody:s,forwardRequest:l}}let dD=(t,r)=>{globalThis[t]=r},dV=t=>globalThis[t];function dJ({name:t,fallback:r=!0}){let i=Symbol.for(`xmcp-context-${t}`),n=Symbol.for(`xmcp-context-${t}-fallback-store`);if(dV(i))return dV(i);let o=new x,a=globalThis[n]??{current:null};dD(n,a);let s={provider:(t,i)=>(r&&(a.current=t),o.run(t,i)),getContext:()=>{let i=o.getStore();if(i)return i;if(r&&a.current)return a.current;throw Error(`getContext() can only be used within the ${t} context.`)},setContext:i=>{let n=o.getStore()??(r?a.current:null);if(!n)throw Error(`setContext() can only be used within the ${t} context.`);Object.assign(n,i)}};return dD(i,s),s}let dB=dJ({name:"http-request-context"});dB.setContext;let dW=dB.getContext,dG=dB.provider,dK=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),dY=t=>{if(!dK(t)||"string"!=typeof t.name||"string"!=typeof t.version)return;let r={name:t.name,version:t.version};return"string"==typeof t.title&&(r.title=t.title),"string"==typeof t.websiteUrl&&(r.websiteUrl=t.websiteUrl),"string"==typeof t.description&&(r.description=t.description),r},dX=t=>{if(t&&"initialize"===t.method&&dK(t.params))return dY(t.params.clientInfo)},dQ=(t,r)=>{let i=r.toLowerCase();for(let[r,n]of Object.entries(t)){if(r.toLowerCase()!==i)continue;let t=Array.isArray(n)?n[0]:n;if("string"!=typeof t)break;let o=t.trim();return o.length>0?o:void 0}};function d0(t){let{tags:r,enabled:i,...n}=t;return{...n,_meta:void 0===r?n._meta:{...n._meta,"xmcp/tags":r}}}let d1=new class{add(t,r){this.resources.set(t,r)}getAll(){return this.resources}clear(){this.resources.clear()}has(t){return this.resources.has(t)}constructor(){var t,r;t="resources",r=new Map,t in this?Object.defineProperty(this,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):this[t]=r}},d2=dJ({name:"request-context",fallback:!1}),d9=dJ({name:"client-info-context"});d9.setContext;let d4=d9.getContext;d9.provider;let d5=new Set(["message","mode","requestedSchema"]),d3=new Set(["elicitationId","message","mode","url"]),d6=new Set(["properties","required","type"]),d7=new Set(["default","description","format","maxLength","minLength","title","type"]),d8=new Set(["default","description","enum","enumNames","title","type"]),pe=new Set(["default","description","title","type"]),pt=new Set(["default","description","maximum","minimum","title","type"]),pr=new Set(["date","date-time","email","uri"]);async function pi(t,r,i){let n=function(t){let r=t.mode??"form";if("url"===r)return function(t){let r;po(t,"Elicitation request must be a plain object."),pn(t,d3,"URL elicitation"),pa(t.message,"URL elicitation requires a string message."),ps(t.elicitationId,"URL elicitation requires a non-empty elicitationId."),ps(t.url,"URL elicitation requires a non-empty URL.");try{r=new URL(t.url)}catch{throw Error("URL elicitation requires a valid http or https URL.")}if("http:"!==r.protocol&&"https:"!==r.protocol)throw Error("URL elicitation requires a valid http or https URL.")}(t),t;if("form"!==r)throw Error(`Unsupported elicitation mode "${String(t.mode)}". Expected "form" or "url".`);return function(t){po(t,"Elicitation request must be a plain object."),pn(t,d5,"Form elicitation"),pa(t.message,"Form elicitation requires a string message.");let r=t.requestedSchema;if(po(r,"Form elicitation requires a flat object schema."),pn(r,d6,"Form elicitation schema"),"object"!==r.type)throw Error('Form elicitation schema must use type "object".');for(let[t,i]of(po(r.properties,"Form elicitation schema requires a properties object."),Object.entries(r.properties)))!function(t,r){if(po(r,`Form elicitation field "${t}" must be a plain object.`),pl(r.title,`Form elicitation field "${t}" title must be a string.`),pl(r.description,`Form elicitation field "${t}" description must be a string.`),"string"===r.type&&"enum"in r){var i,n;if(pn(r,d8,`Form elicitation field "${t}"`),pu(r.enum,`Form elicitation field "${t}" enum values must be strings.`),i=r.enumNames,n=`Form elicitation field "${t}" enumNames must be strings.`,void 0!==i&&pu(i,n),void 0!==r.enumNames&&r.enumNames.length!==r.enum.length)throw Error(`Form elicitation field "${t}" enumNames length must match enum length.`);if(pl(r.default,`Form elicitation field "${t}" default must be a string.`),void 0!==r.default&&!r.enum.includes(r.default))throw Error(`Form elicitation field "${t}" default must be one of its enum values.`);return}if("string"===r.type&&!("enum"in r)){pn(r,d7,`Form elicitation field "${t}"`),pc(r.minLength,`Form elicitation field "${t}" minLength must be a number.`),pc(r.maxLength,`Form elicitation field "${t}" maxLength must be a number.`),pl(r.default,`Form elicitation field "${t}" default must be a string.`);let i=r.format;if(pl(i,`Form elicitation field "${t}" format must be a string.`),void 0!==i&&!pr.has(i))throw Error(`Form elicitation field "${t}" format must be one of: ${Array.from(pr).join(", ")}.`);return}if("boolean"===r.type){if(pn(r,pe,`Form elicitation field "${t}"`),void 0!==r.default&&"boolean"!=typeof r.default)throw Error(`Form elicitation field "${t}" default must be a boolean.`);return}if("number"===r.type||"integer"===r.type){pn(r,pt,`Form elicitation field "${t}"`),pc(r.minimum,`Form elicitation field "${t}" minimum must be a number.`),pc(r.maximum,`Form elicitation field "${t}" maximum must be a number.`),pc(r.default,`Form elicitation field "${t}" default must be a number.`);return}throw Error(`Form elicitation field "${t}" uses unsupported type "${String(r.type)}". Supported types are string, boolean, number, integer, and string enums.`)}(t,i);if(void 0!==r.required){if(!Array.isArray(r.required)||r.required.some(t=>"string"!=typeof t))throw Error("Form elicitation schema required fields must be a string array.");for(let t of r.required)if(!(t in r.properties))throw Error(`Form elicitation schema required field "${t}" is not defined in properties.`)}}(t),{...t,mode:"form"}}(r);try{let r=await t.mcpReq.elicitInput(n,i);return{...r,content:r.content??void 0}}catch(t){if(t instanceof lG&&t.code===lW.MethodNotSupportedByProtocolVersion)throw Error("extra.elicit() is not available on protocol revision 2026-07-28: server-initiated elicitation was replaced by multi round-trip requests. Return inputRequired({ ... }) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw t}}function pn(t,r,i){let n=Object.keys(t).filter(t=>!r.has(t));if(0!==n.length)throw Error(`${i} includes unsupported key(s): ${n.join(", ")}.`)}function po(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}function pa(t,r){if("string"!=typeof t)throw Error(r)}function ps(t,r){if("string"!=typeof t||0===t.trim().length)throw Error(r)}function pl(t,r){if(void 0!==t&&"string"!=typeof t)throw Error(r)}function pc(t,r){if(void 0!==t&&"number"!=typeof t)throw Error(r)}function pu(t,r){if(!Array.isArray(t)||t.some(t=>"string"!=typeof t))throw Error(r)}let pd=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),pp=new Set(["task","toolChoice","tools"]),pm=new Set(["text","image","audio"]);async function ph(t,r,i){let n=function(t){pf(t,"Sampling request must be a plain object.");let r=Object.keys(t),i=r.filter(t=>pp.has(t));if(i.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${i.join(", ")}.`);let n=r.filter(t=>!pd.has(t));if(n.length>0)throw Error(`Sampling request includes unsupported key(s): ${n.join(", ")}.`);if(!Array.isArray(t.messages)||0===t.messages.length)throw Error("Sampling requires at least one message.");for(let[r,i]of t.messages.entries())!function(t,r){if(pf(r,`Sampling message at index ${t} must be a plain object.`),"user"!==r.role&&"assistant"!==r.role)throw Error(`Sampling message at index ${t} requires role "user" or "assistant".`);let i=r.content;pf(i,`Sampling message at index ${t} requires a content object.`);let n=i.type;if("string"!=typeof n||!pm.has(n))throw Error(`Sampling message at index ${t} uses unsupported content type "${String(n)}". Supported types are text, image, and audio.`);if("text"===n&&"string"!=typeof i.text)throw Error(`Sampling message at index ${t} requires string text content.`);if(("image"===n||"audio"===n)&&("string"!=typeof i.data||"string"!=typeof i.mimeType))throw Error(`Sampling message at index ${t} requires base64 data and a mimeType.`)}(r,i);if("number"!=typeof t.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return t}(r);try{return await t.mcpReq.requestSampling(n,i)}catch(t){if(t instanceof lG&&t.code===lW.MethodNotSupportedByProtocolVersion)throw Error("extra.sample() is not available on protocol revision 2026-07-28: server-initiated sampling was replaced by multi round-trip requests. Return inputRequired({ ... }) with inputRequired.createMessage(...) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw t}}function pf(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}let pg={text:t=>"string"!=typeof t.text?{valid:!1,error:'Text content must have a "text" property of type string'}:{valid:!0},image:t=>"string"!=typeof t.data?{valid:!1,error:'Image content must have a "data" property of type string (base64-encoded image)'}:"string"!=typeof t.mimeType?{valid:!1,error:'Image content must have a "mimeType" property of type string'}:{valid:!0},audio:t=>"string"!=typeof t.data?{valid:!1,error:'Audio content must have a "data" property of type string (base64-encoded audio)'}:"string"!=typeof t.mimeType?{valid:!1,error:'Audio content must have a "mimeType" property of type string'}:{valid:!0},resource_link:t=>"string"!=typeof t.name?{valid:!1,error:'Resource link content must have a "name" property of type string'}:"string"!=typeof t.uri?{valid:!1,error:'Resource link content must have a "uri" property of type string'}:void 0!==t.title&&"string"!=typeof t.title?{valid:!1,error:'Resource link "title" property must be a string if provided'}:void 0!==t.description&&"string"!=typeof t.description?{valid:!1,error:'Resource link "description" property must be a string if provided'}:void 0!==t.mimeType&&"string"!=typeof t.mimeType?{valid:!1,error:'Resource link "mimeType" property must be a string if provided'}:{valid:!0}};function py(t){if(!t||"object"!=typeof t)return{valid:!1,error:"Content must be an object"};if("string"!=typeof t.type)return{valid:!1,error:'Content must have a "type" property of type string'};if(void 0!==t._meta&&(null===t._meta||"object"!=typeof t._meta))return{valid:!1,error:'Content "_meta" property must be an object if provided'};let r=pg[t.type];return r?r(t):{valid:!0}}function pv(t,r,i,n){if(null===t||"object"!=typeof t||Array.isArray(t))throw Error(`Tool "${i}" ${n}: expected a plain object.`);let o=new Set(Object.keys(r)),a=Object.keys(t).filter(t=>!o.has(t));if(a.length>0)throw Error(`Tool "${i}" ${n}: unrecognized key(s): ${a.join(", ")}`);for(let[o,a]of Object.entries(r))try{a.parse(t[o])}catch(t){throw Error(`Tool "${i}" ${n}: ${t?.message??`invalid field "${o}"`}`)}}function p_(t){return!!(t&&"object"==typeof t&&Object.keys(t).some(t=>t.startsWith("ui/")))}function pb(t){let r=t.mcpReq.envelope,i=dY(r?.[oK]);if(!i)try{let t,r=dW();i=r.clientInfo??(t=r.headers,dY({name:dQ(t,"x-mcp-client-name"),version:dQ(t,"x-mcp-client-version"),title:dQ(t,"x-mcp-client-title"),websiteUrl:dQ(t,"x-mcp-client-website-url"),description:dQ(t,"x-mcp-client-description")}))}catch{}if(!i)try{i=d4().clientInfo}catch{}return i}function pS(t){let r=[...t];return(t,i,n)=>(function(t,r,i){let n,o=new Map;if(t.http){let t=dW(),r=Object.fromEntries(Object.entries(t.headers).map(([t,r])=>[t,Array.isArray(r)?Object.freeze([...r]):r]));n=Object.freeze({id:t.id,headers:Object.freeze(r)})}return d2.provider(Object.freeze({clientInfo:r?Object.freeze({...r}):void 0,http:n,authInfo:t.http?.authInfo,signal:t.mcpReq.signal,set(t,r){o.set(t,r)},get:t=>o.get(t),async progress(r,i){let n=t.mcpReq._meta?.progressToken;void 0!==n&&await t.mcpReq.notify({method:"notifications/progress",params:{progressToken:n,progress:r,...void 0===i?{}:{total:i}}})},log:(r,i)=>t.mcpReq.log(r,i)}),i)})(i,pb(i),async()=>{if(0===r.length)return n();let i=Object.freeze({...function(){try{return d2.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),...t,params:Object.freeze({...t.params})}),o=-1,a=async t=>{if(t<=o)throw Error("MCP middleware next() can only be called once");o=t;let s=r[t];return s?s(i,()=>a(t+1)):n()};return a(0)})}let pw=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function pR(t){return t.endsWith(".tsx")}let pk=Symbol("Let zodToJsonSchema decide on which parser to use"),px={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};(E=L||(L={})).assertEqual=t=>{},E.assertIs=function(t){},E.assertNever=function(t){throw Error()},E.arrayToEnum=t=>{let r={};for(let i of t)r[i]=i;return r},E.getValidEnumValues=t=>{let r=E.objectKeys(t).filter(r=>"number"!=typeof t[t[r]]),i={};for(let n of r)i[n]=t[n];return E.objectValues(i)},E.objectValues=t=>E.objectKeys(t).map(function(r){return t[r]}),E.objectKeys="function"==typeof Object.keys?t=>Object.keys(t):t=>{let r=[];for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&r.push(i);return r},E.find=(t,r)=>{for(let i of t)if(r(i))return i},E.isInteger="function"==typeof Number.isInteger?t=>Number.isInteger(t):t=>"number"==typeof t&&Number.isFinite(t)&&Math.floor(t)===t,E.joinValues=function(t,r=" | "){return t.map(t=>"string"==typeof t?`'${t}'`:t).join(r)},E.jsonStringifyReplacer=(t,r)=>"bigint"==typeof r?r.toString():r,(N||(N={})).mergeShapes=(t,r)=>({...t,...r});let pC=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),p$=t=>{switch(typeof t){case"undefined":return pC.undefined;case"string":return pC.string;case"number":return Number.isNaN(t)?pC.nan:pC.number;case"boolean":return pC.boolean;case"function":return pC.function;case"bigint":return pC.bigint;case"symbol":return pC.symbol;case"object":if(Array.isArray(t))return pC.array;if(null===t)return pC.null;if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return pC.promise;if("undefined"!=typeof Map&&t instanceof Map)return pC.map;if("undefined"!=typeof Set&&t instanceof Set)return pC.set;if("undefined"!=typeof Date&&t instanceof Date)return pC.date;return pC.object;default:return pC.unknown}},pT=L.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"]);class pP extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=t=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};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(t){return t.message},i={_errors:[]},n=t=>{for(let o of t.issues)if("invalid_union"===o.code)o.unionErrors.map(n);else if("invalid_return_type"===o.code)n(o.returnTypeError);else if("invalid_arguments"===o.code)n(o.argumentsError);else if(0===o.path.length)i._errors.push(r(o));else{let t=i,n=0;for(;n<o.path.length;){let i=o.path[n],a=n===o.path.length-1;if("_errors"===i){a&&t._errors.push(r(o)),n++;continue}Object.prototype.hasOwnProperty.call(t,i)||("__proto__"===i?Object.defineProperty(t,i,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):t[i]={_errors:[]}),t=t[i],a&&t._errors.push(r(o)),n++}}};return n(this),i}static assert(t){if(!(t instanceof pP))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(t=t=>t.message){let r=Object.create(null),i=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(t(n))}else i.push(t(n));return{formErrors:i,fieldErrors:r}}get formErrors(){return this.flatten()}}pP.create=t=>new pP(t);let pE=(t,r)=>{let i;switch(t.code){case pT.invalid_type:i=t.received===pC.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case pT.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,L.jsonStringifyReplacer)}`;break;case pT.unrecognized_keys:i=`Unrecognized key(s) in object: ${L.joinValues(t.keys,", ")}`;break;case pT.invalid_union:i="Invalid input";break;case pT.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${L.joinValues(t.options)}`;break;case pT.invalid_enum_value:i=`Invalid enum value. Expected ${L.joinValues(t.options)}, received '${t.received}'`;break;case pT.invalid_arguments:i="Invalid function arguments";break;case pT.invalid_return_type:i="Invalid function return type";break;case pT.invalid_date:i="Invalid date";break;case pT.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(i=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(i=`${i} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?i=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?i=`Invalid input: must end with "${t.validation.endsWith}"`:L.assertNever(t.validation):i="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case pT.too_small:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type||"bigint"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case pT.too_big:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case pT.custom:i="Invalid input";break;case pT.invalid_intersection_types:i="Intersection results could not be merged";break;case pT.not_multiple_of:i=`Number must be a multiple of ${t.multipleOf}`;break;case pT.not_finite:i="Number must be finite";break;default:i=r.defaultError,L.assertNever(t)}return{message:i}};(O=z||(z={})).errToObj=t=>"string"==typeof t?{message:t}:t||{},O.toString=t=>"string"==typeof t?t:t?.message;let pO=t=>{let{data:r,path:i,errorMaps:n,issueData:o}=t,a=[...i,...o.path||[]],s={...o,path:a};if(void 0!==o.message)return{...o,path:a,message:o.message};let l="";for(let t of n.filter(t=>!!t).slice().reverse())l=t(s,{data:r,defaultError:l}).message;return{...o,path:a,message:l}};function pI(t,r){let i=pO({issueData:r,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pE,void 0].filter(t=>!!t)});t.common.issues.push(i)}class pq{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(t,r){let i=[];for(let n of r){if("aborted"===n.status)return pj;"dirty"===n.status&&t.dirty(),i.push(n.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,r){let i=[];for(let t of r){let r=await t.key,n=await t.value;i.push({key:r,value:n})}return pq.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let n of r){let{key:r,value:o}=n;if("aborted"===r.status||"aborted"===o.status)return pj;"dirty"===r.status&&t.dirty(),"dirty"===o.status&&t.dirty(),"__proto__"!==r.value&&(void 0!==o.value||n.alwaysSet)&&(i[r.value]=o.value)}return{status:t.value,value:i}}}let pj=Object.freeze({status:"aborted"}),pA=t=>({status:"dirty",value:t}),pL=t=>({status:"valid",value:t}),pN=t=>"undefined"!=typeof Promise&&t instanceof Promise;class pz{constructor(t,r,i,n){this._cachedPath=[],this.parent=t,this.data=r,this._path=i,this._key=n}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}}let pM=(t,r)=>{if("valid"===r.status)return{success:!0,data:r.value};if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new pP(t.common.issues);return this._error=r,this._error}}};function pZ(t){if(!t)return{};let{errorMap:r,invalid_type_error:i,required_error:n,description:o}=t;if(r&&(i||n))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return r?{errorMap:r,description:o}:{errorMap:(r,o)=>{let{message:a}=t;return"invalid_enum_value"===r.code?{message:a??o.defaultError}:void 0===o.data?{message:a??n??o.defaultError}:"invalid_type"!==r.code?{message:o.defaultError}:{message:a??i??o.defaultError}},description:o}}class pU{get description(){return this._def.description}_getType(t){return p$(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:p$(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new pq,ctx:{common:t.parent.common,data:t.data,parsedType:p$(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(pN(r))throw Error("Synchronous parse encountered promise.");return r}_parseAsync(t){return Promise.resolve(this._parse(t))}parse(t,r){let i=this.safeParse(t,r);if(i.success)return i.data;throw i.error}safeParse(t,r){let i={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:p$(t)},n=this._parseSync({data:t,path:i.path,parent:i});return pM(i,n)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:p$(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:r});return"valid"===i.status?{value:i.value}:{issues:r.common.issues}}catch(t){t?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(t=>"valid"===t.status?{value:t.value}:{issues:r.common.issues})}async parseAsync(t,r){let i=await this.safeParseAsync(t,r);if(i.success)return i.data;throw i.error}async safeParseAsync(t,r){let i={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:p$(t)},n=this._parse({data:t,path:i.path,parent:i});return pM(i,await (pN(n)?n:Promise.resolve(n)))}refine(t,r){return this._refinement((i,n)=>{let o=t(i),a=()=>n.addIssue({code:pT.custom,..."string"==typeof r||void 0===r?{message:r}:"function"==typeof r?r(i):r});return"undefined"!=typeof Promise&&o instanceof Promise?o.then(t=>!!t||(a(),!1)):!!o||(a(),!1)})}refinement(t,r){return this._refinement((i,n)=>!!t(i)||(n.addIssue("function"==typeof r?r(i,n):r),!1))}_refinement(t){return new mk({schema:this,typeName:M.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:t=>this["~validate"](t)}}optional(){return mx.create(this,this._def)}nullable(){return mC.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ms.create(this)}promise(){return mR.create(this,this._def)}or(t){return mc.create([this,t],this._def)}and(t){return mp.create(this,t,this._def)}transform(t){return new mk({...pZ(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){return new m$({...pZ(this._def),innerType:this,defaultValue:"function"==typeof t?t:()=>t,typeName:M.ZodDefault})}brand(){return new mE({typeName:M.ZodBranded,type:this,...pZ(this._def)})}catch(t){return new mT({...pZ(this._def),innerType:this,catchValue:"function"==typeof t?t:()=>t,typeName:M.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return mO.create(this,t)}readonly(){return mI.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let pF=/^c[^\s-]{8,}$/i,pH=/^[0-9a-z]+$/,pD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pV=/^[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,pJ=/^[a-z0-9_-]{21}$/i,pB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pW=/^[-+]?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)?)??$/,pG=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,pK=/^(?:(?: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])$/,pY=/^(?:(?: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])$/,pX=/^(([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]))$/,pQ=/^(([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])$/,p0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,p1=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,p2="((\\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])))",p9=RegExp(`^${p2}$`);function p4(t){let r="[0-5]\\d";t.precision?r=`${r}\\.\\d{${t.precision}}`:null==t.precision&&(r=`${r}(\\.\\d+)?`);let i=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${r})${i}`}class p5 extends pU{_parse(t){var r,i,n,o;let a;if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==pC.string){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.string,received:r.parsedType}),pj}let s=new pq;for(let l of this._def.checks)if("min"===l.kind)t.data.length<l.value&&(pI(a=this._getOrReturnCtx(t,a),{code:pT.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("max"===l.kind)t.data.length>l.value&&(pI(a=this._getOrReturnCtx(t,a),{code:pT.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("length"===l.kind){let r=t.data.length>l.value,i=t.data.length<l.value;(r||i)&&(a=this._getOrReturnCtx(t,a),r?pI(a,{code:pT.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):i&&pI(a,{code:pT.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),s.dirty())}else if("email"===l.kind)pG.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"email",code:pT.invalid_string,message:l.message}),s.dirty());else if("emoji"===l.kind)p||(p=RegExp("^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),p.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"emoji",code:pT.invalid_string,message:l.message}),s.dirty());else if("uuid"===l.kind)pV.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"uuid",code:pT.invalid_string,message:l.message}),s.dirty());else if("nanoid"===l.kind)pJ.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"nanoid",code:pT.invalid_string,message:l.message}),s.dirty());else if("cuid"===l.kind)pF.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"cuid",code:pT.invalid_string,message:l.message}),s.dirty());else if("cuid2"===l.kind)pH.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"cuid2",code:pT.invalid_string,message:l.message}),s.dirty());else if("ulid"===l.kind)pD.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"ulid",code:pT.invalid_string,message:l.message}),s.dirty());else if("url"===l.kind)try{new URL(t.data)}catch{pI(a=this._getOrReturnCtx(t,a),{validation:"url",code:pT.invalid_string,message:l.message}),s.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"regex",code:pT.invalid_string,message:l.message}),s.dirty())):"trim"===l.kind?t.data=t.data.trim():"includes"===l.kind?t.data.includes(l.value,l.position)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),s.dirty()):"toLowerCase"===l.kind?t.data=t.data.toLowerCase():"toUpperCase"===l.kind?t.data=t.data.toUpperCase():"startsWith"===l.kind?t.data.startsWith(l.value)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:{startsWith:l.value},message:l.message}),s.dirty()):"endsWith"===l.kind?t.data.endsWith(l.value)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:{endsWith:l.value},message:l.message}),s.dirty()):"datetime"===l.kind?(function(t){let r=`${p2}T${p4(t)}`,i=[];return i.push(t.local?"Z?":"Z"),t.offset&&i.push("([+-]\\d{2}:?\\d{2})"),r=`${r}(${i.join("|")})`,RegExp(`^${r}$`)})(l).test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:"datetime",message:l.message}),s.dirty()):"date"===l.kind?p9.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:"date",message:l.message}),s.dirty()):"time"===l.kind?RegExp(`^${p4(l)}$`).test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:"time",message:l.message}),s.dirty()):"duration"===l.kind?pW.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"duration",code:pT.invalid_string,message:l.message}),s.dirty()):"ip"===l.kind?(r=t.data,!(("v4"===(i=l.version)||!i)&&pK.test(r)||("v6"===i||!i)&&pX.test(r))&&1&&(pI(a=this._getOrReturnCtx(t,a),{validation:"ip",code:pT.invalid_string,message:l.message}),s.dirty())):"jwt"===l.kind?!function(t,r){if(!pB.test(t))return!1;try{let[i]=t.split(".");if(!i)return!1;let n=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),o=JSON.parse(atob(n));if("object"!=typeof o||null===o||"typ"in o&&o?.typ!=="JWT"||!o.alg||r&&o.alg!==r)return!1;return!0}catch{return!1}}(t.data,l.alg)&&(pI(a=this._getOrReturnCtx(t,a),{validation:"jwt",code:pT.invalid_string,message:l.message}),s.dirty()):"cidr"===l.kind?(n=t.data,!(("v4"===(o=l.version)||!o)&&pY.test(n)||("v6"===o||!o)&&pQ.test(n))&&1&&(pI(a=this._getOrReturnCtx(t,a),{validation:"cidr",code:pT.invalid_string,message:l.message}),s.dirty())):"base64"===l.kind?p0.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"base64",code:pT.invalid_string,message:l.message}),s.dirty()):"base64url"===l.kind?p1.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"base64url",code:pT.invalid_string,message:l.message}),s.dirty()):L.assertNever(l);return{status:s.value,value:t.data}}_regex(t,r,i){return this.refinement(r=>t.test(r),{validation:r,code:pT.invalid_string,...z.errToObj(i)})}_addCheck(t){return new p5({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...z.errToObj(t)})}url(t){return this._addCheck({kind:"url",...z.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...z.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...z.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...z.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...z.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...z.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...z.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...z.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...z.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...z.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...z.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...z.errToObj(t)})}datetime(t){return"string"==typeof t?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:void 0===t?.precision?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...z.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return"string"==typeof t?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:void 0===t?.precision?null:t?.precision,...z.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...z.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...z.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...z.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...z.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...z.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...z.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...z.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...z.errToObj(r)})}nonempty(t){return this.min(1,z.errToObj(t))}trim(){return new p5({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new p5({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new p5({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>"datetime"===t.kind)}get isDate(){return!!this._def.checks.find(t=>"date"===t.kind)}get isTime(){return!!this._def.checks.find(t=>"time"===t.kind)}get isDuration(){return!!this._def.checks.find(t=>"duration"===t.kind)}get isEmail(){return!!this._def.checks.find(t=>"email"===t.kind)}get isURL(){return!!this._def.checks.find(t=>"url"===t.kind)}get isEmoji(){return!!this._def.checks.find(t=>"emoji"===t.kind)}get isUUID(){return!!this._def.checks.find(t=>"uuid"===t.kind)}get isNANOID(){return!!this._def.checks.find(t=>"nanoid"===t.kind)}get isCUID(){return!!this._def.checks.find(t=>"cuid"===t.kind)}get isCUID2(){return!!this._def.checks.find(t=>"cuid2"===t.kind)}get isULID(){return!!this._def.checks.find(t=>"ulid"===t.kind)}get isIP(){return!!this._def.checks.find(t=>"ip"===t.kind)}get isCIDR(){return!!this._def.checks.find(t=>"cidr"===t.kind)}get isBase64(){return!!this._def.checks.find(t=>"base64"===t.kind)}get isBase64url(){return!!this._def.checks.find(t=>"base64url"===t.kind)}get minLength(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}p5.create=t=>new p5({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...pZ(t)});class p3 extends pU{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){let r;if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==pC.number){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.number,received:r.parsedType}),pj}let i=new pq;for(let n of this._def.checks)"int"===n.kind?L.isInteger(t.data)||(pI(r=this._getOrReturnCtx(t,r),{code:pT.invalid_type,expected:"integer",received:"float",message:n.message}),i.dirty()):"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"multipleOf"===n.kind?0!==function(t,r){let i=(t.toString().split(".")[1]||"").length,n=(r.toString().split(".")[1]||"").length,o=i>n?i:n;return Number.parseInt(t.toFixed(o).replace(".",""))%Number.parseInt(r.toFixed(o).replace(".",""))/10**o}(t.data,n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):"finite"===n.kind?Number.isFinite(t.data)||(pI(r=this._getOrReturnCtx(t,r),{code:pT.not_finite,message:n.message}),i.dirty()):L.assertNever(n);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,z.toString(r))}gt(t,r){return this.setLimit("min",t,!1,z.toString(r))}lte(t,r){return this.setLimit("max",t,!0,z.toString(r))}lt(t,r){return this.setLimit("max",t,!1,z.toString(r))}setLimit(t,r,i,n){return new p3({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:z.toString(n)}]})}_addCheck(t){return new p3({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:z.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:z.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:z.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>"int"===t.kind||"multipleOf"===t.kind&&L.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let i of this._def.checks)if("finite"===i.kind||"int"===i.kind||"multipleOf"===i.kind)return!0;else"min"===i.kind?(null===r||i.value>r)&&(r=i.value):"max"===i.kind&&(null===t||i.value<t)&&(t=i.value);return Number.isFinite(r)&&Number.isFinite(t)}}p3.create=t=>new p3({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...pZ(t)});class p6 extends pU{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){let r;if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==pC.bigint)return this._getInvalidInput(t);let i=new pq;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):"multipleOf"===n.kind?t.data%n.value!==BigInt(0)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):L.assertNever(n);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.bigint,received:r.parsedType}),pj}gte(t,r){return this.setLimit("min",t,!0,z.toString(r))}gt(t,r){return this.setLimit("min",t,!1,z.toString(r))}lte(t,r){return this.setLimit("max",t,!0,z.toString(r))}lt(t,r){return this.setLimit("max",t,!1,z.toString(r))}setLimit(t,r,i,n){return new p6({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:z.toString(n)}]})}_addCheck(t){return new p6({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:z.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}p6.create=t=>new p6({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...pZ(t)});class p7 extends pU{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==pC.boolean){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.boolean,received:r.parsedType}),pj}return pL(t.data)}}p7.create=t=>new p7({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...pZ(t)});class p8 extends pU{_parse(t){let r;if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==pC.date){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.date,received:r.parsedType}),pj}if(Number.isNaN(t.data.getTime()))return pI(this._getOrReturnCtx(t),{code:pT.invalid_date}),pj;let i=new pq;for(let n of this._def.checks)"min"===n.kind?t.data.getTime()<n.value&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):"max"===n.kind?t.data.getTime()>n.value&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):L.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new p8({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:z.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:z.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return null!=t?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return null!=t?new Date(t):null}}p8.create=t=>new p8({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...pZ(t)});class me extends pU{_parse(t){if(this._getType(t)!==pC.symbol){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.symbol,received:r.parsedType}),pj}return pL(t.data)}}me.create=t=>new me({typeName:M.ZodSymbol,...pZ(t)});class mt extends pU{_parse(t){if(this._getType(t)!==pC.undefined){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.undefined,received:r.parsedType}),pj}return pL(t.data)}}mt.create=t=>new mt({typeName:M.ZodUndefined,...pZ(t)});class mr extends pU{_parse(t){if(this._getType(t)!==pC.null){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.null,received:r.parsedType}),pj}return pL(t.data)}}mr.create=t=>new mr({typeName:M.ZodNull,...pZ(t)});class mi extends pU{constructor(){super(...arguments),this._any=!0}_parse(t){return pL(t.data)}}mi.create=t=>new mi({typeName:M.ZodAny,...pZ(t)});class mn extends pU{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pL(t.data)}}mn.create=t=>new mn({typeName:M.ZodUnknown,...pZ(t)});class mo extends pU{_parse(t){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.never,received:r.parsedType}),pj}}mo.create=t=>new mo({typeName:M.ZodNever,...pZ(t)});class ma extends pU{_parse(t){if(this._getType(t)!==pC.undefined){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.void,received:r.parsedType}),pj}return pL(t.data)}}ma.create=t=>new ma({typeName:M.ZodVoid,...pZ(t)});class ms extends pU{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),n=this._def;if(r.parsedType!==pC.array)return pI(r,{code:pT.invalid_type,expected:pC.array,received:r.parsedType}),pj;if(null!==n.exactLength){let t=r.data.length>n.exactLength.value,o=r.data.length<n.exactLength.value;(t||o)&&(pI(r,{code:t?pT.too_big:pT.too_small,minimum:o?n.exactLength.value:void 0,maximum:t?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(null!==n.minLength&&r.data.length<n.minLength.value&&(pI(r,{code:pT.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),null!==n.maxLength&&r.data.length>n.maxLength.value&&(pI(r,{code:pT.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),r.common.async)return Promise.all([...r.data].map((t,i)=>n.type._parseAsync(new pz(r,t,r.path,i)))).then(t=>pq.mergeArray(i,t));let o=[...r.data].map((t,i)=>n.type._parseSync(new pz(r,t,r.path,i)));return pq.mergeArray(i,o)}get element(){return this._def.type}min(t,r){return new ms({...this._def,minLength:{value:t,message:z.toString(r)}})}max(t,r){return new ms({...this._def,maxLength:{value:t,message:z.toString(r)}})}length(t,r){return new ms({...this._def,exactLength:{value:t,message:z.toString(r)}})}nonempty(t){return this.min(1,t)}}ms.create=(t,r)=>new ms({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...pZ(r)});class ml extends pU{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let t=this._def.shape(),r=L.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==pC.object){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.object,received:r.parsedType}),pj}let{status:r,ctx:i}=this._processInputParams(t),{shape:n,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof mo&&"strip"===this._def.unknownKeys))for(let t in i.data)o.includes(t)||a.push(t);let s=[];for(let t of o){let r=n[t],o=i.data[t];s.push({key:{status:"valid",value:t},value:r._parse(new pz(i,o,i.path,t)),alwaysSet:t in i.data})}if(this._def.catchall instanceof mo){let t=this._def.unknownKeys;if("passthrough"===t)for(let t of a)s.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===t)a.length>0&&(pI(i,{code:pT.unrecognized_keys,keys:a}),r.dirty());else if("strip"===t);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let t=this._def.catchall;for(let r of a){let n=i.data[r];s.push({key:{status:"valid",value:r},value:t._parse(new pz(i,n,i.path,r)),alwaysSet:r in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let t=[];for(let r of s){let i=await r.key,n=await r.value;t.push({key:i,value:n,alwaysSet:r.alwaysSet})}return t}).then(t=>pq.mergeObjectSync(r,t)):pq.mergeObjectSync(r,s)}get shape(){return this._def.shape()}strict(t){return z.errToObj,new ml({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(r,i)=>{let n=this._def.errorMap?.(r,i).message??i.defaultError;return"unrecognized_keys"===r.code?{message:z.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new ml({...this._def,unknownKeys:"strip"})}passthrough(){return new ml({...this._def,unknownKeys:"passthrough"})}extend(t){return new ml({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ml({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new ml({...this._def,catchall:t})}pick(t){let r={};for(let i of L.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new ml({...this._def,shape:()=>r})}omit(t){let r={};for(let i of L.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new ml({...this._def,shape:()=>r})}deepPartial(){return function t(r){if(r instanceof ml){let i={};for(let n in r.shape){let o=r.shape[n];i[n]=mx.create(t(o))}return new ml({...r._def,shape:()=>i})}if(r instanceof ms)return new ms({...r._def,type:t(r.element)});if(r instanceof mx)return mx.create(t(r.unwrap()));if(r instanceof mC)return mC.create(t(r.unwrap()));if(r instanceof mm)return mm.create(r.items.map(r=>t(r)));else return r}(this)}partial(t){let r={};for(let i of L.objectKeys(this.shape)){let n=this.shape[i];t&&!t[i]?r[i]=n:r[i]=n.optional()}return new ml({...this._def,shape:()=>r})}required(t){let r={};for(let i of L.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let t=this.shape[i];for(;t instanceof mx;)t=t._def.innerType;r[i]=t}return new ml({...this._def,shape:()=>r})}keyof(){return mb(L.objectKeys(this.shape))}}ml.create=(t,r)=>new ml({shape:()=>t,unknownKeys:"strip",catchall:mo.create(),typeName:M.ZodObject,...pZ(r)}),ml.strictCreate=(t,r)=>new ml({shape:()=>t,unknownKeys:"strict",catchall:mo.create(),typeName:M.ZodObject,...pZ(r)}),ml.lazycreate=(t,r)=>new ml({shape:t,unknownKeys:"strip",catchall:mo.create(),typeName:M.ZodObject,...pZ(r)});class mc extends pU{_parse(t){let{ctx:r}=this._processInputParams(t),i=this._def.options;if(r.common.async)return Promise.all(i.map(async t=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await t._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(function(t){for(let r of t)if("valid"===r.result.status)return r.result;for(let i of t)if("dirty"===i.result.status)return r.common.issues.push(...i.ctx.common.issues),i.result;let i=t.map(t=>new pP(t.ctx.common.issues));return pI(r,{code:pT.invalid_union,unionErrors:i}),pj});{let t,n=[];for(let o of i){let i={...r,common:{...r.common,issues:[]},parent:null},a=o._parseSync({data:r.data,path:r.path,parent:i});if("valid"===a.status)return a;"dirty"!==a.status||t||(t={result:a,ctx:i}),i.common.issues.length&&n.push(i.common.issues)}if(t)return r.common.issues.push(...t.ctx.common.issues),t.result;let o=n.map(t=>new pP(t));return pI(r,{code:pT.invalid_union,unionErrors:o}),pj}}get options(){return this._def.options}}mc.create=(t,r)=>new mc({options:t,typeName:M.ZodUnion,...pZ(r)});let mu=t=>{if(t instanceof mv)return mu(t.schema);if(t instanceof mk)return mu(t.innerType());if(t instanceof m_)return[t.value];if(t instanceof mS)return t.options;if(t instanceof mw)return L.objectValues(t.enum);else if(t instanceof m$)return mu(t._def.innerType);else if(t instanceof mt)return[void 0];else if(t instanceof mr)return[null];else if(t instanceof mx)return[void 0,...mu(t.unwrap())];else if(t instanceof mC)return[null,...mu(t.unwrap())];else if(t instanceof mE)return mu(t.unwrap());else if(t instanceof mI)return mu(t.unwrap());else if(t instanceof mT)return mu(t._def.innerType);else return[]};class md extends pU{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==pC.object)return pI(r,{code:pT.invalid_type,expected:pC.object,received:r.parsedType}),pj;let i=this.discriminator,n=r.data[i],o=this.optionsMap.get(n);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}):(pI(r,{code:pT.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),pj)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,i){let n=new Map;for(let i of r){let r=mu(i.shape[t]);if(!r.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of r){if(n.has(o))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);n.set(o,i)}}return new md({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...pZ(i)})}}class mp extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=(t,n)=>{if("aborted"===t.status||"aborted"===n.status)return pj;let o=function t(r,i){let n=p$(r),o=p$(i);if(r===i)return{valid:!0,data:r};if(n===pC.object&&o===pC.object){let n=L.objectKeys(i),o=L.objectKeys(r).filter(t=>-1!==n.indexOf(t)),a={...r,...i};for(let n of(Object.prototype.hasOwnProperty.call(a,"__proto__")&&delete a.__proto__,o)){if("__proto__"===n)continue;let o=t(r[n],i[n]);if(!o.valid)return{valid:!1};a[n]=o.data}return{valid:!0,data:a}}if(n===pC.array&&o===pC.array){if(r.length!==i.length)return{valid:!1};let n=[];for(let o=0;o<r.length;o++){let a=t(r[o],i[o]);if(!a.valid)return{valid:!1};n.push(a.data)}return{valid:!0,data:n}}if(n===pC.date&&o===pC.date&&+r==+i)return{valid:!0,data:r};return{valid:!1}}(t.value,n.value);return o.valid?(("dirty"===t.status||"dirty"===n.status)&&r.dirty(),{status:r.value,value:o.data}):(pI(i,{code:pT.invalid_intersection_types}),pj)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([t,r])=>n(t,r)):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}mp.create=(t,r,i)=>new mp({left:t,right:r,typeName:M.ZodIntersection,...pZ(i)});class mm extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==pC.array)return pI(i,{code:pT.invalid_type,expected:pC.array,received:i.parsedType}),pj;if(i.data.length<this._def.items.length)return pI(i,{code:pT.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),pj;!this._def.rest&&i.data.length>this._def.items.length&&(pI(i,{code:pT.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let n=[...i.data].map((t,r)=>{let n=this._def.items[r]||this._def.rest;return n?n._parse(new pz(i,t,i.path,r)):null}).filter(t=>!!t);return i.common.async?Promise.all(n).then(t=>pq.mergeArray(r,t)):pq.mergeArray(r,n)}get items(){return this._def.items}rest(t){return new mm({...this._def,rest:t})}}mm.create=(t,r)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new mm({items:t,typeName:M.ZodTuple,rest:null,...pZ(r)})};class mh extends pU{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==pC.object)return pI(i,{code:pT.invalid_type,expected:pC.object,received:i.parsedType}),pj;let n=[],o=this._def.keyType,a=this._def.valueType;for(let t in i.data)n.push({key:o._parse(new pz(i,t,i.path,t)),value:a._parse(new pz(i,i.data[t],i.path,t)),alwaysSet:t in i.data});return i.common.async?pq.mergeObjectAsync(r,n):pq.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,i){return new mh(r instanceof pU?{keyType:t,valueType:r,typeName:M.ZodRecord,...pZ(i)}:{keyType:p5.create(),valueType:t,typeName:M.ZodRecord,...pZ(r)})}}class mf extends pU{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==pC.map)return pI(i,{code:pT.invalid_type,expected:pC.map,received:i.parsedType}),pj;let n=this._def.keyType,o=this._def.valueType,a=[...i.data.entries()].map(([t,r],a)=>({key:n._parse(new pz(i,t,i.path,[a,"key"])),value:o._parse(new pz(i,r,i.path,[a,"value"]))}));if(i.common.async){let t=new Map;return Promise.resolve().then(async()=>{for(let i of a){let n=await i.key,o=await i.value;if("aborted"===n.status||"aborted"===o.status)return pj;("dirty"===n.status||"dirty"===o.status)&&r.dirty(),t.set(n.value,o.value)}return{status:r.value,value:t}})}{let t=new Map;for(let i of a){let n=i.key,o=i.value;if("aborted"===n.status||"aborted"===o.status)return pj;("dirty"===n.status||"dirty"===o.status)&&r.dirty(),t.set(n.value,o.value)}return{status:r.value,value:t}}}}mf.create=(t,r,i)=>new mf({valueType:r,keyType:t,typeName:M.ZodMap,...pZ(i)});class mg extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==pC.set)return pI(i,{code:pT.invalid_type,expected:pC.set,received:i.parsedType}),pj;let n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(pI(i,{code:pT.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),null!==n.maxSize&&i.data.size>n.maxSize.value&&(pI(i,{code:pT.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let o=this._def.valueType;function a(t){let i=new Set;for(let n of t){if("aborted"===n.status)return pj;"dirty"===n.status&&r.dirty(),i.add(n.value)}return{status:r.value,value:i}}let s=[...i.data.values()].map((t,r)=>o._parse(new pz(i,t,i.path,r)));return i.common.async?Promise.all(s).then(t=>a(t)):a(s)}min(t,r){return new mg({...this._def,minSize:{value:t,message:z.toString(r)}})}max(t,r){return new mg({...this._def,maxSize:{value:t,message:z.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}mg.create=(t,r)=>new mg({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...pZ(r)});class my extends pU{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==pC.function)return pI(r,{code:pT.invalid_type,expected:pC.function,received:r.parsedType}),pj;function i(t,i){return pO({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pE,pE].filter(t=>!!t),issueData:{code:pT.invalid_arguments,argumentsError:i}})}function n(t,i){return pO({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pE,pE].filter(t=>!!t),issueData:{code:pT.invalid_return_type,returnTypeError:i}})}let o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof mR){let t=this;return pL(async function(...r){let s=new pP([]),l=await t._def.args.parseAsync(r,o).catch(t=>{throw s.addIssue(i(r,t)),s}),c=await Reflect.apply(a,this,l);return await t._def.returns._def.type.parseAsync(c,o).catch(t=>{throw s.addIssue(n(c,t)),s})})}{let t=this;return pL(function(...r){let s=t._def.args.safeParse(r,o);if(!s.success)throw new pP([i(r,s.error)]);let l=Reflect.apply(a,this,s.data),c=t._def.returns.safeParse(l,o);if(!c.success)throw new pP([n(l,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new my({...this._def,args:mm.create(t).rest(mn.create())})}returns(t){return new my({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new my({args:t||mm.create([]).rest(mn.create()),returns:r||mn.create(),typeName:M.ZodFunction,...pZ(i)})}}class mv extends pU{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})}}mv.create=(t,r)=>new mv({getter:t,typeName:M.ZodLazy,...pZ(r)});class m_ extends pU{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return pI(r,{received:r.data,code:pT.invalid_literal,expected:this._def.value}),pj}return{status:"valid",value:t.data}}get value(){return this._def.value}}function mb(t,r){return new mS({values:t,typeName:M.ZodEnum,...pZ(r)})}m_.create=(t,r)=>new m_({value:t,typeName:M.ZodLiteral,...pZ(r)});class mS extends pU{_parse(t){if("string"!=typeof t.data){let r=this._getOrReturnCtx(t),i=this._def.values;return pI(r,{expected:L.joinValues(i),received:r.parsedType,code:pT.invalid_type}),pj}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),i=this._def.values;return pI(r,{received:r.data,code:pT.invalid_enum_value,options:i}),pj}return pL(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 mS.create(t,{...this._def,...r})}exclude(t,r=this._def){return mS.create(this.options.filter(r=>!t.includes(r)),{...this._def,...r})}}mS.create=mb;class mw extends pU{_parse(t){let r=L.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==pC.string&&i.parsedType!==pC.number){let t=L.objectValues(r);return pI(i,{expected:L.joinValues(t),received:i.parsedType,code:pT.invalid_type}),pj}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let t=L.objectValues(r);return pI(i,{received:i.data,code:pT.invalid_enum_value,options:t}),pj}return pL(t.data)}get enum(){return this._def.values}}mw.create=(t,r)=>new mw({values:t,typeName:M.ZodNativeEnum,...pZ(r)});class mR extends pU{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==pC.promise&&!1===r.common.async?(pI(r,{code:pT.invalid_type,expected:pC.promise,received:r.parsedType}),pj):pL((r.parsedType===pC.promise?r.data:Promise.resolve(r.data)).then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}}mR.create=(t,r)=>new mR({type:t,typeName:M.ZodPromise,...pZ(r)});class mk extends pU{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=this._def.effect||null,o={addIssue:t=>{pI(i,t),t.fatal?r.abort():r.dirty()},get path(){return i.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===n.type){let t=n.transform(i.data,o);if(i.common.async)return Promise.resolve(t).then(async t=>{if("aborted"===r.value)return pj;let n=await this._def.schema._parseAsync({data:t,path:i.path,parent:i});return"aborted"===n.status?pj:"dirty"===n.status||"dirty"===r.value?pA(n.value):n});{if("aborted"===r.value)return pj;let n=this._def.schema._parseSync({data:t,path:i.path,parent:i});return"aborted"===n.status?pj:"dirty"===n.status||"dirty"===r.value?pA(n.value):n}}if("refinement"===n.type){let t=t=>{let r=n.refinement(t,o);if(i.common.async)return Promise.resolve(r);if(r instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return t};if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(i=>"aborted"===i.status?pj:("dirty"===i.status&&r.dirty(),t(i.value).then(()=>({status:r.value,value:i.value}))));{let n=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===n.status?pj:("dirty"===n.status&&r.dirty(),t(n.value),{status:r.value,value:n.value})}}if("transform"===n.type)if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(t=>"valid"!==t.status?pj:Promise.resolve(n.transform(t.value,o)).then(t=>({status:r.value,value:t})));else{let t=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if("valid"!==t.status)return pj;let a=n.transform(t.value,o);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}L.assertNever(n)}}mk.create=(t,r,i)=>new mk({schema:t,typeName:M.ZodEffects,effect:r,...pZ(i)}),mk.createWithPreprocess=(t,r,i)=>new mk({schema:r,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...pZ(i)});class mx extends pU{_parse(t){return this._getType(t)===pC.undefined?pL(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mx.create=(t,r)=>new mx({innerType:t,typeName:M.ZodOptional,...pZ(r)});class mC extends pU{_parse(t){return this._getType(t)===pC.null?pL(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mC.create=(t,r)=>new mC({innerType:t,typeName:M.ZodNullable,...pZ(r)});class m$ extends pU{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===pC.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}m$.create=(t,r)=>new m$({innerType:t,typeName:M.ZodDefault,defaultValue:"function"==typeof r.default?r.default:()=>r.default,...pZ(r)});class mT extends pU{_parse(t){let{ctx:r}=this._processInputParams(t),i={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return pN(n)?n.then(t=>({status:"valid",value:"valid"===t.status?t.value:this._def.catchValue({get error(){return new pP(i.common.issues)},input:i.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new pP(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}mT.create=(t,r)=>new mT({innerType:t,typeName:M.ZodCatch,catchValue:"function"==typeof r.catch?r.catch:()=>r.catch,...pZ(r)});class mP extends pU{_parse(t){if(this._getType(t)!==pC.nan){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.nan,received:r.parsedType}),pj}return{status:"valid",value:t.data}}}mP.create=t=>new mP({typeName:M.ZodNaN,...pZ(t)}),Symbol("zod_brand");class mE extends pU{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return this._def.type._parse({data:i,path:r.path,parent:r})}unwrap(){return this._def.type}}class mO extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let t=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?pj:"dirty"===t.status?(r.dirty(),pA(t.value)):this._def.out._parseAsync({data:t.value,path:i.path,parent:i})})();{let t=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?pj:"dirty"===t.status?(r.dirty(),{status:"dirty",value:t.value}):this._def.out._parseSync({data:t.value,path:i.path,parent:i})}}static create(t,r){return new mO({in:t,out:r,typeName:M.ZodPipeline})}}class mI extends pU{_parse(t){let r=this._def.innerType._parse(t),i=t=>("valid"===t.status&&(t.value=Object.freeze(t.value)),t);return pN(r)?r.then(t=>i(t)):i(r)}unwrap(){return this._def.innerType}}mI.create=(t,r)=>new mI({innerType:t,typeName:M.ZodReadonly,...pZ(r)}),ml.lazycreate,(I=M||(M={})).ZodString="ZodString",I.ZodNumber="ZodNumber",I.ZodNaN="ZodNaN",I.ZodBigInt="ZodBigInt",I.ZodBoolean="ZodBoolean",I.ZodDate="ZodDate",I.ZodSymbol="ZodSymbol",I.ZodUndefined="ZodUndefined",I.ZodNull="ZodNull",I.ZodAny="ZodAny",I.ZodUnknown="ZodUnknown",I.ZodNever="ZodNever",I.ZodVoid="ZodVoid",I.ZodArray="ZodArray",I.ZodObject="ZodObject",I.ZodUnion="ZodUnion",I.ZodDiscriminatedUnion="ZodDiscriminatedUnion",I.ZodIntersection="ZodIntersection",I.ZodTuple="ZodTuple",I.ZodRecord="ZodRecord",I.ZodMap="ZodMap",I.ZodSet="ZodSet",I.ZodFunction="ZodFunction",I.ZodLazy="ZodLazy",I.ZodLiteral="ZodLiteral",I.ZodEnum="ZodEnum",I.ZodEffects="ZodEffects",I.ZodNativeEnum="ZodNativeEnum",I.ZodOptional="ZodOptional",I.ZodNullable="ZodNullable",I.ZodDefault="ZodDefault",I.ZodCatch="ZodCatch",I.ZodPromise="ZodPromise",I.ZodBranded="ZodBranded",I.ZodPipeline="ZodPipeline",I.ZodReadonly="ZodReadonly",p5.create,p3.create,mP.create,p6.create,p7.create,p8.create,me.create,mt.create,mr.create,mi.create,mn.create,mo.create,ma.create,ms.create,ml.create,ml.strictCreate,mc.create,md.create,mp.create,mm.create,mh.create,mf.create,mg.create,my.create,mv.create,m_.create,mS.create,mw.create,mR.create,mk.create,mx.create,mC.create,mk.createWithPreprocess,mO.create;let mq=(t,r)=>{let i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];i++);return[(t.length-i).toString(),...r.slice(i)].join("/")};function mj(t){if("openAi"!==t.target)return{};let r=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===t.$refStrategy?mq(r,t.currentPath):r.join("/")}}function mA(t,r,i,n){n?.errorMessages&&i&&(t.errorMessage={...t.errorMessage,[r]:i})}function mL(t,r,i,n,o){t[r]=i,mA(t,r,n,o)}function mN(t,r){return m4(t.type._def,r)}let mz=/^[cC][^\s-]{8,}$/,mM=/^[0-9a-z]+$/,mZ=/^[0-9A-HJKMNP-TV-Z]{26}$/,mU=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,mF=()=>(void 0===k&&(k=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),k),mH=/^(?:(?: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])$/,mD=/^(([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])$/,mV=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mJ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mB=/^[a-zA-Z0-9_-]{21}$/,mW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function mG(t,r){let i={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":mL(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r);break;case"max":mL(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"email":switch(r.emailStrategy){case"format:email":mX(i,"email",n.message,r);break;case"format:idn-email":mX(i,"idn-email",n.message,r);break;case"pattern:zod":mQ(i,mU,n.message,r)}break;case"url":mX(i,"uri",n.message,r);break;case"uuid":mX(i,"uuid",n.message,r);break;case"regex":mQ(i,n.regex,n.message,r);break;case"cuid":mQ(i,mz,n.message,r);break;case"cuid2":mQ(i,mM,n.message,r);break;case"startsWith":mQ(i,RegExp(`^${mK(n.value,r)}`),n.message,r);break;case"endsWith":mQ(i,RegExp(`${mK(n.value,r)}$`),n.message,r);break;case"datetime":mX(i,"date-time",n.message,r);break;case"date":mX(i,"date",n.message,r);break;case"time":mX(i,"time",n.message,r);break;case"duration":mX(i,"duration",n.message,r);break;case"length":mL(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r),mL(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"includes":mQ(i,RegExp(mK(n.value,r)),n.message,r);break;case"ip":"v6"!==n.version&&mX(i,"ipv4",n.message,r),"v4"!==n.version&&mX(i,"ipv6",n.message,r);break;case"base64url":mQ(i,mJ,n.message,r);break;case"jwt":mQ(i,mW,n.message,r);break;case"cidr":"v6"!==n.version&&mQ(i,mH,n.message,r),"v4"!==n.version&&mQ(i,mD,n.message,r);break;case"emoji":mQ(i,mF(),n.message,r);break;case"ulid":mQ(i,mZ,n.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":mX(i,"binary",n.message,r);break;case"contentEncoding:base64":mL(i,"contentEncoding","base64",n.message,r);break;case"pattern:zod":mQ(i,mV,n.message,r)}break;case"nanoid":mQ(i,mB,n.message,r)}return i}function mK(t,r){return"escape"===r.patternStrategy?function(t){let r="";for(let i=0;i<t.length;i++)mY.has(t[i])||(r+="\\"),r+=t[i];return r}(t):t}let mY=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mX(t,r,i,n){t.format||t.anyOf?.some(t=>t.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,0===Object.keys(t.errorMessage).length&&delete t.errorMessage)),t.anyOf.push({format:r,...i&&n.errorMessages&&{errorMessage:{format:i}}})):mL(t,"format",r,i,n)}function mQ(t,r,i,n){t.pattern||t.allOf?.some(t=>t.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,0===Object.keys(t.errorMessage).length&&delete t.errorMessage)),t.allOf.push({pattern:m0(r,n),...i&&n.errorMessages&&{errorMessage:{pattern:i}}})):mL(t,"pattern",m0(r,n),i,n)}function m0(t,r){if(!r.applyRegexFlags||!t.flags)return t.source;let i={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=i.i?t.source.toLowerCase():t.source,o="",a=!1,s=!1,l=!1;for(let t=0;t<n.length;t++){if(a){o+=n[t],a=!1;continue}if(i.i){if(s){if(n[t].match(/[a-z]/)){l?(o+=n[t],o+=`${n[t-2]}-${n[t]}`.toUpperCase(),l=!1):"-"===n[t+1]&&n[t+2]?.match(/[a-z]/)?(o+=n[t],l=!0):o+=`${n[t]}${n[t].toUpperCase()}`;continue}}else if(n[t].match(/[a-z]/)){o+=`[${n[t]}${n[t].toUpperCase()}]`;continue}}if(i.m){if("^"===n[t]){o+=`(^|(?<=[\r
74
74
  ]))`;continue}else if("$"===n[t]){o+=`($|(?=[\r
75
75
  ]))`;continue}}if(i.s&&"."===n[t]){o+=s?`${n[t]}\r
76
76
  `:`[${n[t]}\r
@@ -80,7 +80,7 @@ data:
80
80
  -> Default export must be a resource handler function.`)}async function hc(t){let r=new Map,i=[];for(let n of(await Promise.all(Object.entries(t).map(async([t,r])=>{let i=await r(),n=function(t,r){if("object"!=typeof t||null===t)throw hl(r);let i=Object.keys(t),n=t.default,o=i.filter(t=>"__esModule"!==t);if(0===i.length||1===o.length&&"default"===o[0]&&"object"==typeof n&&null!==n&&0===Object.keys(n).length)return"empty";if(!("default"in t)||void 0===t.default)return"missing-default";if("function"!=typeof t.default)throw hl(r);return"valid"}(i,t);return"empty"===n?{skipped:!0,issue:{path:t,message:"File is empty."}}:"missing-default"===n?{skipped:!0,issue:{path:t,message:"File does not export a default resource handler."}}:{skipped:!1,path:t,resourceModule:i}})))){if(n.skipped){i.push(n.issue);continue}r.set(n.path,n.resourceModule)}return{resourceModules:r,skippedResources:i}}let hu=function(t=console){let r="";return i=>{let n=i.map(({path:t,message:r})=>`${t}:${r}`).sort().join("|");if(n===r||(r=n,0===i.length))return;i.forEach(({path:r,message:i})=>{t.warn(`[xmcp] Failed to load resource file: ${r}
81
81
  -> ${i}`)});let o=i.length;t.warn(`[xmcp] ${o} resource${1===o?"":"s"} skipped due to empty files or missing default exports`)}}();function hd(t){let r=t.replace(/\\/g,"/");if(!r)throw Error("Invalid tool path: path is empty");let i=r.replace(/\.[^/.]+$/,"").replace(/\//g,"_");return{normalizedPath:r,baseName:i}}function hp(t){let r=t.split("/").filter(t=>""!==t),i=r.findIndex(t=>t.match(/^\(.+\)$/));if(-1===i)return null;let n=r[r.length-1];if(n&&n.match(/^\[.+\]\.ts$/))return null;let o=r[i].slice(1,-1),a=r.slice(i+1),s=a[a.length-1];if(s&&s.includes(".")){let t=s.split(".")[0];"index"!==t?a[a.length-1]=t:a.pop()}let l=[],c=[],u=a.map(t=>{if(!t.match(/^\[.+\]$/))return c.push(t),t;{let r=t.slice(1,-1);return l.push(r),`{${r}}`}}),d=`${o}://${u.join("/")}`,p=l.length>0?"template":"direct";return{filePath:t,uriTemplate:d,scheme:o,parameters:l,pathSegments:c,type:p}}function hm(t){return Error(`[xmcp] Invalid tool file: ${t}
82
82
  -> Default export must be a tool handler function.`)}async function hh(t){let r=new Map,i=[];for(let n of(await Promise.all(Object.entries(t).map(async([t,r])=>{let i=await r(),n=function(t,r){if("object"!=typeof t||null===t)throw hm(r);let i=Object.keys(t),n=t.default,o=i.filter(t=>"__esModule"!==t);if(0===i.length||1===o.length&&"default"===o[0]&&"object"==typeof n&&null!==n&&0===Object.keys(n).length)return"empty";if(!("default"in t)||void 0===t.default)return"missing-default";if("function"!=typeof t.default)throw hm(r);return"valid"}(i,t);return"empty"===n?{skipped:!0,issue:{path:t,message:"File is empty."}}:"missing-default"===n?{skipped:!0,issue:{path:t,message:"File does not export a default tool handler."}}:{skipped:!1,path:t,toolModule:i}})))){if(n.skipped){i.push(n.issue);continue}r.set(n.path,n.toolModule)}return{toolModules:r,skippedTools:i}}let hf=function(t=console){let r="";return i=>{let n=i.map(({path:t,message:r})=>`${t}:${r}`).sort().join("|");if(n===r||(r=n,0===i.length))return;i.forEach(({path:r,message:i})=>{t.warn(`[xmcp] Failed to load tool file: ${r}
83
- -> ${i}`)});let o=i.length;t.warn(`[xmcp] ${o} tool${1===o?"":"s"} skipped due to empty files or missing default exports`)}}(),hg=INJECTED_TOOLS,hy=INJECTED_PROMPTS,hv=INJECTED_RESOURCES,h_=SERVER_INFO;async function hb(t,r,i,n){let o=await INJECTED_MIDDLEWARE?.(),a=function(t){if(void 0===t)return[];let r=Array.isArray(t)?[...t]:[t];if(!r.every(t=>"function"==typeof t))throw Error("src/middleware.ts must export mcp as a function or an array of functions");return r}(o?.mcp),s="undefined"!=typeof OBSERVABILITY_CONFIG&&OBSERVABILITY_CONFIG.enabled?function(t=t=>console.error(t)){let r=new Map,i=[];function n(r){try{t(JSON.stringify({"@timestamp":new Date().toISOString(),...r}))}catch{}}return{middleware:async(t,o)=>{let a,s,l;if("tools/call"!==t.method&&"prompts/get"!==t.method&&"resources/read"!==t.method)return o();try{s=performance.now(),a={log:{level:"info"},...function(t){let r=t.http?.headers.traceparent;if("string"!=typeof r)return{};let i=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/.exec(r);return!i||"ff"===i[1]||/^0+$/.test(i[2])||/^0+$/.test(i[3])||"00"===i[1]&&void 0!==i[5]?{}:{trace:{id:i[2]},parent:{id:i[3]}}}(t),transaction:{id:crypto.randomUUID()},...t.http?{http:{request:{id:t.http.id}}}:{},xmcp:{method:t.method,component:"resources/read"===t.method?function(t){try{let n=new URL(t).href;return r.get(n)??i.find(({template:t})=>t.uriTemplate.match(n))?.name??"unknown"}catch{return"unknown"}}(t.params.uri):t.params.name}}}catch{return o()}n({...a,event:{kind:"event",category:["api"],type:["start"],action:"execution.start"}});let c="unknown";try{let r=await o();try{c=t.signal.aborted?"cancelled":c2(r)?"input_required":"isError"in r&&!0===r.isError?"failure":"success","failure"===c&&(l={message:"Operation returned an error result"})}catch{}return r}catch(r){throw l={message:"cancelled"==(c=t.signal.aborted?"cancelled":"failure")?"Operation cancelled":"Operation threw an exception"},r}finally{try{n({...a,log:{level:"failure"===c?"error":"info"},event:{kind:"event",category:["api"],type:["end"],action:"execution.end",duration:Math.round((performance.now()-s)*1e6),outcome:"success"===c?"success":"failure"===c?"failure":"unknown"},xmcp:{...a.xmcp,status:c},...l?{error:l}:{}})}catch{}}},registerResource(t,n){try{"string"==typeof n?r.set(new URL(n).href,t):i.push({name:t,template:n})}catch{}}}}():void 0;s&&a.unshift(s.middleware),dV.clear();let l="undefined"==typeof COMPONENTS_CONFIG?void 0:COMPONENTS_CONFIG;return!function(t,r,i){let n=t.server,o=n.setRequestHandler,a=pS(r);n.setRequestHandler=(t,...r)=>{if(pw.has(t)&&1===r.length&&"function"==typeof r[0]){let t=r[0];r[0]=(r,i)=>a({method:r.method,params:r.params??{}},i,()=>t(r,i))}Reflect.apply(o,n,[t,...r])};try{i()}finally{n.setRequestHandler=o}}(t,a,()=>{var o,c;!function(t,r,i=[]){r.forEach((r,n)=>{var o,a;let s,l,c,u,d={name:hr(n),description:"No description provided"},{default:p,metadata:m,schema:h,outputSchema:f}=r;if("object"==typeof m&&null!==m&&Object.assign(d,m),!1===d.enabled)return;if("function"==typeof p&&"__x402"in p){let t=F.g.__XMCP_X402_REGISTRY;t&&t.set(d.name,p.__x402)}let g={};if(ht(h)?g=h:null!=h&&console.warn(`Invalid schema for tool "${d.name}" at ${n}. Expected Record<string, z.ZodType>`),null!=f)if(ht(f))s=f;else throw Error(`Invalid outputSchema for tool "${d.name}" at ${n}. Expected Record<string, z.ZodType>`);d.annotations={...d.annotations??{}},void 0===d.annotations.title&&(d.annotations.title=d.name),d._meta={...dD(d)._meta};let y=pR(n),v=!!(o=d._meta)&&"object"==typeof o&&"ui"in o&&"object"==typeof o.ui||y,_=d._meta;if(v){let t=`ui://app/${d.name}.html`;d._meta.ui||(d._meta.ui={}),d._meta.ui.resourceUri||(d._meta.ui.resourceUri=t);let r=function(t){let r={},i={};if(t.ui&&"object"==typeof t.ui){let n=t.ui,o={},a={};for(let[t,r]of Object.entries(n))m8.includes(t)?o[t]=r:he.includes(t)?a[t]=r:o[t]=r;Object.keys(o).length>0&&(r.ui=o),Object.keys(a).length>0&&(i.ui=a)}for(let[i,n]of Object.entries(t))"ui"!==i&&(r[i]=n);return{toolMeta:r,resourceMeta:i}}(_);_=r.toolMeta;let i=r.resourceMeta;i.ui=i.ui||{},i.ui.csp=i.ui.csp||{},i.ui.csp.resourceDomains=i.ui.csp.resourceDomains||[],i.ui.csp.resourceDomains.includes("https://esm.sh")||i.ui.csp.resourceDomains.push("https://esm.sh"),dV.add(d.name,{name:d.name,uri:t,handler:p,mimeType:"text/html;profile=mcp-app",_meta:i,toolPath:y?n:void 0})}let b=m7(_),S=v?b:void 0;l=pR(n)&&v?async(t,r)=>({content:[{type:"text",text:""}],_meta:S,structuredContent:{args:t}}):function(t,r,i,n="unknown-tool"){return async(o,a)=>{let s,l,c=t(o,(s=pb(a),l=function(t){if(!t)return;let r={};return t.headers.forEach((t,i)=>{r[i]=t}),r}(a.http?.req),{signal:a.mcpReq.signal,authInfo:a.http?.authInfo,sessionId:a.sessionId,_meta:a.mcpReq._meta,requestId:a.mcpReq.id,requestInfo:l?{headers:l}:void 0,clientInfo:s,sendNotification:t=>a.mcpReq.notify(t),sendRequest:(t,r,i)=>a.mcpReq.send(t,r,i),elicit:(t,r)=>pi(a,t,r),sample:(t,r)=>ph(a,t,r),inputResponses:a.mcpReq.inputResponses,requestState:a.mcpReq.requestState}));if(c instanceof Promise&&(c=await c),c2(c))return c;if("string"==typeof c||"number"==typeof c){if(i){let t=Object.entries(i);if(1===t.length){let[r,i]=t[0];try{return i.parse(c),{content:[{type:"text",text:"number"==typeof c?`${c}`:c}],structuredContent:{[r]:c}}}catch{}}}return p_(r)?{content:[{type:"text",text:""}],structuredContent:{args:o},_meta:r}:{content:[{type:"text",text:"number"==typeof c?`${c}`:c}]}}if(!i||!c||"object"!=typeof c||Array.isArray(c)||"structuredContent"in c||"content"in c&&Array.isArray(c.content)||"_meta"in c||"isError"in c||(pv(c,i,n,"returned data that does not match outputSchema"),c={structuredContent:c}),c&&"object"==typeof c&&"_meta"in c&&!("content"in c)&&!("structuredContent"in c)){let t=c._meta;if(p_(t))return{content:[{type:"text",text:""}],_meta:t}}if(!c||"object"!=typeof c){let t=null===c?"null":typeof c,r=void 0===c?"undefined":null===c?"null":"object"==typeof c?JSON.stringify(c,null,2):String(c);throw Error(`Tool handler must return a CallToolResult, string, or number. Got ${t}: ${r}
83
+ -> ${i}`)});let o=i.length;t.warn(`[xmcp] ${o} tool${1===o?"":"s"} skipped due to empty files or missing default exports`)}}(),hg=INJECTED_TOOLS,hy=INJECTED_PROMPTS,hv=INJECTED_RESOURCES,h_=SERVER_INFO;async function hb(t,r,i,n){let o=await INJECTED_MIDDLEWARE?.(),a=function(t){if(void 0===t)return[];let r=Array.isArray(t)?[...t]:[t];if(!r.every(t=>"function"==typeof t))throw Error("src/middleware.ts must export mcp as a function or an array of functions");return r}(o?.mcp),s="undefined"!=typeof OBSERVABILITY_CONFIG&&OBSERVABILITY_CONFIG.enabled?function(t=t=>console.error(t)){let r=new Map,i=[];function n(r){try{t(JSON.stringify({"@timestamp":new Date().toISOString(),...r}))}catch{}}return{middleware:async(t,o)=>{let a,s,l;if("tools/call"!==t.method&&"prompts/get"!==t.method&&"resources/read"!==t.method)return o();try{s=performance.now(),a={log:{level:"info"},...function(t){let r=t.http?.headers.traceparent;if("string"!=typeof r)return{};let i=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/.exec(r);return!i||"ff"===i[1]||/^0+$/.test(i[2])||/^0+$/.test(i[3])||"00"===i[1]&&void 0!==i[5]?{}:{trace:{id:i[2]},parent:{id:i[3]}}}(t),transaction:{id:crypto.randomUUID()},...t.http?{http:{request:{id:t.http.id}}}:{},xmcp:{method:t.method,component:"resources/read"===t.method?function(t){try{let n=new URL(t).href;return r.get(n)??i.find(({template:t})=>t.uriTemplate.match(n))?.name??"unknown"}catch{return"unknown"}}(t.params.uri):t.params.name}}}catch{return o()}n({...a,event:{kind:"event",category:["api"],type:["start"],action:"execution.start"}});let c="unknown";try{let r=await o();try{c=t.signal.aborted?"cancelled":c2(r)?"input_required":"isError"in r&&!0===r.isError?"failure":"success","failure"===c&&(l={message:"Operation returned an error result"})}catch{}return r}catch(r){throw l={message:"cancelled"==(c=t.signal.aborted?"cancelled":"failure")?"Operation cancelled":"Operation threw an exception"},r}finally{try{n({...a,log:{level:"failure"===c?"error":"info"},event:{kind:"event",category:["api"],type:["end"],action:"execution.end",duration:Math.round((performance.now()-s)*1e6),outcome:"success"===c?"success":"failure"===c?"failure":"unknown"},xmcp:{...a.xmcp,status:c},...l?{error:l}:{}})}catch{}}},registerResource(t,n){try{"string"==typeof n?r.set(new URL(n).href,t):i.push({name:t,template:n})}catch{}}}}():void 0;s&&a.unshift(s.middleware),d1.clear();let l="undefined"==typeof COMPONENTS_CONFIG?void 0:COMPONENTS_CONFIG;return!function(t,r,i){let n=t.server,o=n.setRequestHandler,a=pS(r);n.setRequestHandler=(t,...r)=>{if(pw.has(t)&&1===r.length&&"function"==typeof r[0]){let t=r[0];r[0]=(r,i)=>a({method:r.method,params:r.params??{}},i,()=>t(r,i))}Reflect.apply(o,n,[t,...r])};try{i()}finally{n.setRequestHandler=o}}(t,a,()=>{var o,c;!function(t,r,i=[]){r.forEach((r,n)=>{var o,a;let s,l,c,u,d={name:hr(n),description:"No description provided"},{default:p,metadata:m,schema:h,outputSchema:f}=r;if("object"==typeof m&&null!==m&&Object.assign(d,m),!1===d.enabled)return;if("function"==typeof p&&"__x402"in p){let t=F.g.__XMCP_X402_REGISTRY;t&&t.set(d.name,p.__x402)}let g={};if(ht(h)?g=h:null!=h&&console.warn(`Invalid schema for tool "${d.name}" at ${n}. Expected Record<string, z.ZodType>`),null!=f)if(ht(f))s=f;else throw Error(`Invalid outputSchema for tool "${d.name}" at ${n}. Expected Record<string, z.ZodType>`);d.annotations={...d.annotations??{}},void 0===d.annotations.title&&(d.annotations.title=d.name),d._meta={...d0(d)._meta};let y=pR(n),v=!!(o=d._meta)&&"object"==typeof o&&"ui"in o&&"object"==typeof o.ui||y,_=d._meta;if(v){let t=`ui://app/${d.name}.html`;d._meta.ui||(d._meta.ui={}),d._meta.ui.resourceUri||(d._meta.ui.resourceUri=t);let r=function(t){let r={},i={};if(t.ui&&"object"==typeof t.ui){let n=t.ui,o={},a={};for(let[t,r]of Object.entries(n))m8.includes(t)?o[t]=r:he.includes(t)?a[t]=r:o[t]=r;Object.keys(o).length>0&&(r.ui=o),Object.keys(a).length>0&&(i.ui=a)}for(let[i,n]of Object.entries(t))"ui"!==i&&(r[i]=n);return{toolMeta:r,resourceMeta:i}}(_);_=r.toolMeta;let i=r.resourceMeta;i.ui=i.ui||{},i.ui.csp=i.ui.csp||{},i.ui.csp.resourceDomains=i.ui.csp.resourceDomains||[],i.ui.csp.resourceDomains.includes("https://esm.sh")||i.ui.csp.resourceDomains.push("https://esm.sh"),d1.add(d.name,{name:d.name,uri:t,handler:p,mimeType:"text/html;profile=mcp-app",_meta:i,toolPath:y?n:void 0})}let b=m7(_),S=v?b:void 0;l=pR(n)&&v?async(t,r)=>({content:[{type:"text",text:""}],_meta:S,structuredContent:{args:t}}):function(t,r,i,n="unknown-tool"){return async(o,a)=>{let s,l,c=t(o,(s=pb(a),l=function(t){if(!t)return;let r={};return t.headers.forEach((t,i)=>{r[i]=t}),r}(a.http?.req),{signal:a.mcpReq.signal,authInfo:a.http?.authInfo,sessionId:a.sessionId,_meta:a.mcpReq._meta,requestId:a.mcpReq.id,requestInfo:l?{headers:l}:void 0,clientInfo:s,sendNotification:t=>a.mcpReq.notify(t),sendRequest:(t,r,i)=>a.mcpReq.send(t,r,i),elicit:(t,r)=>pi(a,t,r),sample:(t,r)=>ph(a,t,r),inputResponses:a.mcpReq.inputResponses,requestState:a.mcpReq.requestState}));if(c instanceof Promise&&(c=await c),c2(c))return c;if("string"==typeof c||"number"==typeof c){if(i){let t=Object.entries(i);if(1===t.length){let[r,i]=t[0];try{return i.parse(c),{content:[{type:"text",text:"number"==typeof c?`${c}`:c}],structuredContent:{[r]:c}}}catch{}}}return p_(r)?{content:[{type:"text",text:""}],structuredContent:{args:o},_meta:r}:{content:[{type:"text",text:"number"==typeof c?`${c}`:c}]}}if(!i||!c||"object"!=typeof c||Array.isArray(c)||"structuredContent"in c||"content"in c&&Array.isArray(c.content)||"_meta"in c||"isError"in c||(pv(c,i,n,"returned data that does not match outputSchema"),c={structuredContent:c}),c&&"object"==typeof c&&"_meta"in c&&!("content"in c)&&!("structuredContent"in c)){let t=c._meta;if(p_(t))return{content:[{type:"text",text:""}],_meta:t}}if(!c||"object"!=typeof c){let t=null===c?"null":typeof c,r=void 0===c?"undefined":null===c?"null":"object"==typeof c?JSON.stringify(c,null,2):String(c);throw Error(`Tool handler must return a CallToolResult, string, or number. Got ${t}: ${r}
84
84
 
85
85
  Expected CallToolResult format:
86
86
  {
@@ -160,7 +160,7 @@ Expected formats:
160
160
  - Image content: { type: "image", data: "base64data", mimeType: "image/jpeg" }
161
161
  - Audio content: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }
162
162
  - Resource link: { type: "resource_link", name: "resource name", uri: "resource://uri" }
163
- - All content types support an optional "_meta" object property`)}}if("user"!==r&&"assistant"!==r)throw Error(`Invalid role: ${r}`);return{messages:[{role:r,content:o}]}}}(s,o.role||"assistant");ht(c)?Object.assign(a,c):null!=c&&console.warn(`Invalid schema for prompt "${o.name}" at ${i}. Expected Record<string, z.ZodType>`),t.registerPrompt(o.name,{title:o.title,description:o.description,icons:o.icons,_meta:dD(o)._meta,argsSchema:m6(a)},u)}),o=hn(n,l),c=s?.registerResource,[...dV.getAll()].forEach(([r,i])=>{let n=i.mimeType||"text/html;profile=mcp-app",o=i?._meta?m7(i._meta):void 0,a={name:i.name,description:`Auto-generated resource for ${i.name} tool`,mimeType:i.mimeType,_meta:o},s=async(t,r)=>{if(i.mimeType&&i.toolPath)try{var o;let t,r,a=(o=i.toolPath,IS_CLOUDFLARE?function(t){let{normalizedPath:r,baseName:i}=hd(t),n=5381;for(let t=0;t<r.length;t++)n=Math.imul(n,33)+r.charCodeAt(t)>>>0;let o=n.toString(16).slice(0,6).padStart(6,"0");return`${i}_${o}`}(o):function(t){let{normalizedPath:r,baseName:i}=hd(t),n=F(Object(function(){var t=Error("Cannot find module 'crypto'");throw t.code="MODULE_NOT_FOUND",t}())).createHash("md5").update(r).digest("hex").slice(0,6);return`${i}_${n}`}(o)),s=function(t){if(INJECTED_CLIENT_BUNDLES)return INJECTED_CLIENT_BUNDLES[t]||null;if(!IS_CLOUDFLARE)try{let r=F(Object(function(){var t=Error("Cannot find module 'fs'");throw t.code="MODULE_NOT_FOUND",t}())),i=F(Object(function(){var t=Error("Cannot find module 'path'");throw t.code="MODULE_NOT_FOUND",t}()));for(let n of[i.join(process.cwd(),"dist","client"),i.join(process.cwd(),"client")]){let o=i.join(n,`${t}.bundle.js`),a=i.join(n,`${t}.bundle.css`);if(r.existsSync(o)){let t,i=r.readFileSync(o,"utf-8");return r.existsSync(a)&&(t=r.readFileSync(a,"utf-8")),{js:i,css:t}}}}catch{}return null}(a);if(!s)throw Error(`React client bundle not found for "${i.name}" (bundle: "${a}").
163
+ - All content types support an optional "_meta" object property`)}}if("user"!==r&&"assistant"!==r)throw Error(`Invalid role: ${r}`);return{messages:[{role:r,content:o}]}}}(s,o.role||"assistant");ht(c)?Object.assign(a,c):null!=c&&console.warn(`Invalid schema for prompt "${o.name}" at ${i}. Expected Record<string, z.ZodType>`),t.registerPrompt(o.name,{title:o.title,description:o.description,icons:o.icons,_meta:d0(o)._meta,argsSchema:m6(a)},u)}),o=hn(n,l),c=s?.registerResource,[...d1.getAll()].forEach(([r,i])=>{let n=i.mimeType||"text/html;profile=mcp-app",o=i?._meta?m7(i._meta):void 0,a={name:i.name,description:`Auto-generated resource for ${i.name} tool`,mimeType:i.mimeType,_meta:o},s=async(t,r)=>{if(i.mimeType&&i.toolPath)try{var o;let t,r,a=(o=i.toolPath,IS_CLOUDFLARE?function(t){let{normalizedPath:r,baseName:i}=hd(t),n=5381;for(let t=0;t<r.length;t++)n=Math.imul(n,33)+r.charCodeAt(t)>>>0;let o=n.toString(16).slice(0,6).padStart(6,"0");return`${i}_${o}`}(o):function(t){let{normalizedPath:r,baseName:i}=hd(t),n=F(Object(function(){var t=Error("Cannot find module 'crypto'");throw t.code="MODULE_NOT_FOUND",t}())).createHash("md5").update(r).digest("hex").slice(0,6);return`${i}_${n}`}(o)),s=function(t){if(INJECTED_CLIENT_BUNDLES)return INJECTED_CLIENT_BUNDLES[t]||null;if(!IS_CLOUDFLARE)try{let r=F(Object(function(){var t=Error("Cannot find module 'fs'");throw t.code="MODULE_NOT_FOUND",t}())),i=F(Object(function(){var t=Error("Cannot find module 'path'");throw t.code="MODULE_NOT_FOUND",t}()));for(let n of[i.join(process.cwd(),"dist","client"),i.join(process.cwd(),"client")]){let o=i.join(n,`${t}.bundle.js`),a=i.join(n,`${t}.bundle.css`);if(r.existsSync(o)){let t,i=r.readFileSync(o,"utf-8");return r.existsSync(a)&&(t=r.readFileSync(a,"utf-8")),{js:i,css:t}}}}catch{}return null}(a);if(!s)throw Error(`React client bundle not found for "${i.name}" (bundle: "${a}").
164
164
  React tool bundles are generated automatically when you run "xmcp build" (or "xmcp dev").
165
165
  Please re-run the build so the framework can regenerate the bundle.`);let l=s.js,c=s.css,u=(t=`
166
166
  <script type="module">
@@ -224,7 +224,7 @@ Expected ReadResourceResult format:
224
224
  { uri: "resource://uri", mimeType: "application/json", text: "json content" },
225
225
  { uri: "resource://uri", blob: base64data }
226
226
  ]
227
- }`)}return a.contents.forEach(t=>{t.uri||(t.uri=r.href)}),a}}(o,i,u);if("direct"===d.type)c?.(n.name,p),t.registerResource(n.name,p,dD(n),m);else{let r=Object.create(null);for(let t of d.parameters)l&&Object.hasOwn(l,t)&&(r[t]=l[t]);let i=new dS(p,{list:void 0,complete:r}),a=async(t,r,i)=>{let n={};for(let t of d.parameters){let i=r[t],o=u[t];if(void 0===i)throw Error(`Missing required parameter: ${t}. Available variables: ${Object.keys(r)}`);o?n[t]=o.parse(i):n[t]=i}let a=o(n,i);return a instanceof Promise&&(a=await a),"string"==typeof a?{contents:[{uri:t.href,text:a}]}:a};c?.(n.name,i),t.registerResource(n.name,i,dD(n),a)}})}),t}async function hS(){let{toolModules:t,skippedTools:r}=await hh(hg);return hf(r),t}async function hw(){let{promptModules:t,skippedPrompts:r}=await ha(hy);return hs(r),t}async function hR(){let{resourceModules:t,skippedResources:r}=await hc(hv);return hu(r),t}async function hk(){let{instructions:t,...r}=h_,i=new db(r,{instructions:t}),n=hS(),o=hw(),a=hR(),[s,l,c]=await Promise.all([n,o,a]);return hb(i,s,l,c)}let hx="This MCP server was bootstrapped with xmcp.",hC={cursor:`
227
+ }`)}return a.contents.forEach(t=>{t.uri||(t.uri=r.href)}),a}}(o,i,u);if("direct"===d.type)c?.(n.name,p),t.registerResource(n.name,p,d0(n),m);else{let r=Object.create(null);for(let t of d.parameters)l&&Object.hasOwn(l,t)&&(r[t]=l[t]);let i=new dS(p,{list:void 0,complete:r}),a=async(t,r,i)=>{let n={};for(let t of d.parameters){let i=r[t],o=u[t];if(void 0===i)throw Error(`Missing required parameter: ${t}. Available variables: ${Object.keys(r)}`);o?n[t]=o.parse(i):n[t]=i}let a=o(n,i);return a instanceof Promise&&(a=await a),"string"==typeof a?{contents:[{uri:t.href,text:a}]}:a};c?.(n.name,i),t.registerResource(n.name,i,d0(n),a)}})}),t}async function hS(){let{toolModules:t,skippedTools:r}=await hh(hg);return hf(r),t}async function hw(){let{promptModules:t,skippedPrompts:r}=await ha(hy);return hs(r),t}async function hR(){let{resourceModules:t,skippedResources:r}=await hc(hv);return hu(r),t}async function hk(){let{instructions:t,...r}=h_,i=new db(r,{instructions:t}),n=hS(),o=hw(),a=hR(),[s,l,c]=await Promise.all([n,o,a]);return hb(i,s,l,c)}let hx="This MCP server was bootstrapped with xmcp.",hC={cursor:`
228
228
  <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
229
229
  <g clip-path="url(#cursor)">
230
230
  <path d="M18.1937 4.73376L10.1872 0.111231C9.93007 -0.0372398 9.61283 -0.0372398 9.35573 0.111231L1.34956 4.73376C1.13344 4.85855 1 5.08934 1 5.33929V14.6606C1 14.9106 1.13344 15.1414 1.34956 15.2662L9.3561 19.8887C9.6132 20.0372 9.93044 20.0372 10.1875 19.8887L18.1941 15.2662C18.4102 15.1414 18.5436 14.9106 18.5436 14.6606V5.33929C18.5436 5.08934 18.4102 4.85855 18.1941 4.73376H18.1937ZM17.6908 5.71291L9.96164 19.1001C9.90939 19.1903 9.77145 19.1535 9.77145 19.049V10.2832C9.77145 10.108 9.67785 9.94603 9.526 9.85808L1.9348 5.47536C1.84459 5.42311 1.88143 5.28517 1.98592 5.28517H17.4442C17.6637 5.28517 17.8009 5.5231 17.6912 5.71329H17.6908V5.71291Z" fill="currentColor" />
@@ -584,7 +584,7 @@ data: ${JSON.stringify({jsonrpc:"2.0",method:t,params:r})}
584
584
  `)},$=t=>{if(!k){t&&x(`event: message
585
585
  data: ${JSON.stringify({jsonrpc:"2.0",id:w,result:{resultType:"complete",_meta:{[oQ]:w,[oY]:c}}})}
586
586
 
587
- `),k=!0;try{h?.()}catch(t){i?.(t instanceof Error?t:Error(String(t)))}void 0!==f&&clearInterval(f),g?.(),a.delete($);try{m.close()}catch{}}},T=new ReadableStream({start(t){m=t;let i=dc({method:"notifications/subscriptions/acknowledged",params:{notifications:S}},w);(C(i.method,i.params),0===Object.keys(S).length)?$(!0):(h=r.subscribe(t=>{if(k||!function(t,r){switch(r.kind){case"tools_list_changed":return!0===t.toolsListChanged;case"prompts_list_changed":return!0===t.promptsListChanged;case"resources_list_changed":return!0===t.resourcesListChanged;case"resource_updated":return void 0!==t.resourceSubscriptions&&t.resourceSubscriptions.includes(r.uri)}}(S,t))return;let r=dc(function(t){switch(t.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:t.uri}}}}(t),w);C(r.method,r.params)}),f=da(o,()=>x(": keepalive\n\n")),a.add($))},cancel(){$(!1)}});if(void 0!==s)if(s.aborted)$(!1);else{let t=()=>$(!1);s.addEventListener("abort",t,{once:!0}),g=()=>s.removeEventListener("abort",t)}return new Response(T,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let t of a)t(!0)},get openCount(){return a.size}}}({bus:f,maxSubscriptions:r.maxSubscriptions??1024,keepAliveMs:r.keepAliveMs??15e3,onerror:h});"json"===a&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let v="reject"===n?void 0:(i=r.keepAliveMs,async(r,n)=>{if("POST"!==r.method.toUpperCase())return dN(405,-32e3,"Method not allowed.");try{let o=await t({era:"legacy",...n?.authInfo!==void 0&&{authInfo:n.authInfo},requestInfo:r}),a=new dA({sessionIdGenerator:void 0,...void 0!==i&&{keepAliveMs:i},...void 0!==s&&{maxRequestBodySize:s}});await o.connect(a);let l=()=>{a.close().catch(()=>{}),o.close().catch(()=>{})};r.signal?.addEventListener("abort",l,{once:!0});let c=await a.handleRequest(r,{...n?.authInfo!==void 0&&{authInfo:n.authInfo},...n?.parsedBody!==void 0&&{parsedBody:n.parsedBody}});if(null===c.body||"text/event-stream"!==uM(c.headers.get("content-type")))return l(),c;let u=c.body.getReader(),d=!1,p=()=>{d||(d=!0,l())},m=new ReadableStream({pull:async t=>{try{let{done:r,value:i}=await u.read();if(r){p(),t.close();return}void 0!==i&&t.enqueue(i)}catch(r){p(),t.error(r)}},cancel:t=>(p(),u.cancel(t).catch(()=>{}))});return new Response(m,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(t){try{h?.(dM(t))}catch{}return dZ(dL(n?.parsedBody))}});async function _(i,n,o){var s,m;let f=i.classification.revision;if(void 0===f||!l0.includes(f)){let t=new cw({supported:[...l0],requested:f??"unknown"});return h(t),dN(400,t.code,t.message,t.data,dL(i.message))}let g=function(t,r){if("request"!==r.messageKind)return;let i=r.message.method;if(void 0===t.protocolVersionHeader){let t=r.classification.revision;return us("version-header-missing","(missing)",void 0===t?"the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent":`the body envelope names protocol version ${t} but the required MCP-Protocol-Version header is absent`,"standard-header-validation")}if(void 0===t.mcpMethodHeader)return us("method-header-missing","(missing)",`the body names method ${i} but the required Mcp-Method header is absent`,"standard-header-validation");let n=function(t,r){let i=Object.hasOwn(ul,t)?ul[t]:void 0;if(void 0===i)return;let n=uu(r)?r[i]:void 0;return{field:i,value:"string"==typeof n?n:void 0}}(i,r.message.params);if(void 0===n)return;let{field:o,value:a}=n;if(void 0===t.mcpNameHeader){if(void 0===a)return;return us("name-header-missing","(missing)",`the body carries params.${o}="${a}" but the required Mcp-Name header is absent`,"standard-header-validation")}let s=uc(t.mcpNameHeader),l=ur(s);return void 0===l?us("name-header-invalid-encoding",s,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==a&&l!==a?us("name-header-mismatch",s,`the body carries params.${o}="${a}" but the Mcp-Name header names "${l}"`,"standard-header-validation"):void 0}({httpMethod:n.method,...dF(n)},i);if(void 0!==g)return h(Error(`Rejected inbound request (${g.cell}): ${g.message}`)),dz(g,dL(i.message));let v="request"===i.messageKind?cB(i.message.params):void 0,_=v?.[oX];if("request"===i.messageKind){let t=Object.hasOwn(lK,s=i.message.method)?lK[s]:void 0;if(void 0!==t){let r=lX(t,_);if(void 0!==r){let t=new cR({requiredCapabilities:r});return h(t),dN(uo[t.code]??400,t.code,t.message,t.data,i.message.id)}}}let b=await t({era:"modern",...void 0!==o&&{authInfo:o},requestInfo:n}),S=b instanceof db?b.server:b;if(dU(S),"request"===i.messageKind&&"subscriptions/listen"===i.message.method){let t=S.getCapabilities(),r=d(S);return b.close().catch(h),y.serve(i.message,n.signal,t,r)}if("request"===i.messageKind&&"tools/call"===i.message.method&&b instanceof db){let t=i.message.params,r="string"==typeof t?.name?t.name:void 0,o=void 0===r?void 0:b.toolInputSchemaJson(r);if(void 0!==o){let r=c3(o);if(r.valid&&r.declarations.length>0){let o=function(t,r,i){for(let n of t){let t=`Mcp-Param-${n.headerName}`,o=i.get(t),a=function(t,r){let i=t;for(let t of r){if(null===i||"object"!=typeof i)return;i=i[t]}return i}(r,n.path);if(null==a)continue;let s=function(t){if("string"==typeof t)return t;if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t)||Number.isInteger(t)&&!Number.isSafeInteger(t))return;return String(t)}}(a);if(void 0===s)continue;if(null===o)return ui("param-header-missing",t,`the body carries ${c8(n.path)}=${JSON.stringify(a)} but the ${t} header is absent`);let l=ur(o);if(void 0===l)return ui("param-header-invalid-encoding",t,`the ${t} header carries an invalid Base64 sentinel value`);if(!(("integer"===n.type||"number"===n.type)&&ut.test(l)&&"number"==typeof a?Number(l)===a:l===s))return ui("param-header-mismatch",t,`the ${t} header decodes to ${JSON.stringify(l)} but the body carries ${c8(n.path)}=${JSON.stringify(a)}`)}}(r.declarations,t?.arguments,n.headers);if(void 0!==o)return b.close().catch(h),h(Error(`Rejected inbound request (${o.cell}): ${o.message}`)),dz(o,i.message.id)}}}if("request"===i.messageKind&&b instanceof db)try{let t=await dp([i.message],o,t=>b.resolveScopeChallenge(t));if(void 0!==t)return b.close().catch(h),dh(t,dm(o))}catch(t){return b.close().catch(h),h(dM(t)),dZ(i.message.id)}dU(S),l(S,f),u(S,l0),void 0!==v&&(m={clientInfo:v[oK],clientCapabilities:_},c(S,m));let w=S.onclose;p.add(S);let R=()=>{p.delete(S),S.onclose===R&&(S.onclose=w),w?.()};S.onclose=R;try{let t=await dO(b,i.message,{classification:i.classification,request:n,...void 0!==o&&{authInfo:o},...void 0!==a&&{responseMode:a},...void 0!==r.keepAliveMs&&{keepAliveMs:r.keepAliveMs}});return"notification"===i.messageKind&&queueMicrotask(()=>void S.close().catch(()=>{})),t}catch(t){if(t instanceof lG&&t.code===lW.ConnectionClosed)return new Response(null,{status:499});return await S.close().catch(()=>{}),p.delete(S),h(dM(t)),dZ(dL(i.message))}}async function b(t,r,i,n){if(void 0!==v)return v(r,{...void 0!==i&&{authInfo:i},...void 0!==n&&{parsedBody:n}});let o=function(t,r){switch(t.reason){case"http-method":return ua("http-method","modern-only-method-not-allowed",405,new c_(-32e3,"Method not allowed."),!0);case"batch":return ua("jsonrpc-shape","modern-only-batch-not-supported",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return ua("jsonrpc-shape","modern-only-response-post",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let i=t.requestedVersion;return ua("era-classification","modern-only-missing-envelope",400,void 0===i?new c_(cv.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...r]}):new cw({supported:[...r],requested:i}),!0)}}}(t,l0);return void 0===o?new Response(null,{status:202}):(h(Error(`Rejected 2025-era request on a modern-only endpoint (${o.cell}): ${o.message}`)),dz(o,dL(n)))}async function S(t,r){let i=r?.authInfo;if("POST"===t.method.toUpperCase()&&!uZ(t.headers.get("content-type")))return h(Error("Unsupported Media Type: Content-Type must be application/json")),dN(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let n=await dH(t,r?.parsedBody,!0,s);if("unreadable-body"===n.step)return dN(400,-32700,"Parse error: the request body could not be read");if("body-too-large"===n.step)return dN(413,-32e3,dI(s));if("no-json-body"===n.step)return void 0!==v?v(n.forwardRequest,{...void 0!==i&&{authInfo:i}}):dN(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:o,body:a,parsedBody:l,forwardRequest:c}=n;try{switch(o.kind){case"reject":return h(Error(`Rejected inbound request (${o.cell}): ${o.message}`)),dz(o,dL(a));case"modern":return await _(o,t,i);case"legacy":return await b(o,c,i,l)}}catch(t){return h(dM(t)),dZ(dL(a))}}return{fetch:async(t,r)=>{if(m)throw Error("This MCP handler has been closed");try{return await S(t,r)}catch(t){return h(dM(t)),dZ(dL(r?.parsedBody))}},notify:g,bus:f,close:async()=>{m=!0,y.closeAll();let t=[...p].map(t=>t.close().catch(()=>{}));p.clear(),await Promise.all(t)}}}(hk,{legacy:"stateless",responseMode:"json",onerror:t=>hz("MCP handler error:",t)});async function hZ(t,r,i,n){let o=crypto.randomUUID(),a=await t.clone().json().catch(()=>void 0),s=(t=>{for(let r of Array.isArray(t)?t:[t]){let t=d9(r);if(t)return t}})(a),l={};return t.headers.forEach((t,r)=>{l[r]=t}),dY({id:o,headers:l,clientInfo:s},async()=>{try{let i=await hM.fetch(t,{authInfo:n,parsedBody:a});return hE(i,r)}catch(t){return console.error("[Cloudflare-MCP] Error handling MCP request:",t),hE(new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}}),r)}})}let hU={async fetch(t,r,i){let n=new URL(t.url).pathname,o=t.headers.get("origin");if(hz(`${t.method} ${n}`),"OPTIONS"===t.method)return new Response(null,{status:204,headers:new Headers(hT(hP,o))});let a=hO.endpoint?.startsWith("/")?hO.endpoint:`/${hO.endpoint||"mcp"}`;if("/health"===n)return hE(new Response(JSON.stringify({status:"ok",transport:"cloudflare-workers",mode:"stateless",auth:"none"}),{status:200,headers:{"Content-Type":"application/json"}}),o);if("/"===n&&"GET"===t.method){var s,l;return hE(new Response((s=hI.name,l=hI.description,`
587
+ `),k=!0;try{h?.()}catch(t){i?.(t instanceof Error?t:Error(String(t)))}void 0!==f&&clearInterval(f),g?.(),a.delete($);try{m.close()}catch{}}},T=new ReadableStream({start(t){m=t;let i=dc({method:"notifications/subscriptions/acknowledged",params:{notifications:S}},w);(C(i.method,i.params),0===Object.keys(S).length)?$(!0):(h=r.subscribe(t=>{if(k||!function(t,r){switch(r.kind){case"tools_list_changed":return!0===t.toolsListChanged;case"prompts_list_changed":return!0===t.promptsListChanged;case"resources_list_changed":return!0===t.resourcesListChanged;case"resource_updated":return void 0!==t.resourceSubscriptions&&t.resourceSubscriptions.includes(r.uri)}}(S,t))return;let r=dc(function(t){switch(t.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:t.uri}}}}(t),w);C(r.method,r.params)}),f=da(o,()=>x(": keepalive\n\n")),a.add($))},cancel(){$(!1)}});if(void 0!==s)if(s.aborted)$(!1);else{let t=()=>$(!1);s.addEventListener("abort",t,{once:!0}),g=()=>s.removeEventListener("abort",t)}return new Response(T,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let t of a)t(!0)},get openCount(){return a.size}}}({bus:f,maxSubscriptions:r.maxSubscriptions??1024,keepAliveMs:r.keepAliveMs??15e3,onerror:h});"json"===a&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let v="reject"===n?void 0:(i=r.keepAliveMs,async(r,n)=>{if("POST"!==r.method.toUpperCase())return dN(405,-32e3,"Method not allowed.");try{let o=await t({era:"legacy",...n?.authInfo!==void 0&&{authInfo:n.authInfo},requestInfo:r}),a=new dA({sessionIdGenerator:void 0,...void 0!==i&&{keepAliveMs:i},...void 0!==s&&{maxRequestBodySize:s}});await o.connect(a);let l=()=>{a.close().catch(()=>{}),o.close().catch(()=>{})};r.signal?.addEventListener("abort",l,{once:!0});let c=await a.handleRequest(r,{...n?.authInfo!==void 0&&{authInfo:n.authInfo},...n?.parsedBody!==void 0&&{parsedBody:n.parsedBody}});if(null===c.body||"text/event-stream"!==uM(c.headers.get("content-type")))return l(),c;let u=c.body.getReader(),d=!1,p=()=>{d||(d=!0,l())},m=new ReadableStream({pull:async t=>{try{let{done:r,value:i}=await u.read();if(r){p(),t.close();return}void 0!==i&&t.enqueue(i)}catch(r){p(),t.error(r)}},cancel:t=>(p(),u.cancel(t).catch(()=>{}))});return new Response(m,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(t){try{h?.(dM(t))}catch{}return dZ(dL(n?.parsedBody))}});async function _(i,n,o){var s,m;let f=i.classification.revision;if(void 0===f||!l0.includes(f)){let t=new cw({supported:[...l0],requested:f??"unknown"});return h(t),dN(400,t.code,t.message,t.data,dL(i.message))}let g=function(t,r){if("request"!==r.messageKind)return;let i=r.message.method;if(void 0===t.protocolVersionHeader){let t=r.classification.revision;return us("version-header-missing","(missing)",void 0===t?"the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent":`the body envelope names protocol version ${t} but the required MCP-Protocol-Version header is absent`,"standard-header-validation")}if(void 0===t.mcpMethodHeader)return us("method-header-missing","(missing)",`the body names method ${i} but the required Mcp-Method header is absent`,"standard-header-validation");let n=function(t,r){let i=Object.hasOwn(ul,t)?ul[t]:void 0;if(void 0===i)return;let n=uu(r)?r[i]:void 0;return{field:i,value:"string"==typeof n?n:void 0}}(i,r.message.params);if(void 0===n)return;let{field:o,value:a}=n;if(void 0===t.mcpNameHeader){if(void 0===a)return;return us("name-header-missing","(missing)",`the body carries params.${o}="${a}" but the required Mcp-Name header is absent`,"standard-header-validation")}let s=uc(t.mcpNameHeader),l=ur(s);return void 0===l?us("name-header-invalid-encoding",s,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==a&&l!==a?us("name-header-mismatch",s,`the body carries params.${o}="${a}" but the Mcp-Name header names "${l}"`,"standard-header-validation"):void 0}({httpMethod:n.method,...dF(n)},i);if(void 0!==g)return h(Error(`Rejected inbound request (${g.cell}): ${g.message}`)),dz(g,dL(i.message));let v="request"===i.messageKind?cB(i.message.params):void 0,_=v?.[oX];if("request"===i.messageKind){let t=Object.hasOwn(lK,s=i.message.method)?lK[s]:void 0;if(void 0!==t){let r=lX(t,_);if(void 0!==r){let t=new cR({requiredCapabilities:r});return h(t),dN(uo[t.code]??400,t.code,t.message,t.data,i.message.id)}}}let b=await t({era:"modern",...void 0!==o&&{authInfo:o},requestInfo:n}),S=b instanceof db?b.server:b;if(dU(S),"request"===i.messageKind&&"subscriptions/listen"===i.message.method){let t=S.getCapabilities(),r=d(S);return b.close().catch(h),y.serve(i.message,n.signal,t,r)}if("request"===i.messageKind&&"tools/call"===i.message.method&&b instanceof db){let t=i.message.params,r="string"==typeof t?.name?t.name:void 0,o=void 0===r?void 0:b.toolInputSchemaJson(r);if(void 0!==o){let r=c3(o);if(r.valid&&r.declarations.length>0){let o=function(t,r,i){for(let n of t){let t=`Mcp-Param-${n.headerName}`,o=i.get(t),a=function(t,r){let i=t;for(let t of r){if(null===i||"object"!=typeof i)return;i=i[t]}return i}(r,n.path);if(null==a)continue;let s=function(t){if("string"==typeof t)return t;if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t)||Number.isInteger(t)&&!Number.isSafeInteger(t))return;return String(t)}}(a);if(void 0===s)continue;if(null===o)return ui("param-header-missing",t,`the body carries ${c8(n.path)}=${JSON.stringify(a)} but the ${t} header is absent`);let l=ur(o);if(void 0===l)return ui("param-header-invalid-encoding",t,`the ${t} header carries an invalid Base64 sentinel value`);if(!(("integer"===n.type||"number"===n.type)&&ut.test(l)&&"number"==typeof a?Number(l)===a:l===s))return ui("param-header-mismatch",t,`the ${t} header decodes to ${JSON.stringify(l)} but the body carries ${c8(n.path)}=${JSON.stringify(a)}`)}}(r.declarations,t?.arguments,n.headers);if(void 0!==o)return b.close().catch(h),h(Error(`Rejected inbound request (${o.cell}): ${o.message}`)),dz(o,i.message.id)}}}if("request"===i.messageKind&&b instanceof db)try{let t=await dp([i.message],o,t=>b.resolveScopeChallenge(t));if(void 0!==t)return b.close().catch(h),dh(t,dm(o))}catch(t){return b.close().catch(h),h(dM(t)),dZ(i.message.id)}dU(S),l(S,f),u(S,l0),void 0!==v&&(m={clientInfo:v[oK],clientCapabilities:_},c(S,m));let w=S.onclose;p.add(S);let R=()=>{p.delete(S),S.onclose===R&&(S.onclose=w),w?.()};S.onclose=R;try{let t=await dO(b,i.message,{classification:i.classification,request:n,...void 0!==o&&{authInfo:o},...void 0!==a&&{responseMode:a},...void 0!==r.keepAliveMs&&{keepAliveMs:r.keepAliveMs}});return"notification"===i.messageKind&&queueMicrotask(()=>void S.close().catch(()=>{})),t}catch(t){if(t instanceof lG&&t.code===lW.ConnectionClosed)return new Response(null,{status:499});return await S.close().catch(()=>{}),p.delete(S),h(dM(t)),dZ(dL(i.message))}}async function b(t,r,i,n){if(void 0!==v)return v(r,{...void 0!==i&&{authInfo:i},...void 0!==n&&{parsedBody:n}});let o=function(t,r){switch(t.reason){case"http-method":return ua("http-method","modern-only-method-not-allowed",405,new c_(-32e3,"Method not allowed."),!0);case"batch":return ua("jsonrpc-shape","modern-only-batch-not-supported",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return ua("jsonrpc-shape","modern-only-response-post",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let i=t.requestedVersion;return ua("era-classification","modern-only-missing-envelope",400,void 0===i?new c_(cv.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...r]}):new cw({supported:[...r],requested:i}),!0)}}}(t,l0);return void 0===o?new Response(null,{status:202}):(h(Error(`Rejected 2025-era request on a modern-only endpoint (${o.cell}): ${o.message}`)),dz(o,dL(n)))}async function S(t,r){let i=r?.authInfo;if("POST"===t.method.toUpperCase()&&!uZ(t.headers.get("content-type")))return h(Error("Unsupported Media Type: Content-Type must be application/json")),dN(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let n=await dH(t,r?.parsedBody,!0,s);if("unreadable-body"===n.step)return dN(400,-32700,"Parse error: the request body could not be read");if("body-too-large"===n.step)return dN(413,-32e3,dI(s));if("no-json-body"===n.step)return void 0!==v?v(n.forwardRequest,{...void 0!==i&&{authInfo:i}}):dN(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:o,body:a,parsedBody:l,forwardRequest:c}=n;try{switch(o.kind){case"reject":return h(Error(`Rejected inbound request (${o.cell}): ${o.message}`)),dz(o,dL(a));case"modern":return await _(o,t,i);case"legacy":return await b(o,c,i,l)}}catch(t){return h(dM(t)),dZ(dL(a))}}return{fetch:async(t,r)=>{if(m)throw Error("This MCP handler has been closed");try{return await S(t,r)}catch(t){return h(dM(t)),dZ(dL(r?.parsedBody))}},notify:g,bus:f,close:async()=>{m=!0,y.closeAll();let t=[...p].map(t=>t.close().catch(()=>{}));p.clear(),await Promise.all(t)}}}(hk,{legacy:"stateless",responseMode:"json",maxSubscriptions:hO.maxSubscriptions,onerror:t=>hz("MCP handler error:",t)});async function hZ(t,r,i,n){let o=crypto.randomUUID(),a=await t.clone().json().catch(()=>void 0),s=(t=>{for(let r of Array.isArray(t)?t:[t]){let t=dX(r);if(t)return t}})(a),l={};return t.headers.forEach((t,r)=>{l[r]=t}),dG({id:o,headers:l,clientInfo:s},async()=>{try{let i=await hM.fetch(t,{authInfo:n,parsedBody:a});return hE(i,r)}catch(t){return console.error("[Cloudflare-MCP] Error handling MCP request:",t),hE(new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}}),r)}})}let hU={async fetch(t,r,i){let n=new URL(t.url).pathname,o=t.headers.get("origin");if(hz(`${t.method} ${n}`),"OPTIONS"===t.method)return new Response(null,{status:204,headers:new Headers(hT(hP,o))});let a=hO.endpoint?.startsWith("/")?hO.endpoint:`/${hO.endpoint||"mcp"}`;if("/health"===n)return hE(new Response(JSON.stringify({status:"ok",transport:"cloudflare-workers",mode:"stateless",auth:"none"}),{status:200,headers:{"Content-Type":"application/json"}}),o);if("/"===n&&"GET"===t.method){var s,l;return hE(new Response((s=hI.name,l=hI.description,`
588
588
  <!DOCTYPE html>
589
589
  <html lang="en">
590
590
  <head>