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.
- package/README.md +36 -12
- package/dist/client.js +1 -1
- package/dist/config/index.d.ts +7 -0
- package/dist/config/schemas/transport/http.d.ts +16 -0
- package/dist/config.js +1 -1
- package/dist/index.js +1 -1
- package/dist/runtime/adapter-express.js +23 -23
- package/dist/runtime/adapter-fastify.js +23 -23
- package/dist/runtime/adapter-fetch-cloudflare.js +5 -5
- package/dist/runtime/adapter-fetch.js +5 -5
- package/dist/runtime/adapter-nestjs.js +17 -17
- package/dist/runtime/adapter-nextjs.js +23 -23
- package/dist/runtime/cloudflare-worker.js +5 -5
- package/dist/runtime/http.js +30 -30
- package/dist/runtime/transports/http/base-streamable-http.d.ts +1 -0
- package/dist/runtime/vercel.js +30 -30
- package/package.json +3 -3
|
@@ -70,7 +70,7 @@ data:
|
|
|
70
70
|
`;return n&&(a+=`id: ${n}
|
|
71
71
|
`),a+=`data: ${JSON.stringify(i)}
|
|
72
72
|
|
|
73
|
-
`,t.enqueue(r.encode(a)),!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,a,o,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 dq(t,this._maxRequestBodySize);if(r.tooLarge){let t=dE(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=>od.parse(t)):[od.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=>o$.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{a=await this._checkScopeChallenge(n,r?.authInfo)}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(500,-32603,"Internal server error")}if(a)return a;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=>o$.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=>{o=t},cancel:()=>{void 0!==s&&clearInterval(s),this._streamMapping.get(u)?.controller===o&&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:o,encoder:m,cleanup:()=>{void 0!==s&&clearInterval(s),this._streamMapping.delete(u);try{o.close()}catch{}}}),this._requestToStreamMapping.set(t.id,u));for(let i of(await this.writePrimingEvent(o,m,u,p),n)){let n,a;cX(i)&&this._eventStore&&this.supportsEmptySSEData(p)&&(n=()=>{this.closeSSEStream(i.id)},a=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(i,{authInfo:r?.authInfo,request:t,closeSSEStream:n,closeStandaloneSSEStream:a})}return this._streamMapping.get(u)?.controller===o&&(s=this.startKeepAlive(o,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 a=this._streamMapping.get(n);if(!this._enableJsonResponse){let r;this._eventStore&&(r=await this._eventStore.storeEvent(n,t),a=this._streamMapping.get(n)),a?.controller&&a?.encoder&&(void 0===r||!a.replayedEventIds?.has(r))&&this.writeSSEEvent(a.controller,a.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(!a){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&&a.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?a.resolveJson(Response.json(i[0],{status:200,headers:t})):a.resolveJson(Response.json(i,{status:200,headers:t})),a.cleanup()}else a.cleanup();for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t)}}}};function dA(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 dz(t,r,i,n,a=null){return Response.json({jsonrpc:"2.0",error:{code:r,message:i,...void 0!==n&&{data:n}},id:a},{status:t})}function dN(t,r=null){return dz(t.httpStatus,t.code,t.message,t.data,r)}function dM(t){return t instanceof Error?t:Error(String(t))}function dL(t=null){return dz(500,-32603,"Internal server error",void 0,t)}function dZ(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 dU(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 dF(t,r,i=!0,n=4194304){let a,o=t.method.toUpperCase(),s=r,l=t,c=!1;if("POST"===o){if(void 0===s){let r;i&&(l=t.clone());try{let i=await dq(t,n);if(i.tooLarge)return{step:"body-too-large"};r=i.text}catch{return{step:"unreadable-body"}}try{a=0===r.length?void 0:JSON.parse(r)}catch{c=!0}c||void 0===a||(s=a)}else a=s;if(c||void 0===a)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 uo("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 uo("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 uo("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,a=t.protocolVersionHeader,o=void 0!==a&&a>=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(o)return us("initialize-with-modern-header",a,"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 o=cB(i),s=(void 0===o?[]:cK(o))[0];if(void 0!==s)return uo("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!==a&&void 0!==l&&a!==l?us("header-body-version-mismatch",a,`the body envelope names protocol version ${l} but the MCP-Protocol-Version header names ${a}`):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(o){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:[aG];return uo("envelope","modern-header-without-claim",400,new c_(cv.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${a}, 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!==a&&{requestedVersion:a}}}(t,r):uu(r)&&cQ(r)?function(t,r){let i=r.params,n=r.method,a=t.protocolVersionHeader,o=void 0!==a&&a>=lQ;if(cW(i)){let o=cG(i);if(void 0===o){let t=cB(i),r=(void 0===t?[]:cK(t)).find(t=>t.key===aG)??{key:aG,problem:"expected a protocol version string"};return uo("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!==a&&a!==o)return us("notification-header-body-version-mismatch",a,`the notification envelope names protocol version ${o} but the MCP-Protocol-Version header names ${a}`);let s=ud(o);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 o?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:a}}:{kind:"legacy",reason:"notification",...void 0!==a&&{requestedVersion:a}}}(t,r):uo("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:o,...dU(t),...void 0!==a&&{body:a}}),body:a,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 dH=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},dV=t=>globalThis[t];function dB({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 a=new x,o=globalThis[n]??{current:null};dJ(n,o);let s={provider:(t,i)=>(r&&(o.current=t),a.run(t,i)),getContext:()=>{let i=a.getStore();if(i)return i;if(r&&o.current)return o.current;throw Error(`getContext() can only be used within the ${t} context.`)},setContext:i=>{let n=a.getStore()??(r?o.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 dW=dB({name:"http-request-context"});dW.setContext;let dG=dW.getContext,dK=dW.provider,dY=dB({name:"request-context",fallback:!1}),dX=dB({name:"client-info-context"});dX.setContext;let dQ=dX.getContext;dX.provider;let d0=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),d1=t=>{if(!d0(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},d2=t=>{if(t&&"initialize"===t.method&&d0(t.params))return d1(t.params.clientInfo)},d9=(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 a=t.trim();return a.length>0?a:void 0}},d4=new Set(["message","mode","requestedSchema"]),d3=new Set(["elicitationId","message","mode","url"]),d6=new Set(["properties","required","type"]),d5=new Set(["default","description","format","maxLength","minLength","title","type"]),d7=new Set(["default","description","enum","enumNames","title","type"]),d8=new Set(["default","description","title","type"]),pe=new Set(["default","description","maximum","minimum","title","type"]),pt=new Set(["date","date-time","email","uri"]);async function pr(t,r,i){let n=function(t){let r=t.mode??"form";if("url"===r)return function(t){let r;pn(t,"Elicitation request must be a plain object."),pi(t,d3,"URL elicitation"),pa(t.message,"URL elicitation requires a string message."),po(t.elicitationId,"URL elicitation requires a non-empty elicitationId."),po(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){pn(t,"Elicitation request must be a plain object."),pi(t,d4,"Form elicitation"),pa(t.message,"Form elicitation requires a string message.");let r=t.requestedSchema;if(pn(r,"Form elicitation requires a flat object schema."),pi(r,d6,"Form elicitation schema"),"object"!==r.type)throw Error('Form elicitation schema must use type "object".');for(let[t,i]of(pn(r.properties,"Form elicitation schema requires a properties object."),Object.entries(r.properties)))!function(t,r){if(pn(r,`Form elicitation field "${t}" must be a plain object.`),ps(r.title,`Form elicitation field "${t}" title must be a string.`),ps(r.description,`Form elicitation field "${t}" description must be a string.`),"string"===r.type&&"enum"in r){var i,n;if(pi(r,d7,`Form elicitation field "${t}"`),pc(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&&pc(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(ps(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)){pi(r,d5,`Form elicitation field "${t}"`),pl(r.minLength,`Form elicitation field "${t}" minLength must be a number.`),pl(r.maxLength,`Form elicitation field "${t}" maxLength must be a number.`),ps(r.default,`Form elicitation field "${t}" default must be a string.`);let i=r.format;if(ps(i,`Form elicitation field "${t}" format must be a string.`),void 0!==i&&!pt.has(i))throw Error(`Form elicitation field "${t}" format must be one of: ${Array.from(pt).join(", ")}.`);return}if("boolean"===r.type){if(pi(r,d8,`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){pi(r,pe,`Form elicitation field "${t}"`),pl(r.minimum,`Form elicitation field "${t}" minimum must be a number.`),pl(r.maximum,`Form elicitation field "${t}" maximum must be a number.`),pl(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 pi(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 pn(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 po(t,r){if("string"!=typeof t||0===t.trim().length)throw Error(r)}function ps(t,r){if(void 0!==t&&"string"!=typeof t)throw Error(r)}function pl(t,r){if(void 0!==t&&"number"!=typeof t)throw Error(r)}function pc(t,r){if(!Array.isArray(t)||t.some(t=>"string"!=typeof t))throw Error(r)}let pu=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),pd=new Set(["task","toolChoice","tools"]),pp=new Set(["text","image","audio"]);async function pm(t,r,i){let n=function(t){ph(t,"Sampling request must be a plain object.");let r=Object.keys(t),i=r.filter(t=>pd.has(t));if(i.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${i.join(", ")}.`);let n=r.filter(t=>!pu.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(ph(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;ph(i,`Sampling message at index ${t} requires a content object.`);let n=i.type;if("string"!=typeof n||!pp.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 ph(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}let pf={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 pg(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=pf[t.type];return r?r(t):{valid:!0}}function py(t,r,i,n){if(null===t||"object"!=typeof t||Array.isArray(t))throw Error(`Tool "${i}" ${n}: expected a plain object.`);let a=new Set(Object.keys(r)),o=Object.keys(t).filter(t=>!a.has(t));if(o.length>0)throw Error(`Tool "${i}" ${n}: unrecognized key(s): ${o.join(", ")}`);for(let[a,o]of Object.entries(r))try{o.parse(t[a])}catch(t){throw Error(`Tool "${i}" ${n}: ${t?.message??`invalid field "${a}"`}`)}}function pv(t){return!!(t&&"object"==typeof t&&Object.keys(t).some(t=>t.startsWith("ui/")))}function p_(t){let r=t.mcpReq.envelope,i=d1(r?.[aK]);if(!i)try{let t,r=dG();i=r.clientInfo??(t=r.headers,d1({name:d9(t,"x-mcp-client-name"),version:d9(t,"x-mcp-client-version"),title:d9(t,"x-mcp-client-title"),websiteUrl:d9(t,"x-mcp-client-website-url"),description:d9(t,"x-mcp-client-description")}))}catch{}if(!i)try{i=dQ().clientInfo}catch{}return i}function pb(t){let r=[...t];return(t,i,n)=>(function(t,r,i){let n,a=new Map;if(t.http){let t=dG(),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 dY.provider(Object.freeze({clientInfo:r?Object.freeze({...r}):void 0,http:n,authInfo:t.http?.authInfo,signal:t.mcpReq.signal,set(t,r){a.set(t,r)},get:t=>a.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,p_(i),async()=>{if(0===r.length)return n();let i=Object.freeze({...function(){try{return dY.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),...t,params:Object.freeze({...t.params})}),a=-1,o=async t=>{if(t<=a)throw Error("MCP middleware next() can only be called once");a=t;let s=r[t];return s?s(i,()=>o(t+1)):n()};return o(0)})}let pS=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function pw(t){return t.endsWith(".tsx")}let pR=Symbol("Let zodToJsonSchema decide on which parser to use"),pk={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"};(C=z||(z={})).assertEqual=t=>{},C.assertIs=function(t){},C.assertNever=function(t){throw Error()},C.arrayToEnum=t=>{let r={};for(let i of t)r[i]=i;return r},C.getValidEnumValues=t=>{let r=C.objectKeys(t).filter(r=>"number"!=typeof t[t[r]]),i={};for(let n of r)i[n]=t[n];return C.objectValues(i)},C.objectValues=t=>C.objectKeys(t).map(function(r){return t[r]}),C.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},C.find=(t,r)=>{for(let i of t)if(r(i))return i},C.isInteger="function"==typeof Number.isInteger?t=>Number.isInteger(t):t=>"number"==typeof t&&Number.isFinite(t)&&Math.floor(t)===t,C.joinValues=function(t,r=" | "){return t.map(t=>"string"==typeof t?`'${t}'`:t).join(r)},C.jsonStringifyReplacer=(t,r)=>"bigint"==typeof r?r.toString():r,(N||(N={})).mergeShapes=(t,r)=>({...t,...r});let px=z.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 px.undefined;case"string":return px.string;case"number":return Number.isNaN(t)?px.nan:px.number;case"boolean":return px.boolean;case"function":return px.function;case"bigint":return px.bigint;case"symbol":return px.symbol;case"object":if(Array.isArray(t))return px.array;if(null===t)return px.null;if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return px.promise;if("undefined"!=typeof Map&&t instanceof Map)return px.map;if("undefined"!=typeof Set&&t instanceof Set)return px.set;if("undefined"!=typeof Date&&t instanceof Date)return px.date;return px.object;default:return px.unknown}},pT=z.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 pO 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 a of t.issues)if("invalid_union"===a.code)a.unionErrors.map(n);else if("invalid_return_type"===a.code)n(a.returnTypeError);else if("invalid_arguments"===a.code)n(a.argumentsError);else if(0===a.path.length)i._errors.push(r(a));else{let t=i,n=0;for(;n<a.path.length;){let i=a.path[n],o=n===a.path.length-1;if("_errors"===i){o&&t._errors.push(r(a)),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],o&&t._errors.push(r(a)),n++}}};return n(this),i}static assert(t){if(!(t instanceof pO))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,z.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()}}pO.create=t=>new pO(t);let pP=(t,r)=>{let i;switch(t.code){case pT.invalid_type:i=t.received===px.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case pT.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,z.jsonStringifyReplacer)}`;break;case pT.unrecognized_keys:i=`Unrecognized key(s) in object: ${z.joinValues(t.keys,", ")}`;break;case pT.invalid_union:i="Invalid input";break;case pT.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${z.joinValues(t.options)}`;break;case pT.invalid_enum_value:i=`Invalid enum value. Expected ${z.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}"`:z.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,z.assertNever(t)}return{message:i}};(E=M||(M={})).errToObj=t=>"string"==typeof t?{message:t}:t||{},E.toString=t=>"string"==typeof t?t:t?.message;let pC=t=>{let{data:r,path:i,errorMaps:n,issueData:a}=t,o=[...i,...a.path||[]],s={...a,path:o};if(void 0!==a.message)return{...a,path:o,message:a.message};let l="";for(let t of n.filter(t=>!!t).slice().reverse())l=t(s,{data:r,defaultError:l}).message;return{...a,path:o,message:l}};function pE(t,r){let i=pC({issueData:r,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pP,void 0].filter(t=>!!t)});t.common.issues.push(i)}class pI{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 pq;"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 pI.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let n of r){let{key:r,value:a}=n;if("aborted"===r.status||"aborted"===a.status)return pq;"dirty"===r.status&&t.dirty(),"dirty"===a.status&&t.dirty(),"__proto__"!==r.value&&(void 0!==a.value||n.alwaysSet)&&(i[r.value]=a.value)}return{status:t.value,value:i}}}let pq=Object.freeze({status:"aborted"}),pj=t=>({status:"dirty",value:t}),pA=t=>({status:"valid",value:t}),pz=t=>"undefined"!=typeof Promise&&t instanceof Promise;class pN{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 pO(t.common.issues);return this._error=r,this._error}}};function pL(t){if(!t)return{};let{errorMap:r,invalid_type_error:i,required_error:n,description:a}=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:a}:{errorMap:(r,a)=>{let{message:o}=t;return"invalid_enum_value"===r.code?{message:o??a.defaultError}:void 0===a.data?{message:o??n??a.defaultError}:"invalid_type"!==r.code?{message:a.defaultError}:{message:o??i??a.defaultError}},description:a}}class pZ{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 pI,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(pz(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 (pz(n)?n:Promise.resolve(n)))}refine(t,r){return this._refinement((i,n)=>{let a=t(i),o=()=>n.addIssue({code:pT.custom,..."string"==typeof r||void 0===r?{message:r}:"function"==typeof r?r(i):r});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(t=>!!t||(o(),!1)):!!a||(o(),!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 mR({schema:this,typeName:L.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 mk.create(this,this._def)}nullable(){return mx.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mo.create(this)}promise(){return mw.create(this,this._def)}or(t){return ml.create([this,t],this._def)}and(t){return md.create(this,t,this._def)}transform(t){return new mR({...pL(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:t}})}default(t){return new m$({...pL(this._def),innerType:this,defaultValue:"function"==typeof t?t:()=>t,typeName:L.ZodDefault})}brand(){return new mP({typeName:L.ZodBranded,type:this,...pL(this._def)})}catch(t){return new mT({...pL(this._def),innerType:this,catchValue:"function"==typeof t?t:()=>t,typeName:L.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return mC.create(this,t)}readonly(){return mE.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let pU=/^c[^\s-]{8,}$/i,pF=/^[0-9a-z]+$/,pD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pH=/^[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,pV=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pB=/^[-+]?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)?)??$/,pW=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,pG=/^(?:(?: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])$/,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])\/(3[0-2]|[12]?[0-9])$/,pY=/^(([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]))$/,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]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,p0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,p1="((\\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])))",p2=RegExp(`^${p1}$`);function p9(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 p4 extends pZ{_parse(t){var r,i,n,a;let o;if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==px.string){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.string,received:r.parsedType}),pq}let s=new pI;for(let l of this._def.checks)if("min"===l.kind)t.data.length<l.value&&(pE(o=this._getOrReturnCtx(t,o),{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&&(pE(o=this._getOrReturnCtx(t,o),{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)&&(o=this._getOrReturnCtx(t,o),r?pE(o,{code:pT.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):i&&pE(o,{code:pT.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),s.dirty())}else if("email"===l.kind)pW.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{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)||(pE(o=this._getOrReturnCtx(t,o),{validation:"emoji",code:pT.invalid_string,message:l.message}),s.dirty());else if("uuid"===l.kind)pH.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"uuid",code:pT.invalid_string,message:l.message}),s.dirty());else if("nanoid"===l.kind)pJ.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"nanoid",code:pT.invalid_string,message:l.message}),s.dirty());else if("cuid"===l.kind)pU.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"cuid",code:pT.invalid_string,message:l.message}),s.dirty());else if("cuid2"===l.kind)pF.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"cuid2",code:pT.invalid_string,message:l.message}),s.dirty());else if("ulid"===l.kind)pD.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"ulid",code:pT.invalid_string,message:l.message}),s.dirty());else if("url"===l.kind)try{new URL(t.data)}catch{pE(o=this._getOrReturnCtx(t,o),{validation:"url",code:pT.invalid_string,message:l.message}),s.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{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)||(pE(o=this._getOrReturnCtx(t,o),{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)||(pE(o=this._getOrReturnCtx(t,o),{code:pT.invalid_string,validation:{startsWith:l.value},message:l.message}),s.dirty()):"endsWith"===l.kind?t.data.endsWith(l.value)||(pE(o=this._getOrReturnCtx(t,o),{code:pT.invalid_string,validation:{endsWith:l.value},message:l.message}),s.dirty()):"datetime"===l.kind?(function(t){let r=`${p1}T${p9(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)||(pE(o=this._getOrReturnCtx(t,o),{code:pT.invalid_string,validation:"datetime",message:l.message}),s.dirty()):"date"===l.kind?p2.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{code:pT.invalid_string,validation:"date",message:l.message}),s.dirty()):"time"===l.kind?RegExp(`^${p9(l)}$`).test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{code:pT.invalid_string,validation:"time",message:l.message}),s.dirty()):"duration"===l.kind?pB.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"duration",code:pT.invalid_string,message:l.message}),s.dirty()):"ip"===l.kind?(r=t.data,!(("v4"===(i=l.version)||!i)&&pG.test(r)||("v6"===i||!i)&&pY.test(r))&&1&&(pE(o=this._getOrReturnCtx(t,o),{validation:"ip",code:pT.invalid_string,message:l.message}),s.dirty())):"jwt"===l.kind?!function(t,r){if(!pV.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,"="),a=JSON.parse(atob(n));if("object"!=typeof a||null===a||"typ"in a&&a?.typ!=="JWT"||!a.alg||r&&a.alg!==r)return!1;return!0}catch{return!1}}(t.data,l.alg)&&(pE(o=this._getOrReturnCtx(t,o),{validation:"jwt",code:pT.invalid_string,message:l.message}),s.dirty()):"cidr"===l.kind?(n=t.data,!(("v4"===(a=l.version)||!a)&&pK.test(n)||("v6"===a||!a)&&pX.test(n))&&1&&(pE(o=this._getOrReturnCtx(t,o),{validation:"cidr",code:pT.invalid_string,message:l.message}),s.dirty())):"base64"===l.kind?pQ.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"base64",code:pT.invalid_string,message:l.message}),s.dirty()):"base64url"===l.kind?p0.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"base64url",code:pT.invalid_string,message:l.message}),s.dirty()):z.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,...M.errToObj(i)})}_addCheck(t){return new p4({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...M.errToObj(t)})}url(t){return this._addCheck({kind:"url",...M.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...M.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...M.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...M.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...M.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...M.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...M.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...M.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...M.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...M.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...M.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...M.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,...M.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,...M.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...M.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...M.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...M.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...M.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...M.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...M.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...M.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...M.errToObj(r)})}nonempty(t){return this.min(1,M.errToObj(t))}trim(){return new p4({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new p4({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new p4({...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}}p4.create=t=>new p4({checks:[],typeName:L.ZodString,coerce:t?.coerce??!1,...pL(t)});class p3 extends pZ{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)!==px.number){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.number,received:r.parsedType}),pq}let i=new pI;for(let n of this._def.checks)"int"===n.kind?z.isInteger(t.data)||(pE(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)&&(pE(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)&&(pE(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,a=i>n?i:n;return Number.parseInt(t.toFixed(a).replace(".",""))%Number.parseInt(r.toFixed(a).replace(".",""))/10**a}(t.data,n.value)&&(pE(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)||(pE(r=this._getOrReturnCtx(t,r),{code:pT.not_finite,message:n.message}),i.dirty()):z.assertNever(n);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,M.toString(r))}gt(t,r){return this.setLimit("min",t,!1,M.toString(r))}lte(t,r){return this.setLimit("max",t,!0,M.toString(r))}lt(t,r){return this.setLimit("max",t,!1,M.toString(r))}setLimit(t,r,i,n){return new p3({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:M.toString(n)}]})}_addCheck(t){return new p3({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:M.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:M.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:M.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.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&&z.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:L.ZodNumber,coerce:t?.coerce||!1,...pL(t)});class p6 extends pZ{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)!==px.bigint)return this._getInvalidInput(t);let i=new pI;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(pE(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)&&(pE(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)&&(pE(r=this._getOrReturnCtx(t,r),{code:pT.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):z.assertNever(n);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.bigint,received:r.parsedType}),pq}gte(t,r){return this.setLimit("min",t,!0,M.toString(r))}gt(t,r){return this.setLimit("min",t,!1,M.toString(r))}lte(t,r){return this.setLimit("max",t,!0,M.toString(r))}lt(t,r){return this.setLimit("max",t,!1,M.toString(r))}setLimit(t,r,i,n){return new p6({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:M.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:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:M.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:L.ZodBigInt,coerce:t?.coerce??!1,...pL(t)});class p5 extends pZ{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==px.boolean){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.boolean,received:r.parsedType}),pq}return pA(t.data)}}p5.create=t=>new p5({typeName:L.ZodBoolean,coerce:t?.coerce||!1,...pL(t)});class p7 extends pZ{_parse(t){let r;if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==px.date){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.date,received:r.parsedType}),pq}if(Number.isNaN(t.data.getTime()))return pE(this._getOrReturnCtx(t),{code:pT.invalid_date}),pq;let i=new pI;for(let n of this._def.checks)"min"===n.kind?t.data.getTime()<n.value&&(pE(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&&(pE(r=this._getOrReturnCtx(t,r),{code:pT.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):z.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new p7({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:M.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:M.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}}p7.create=t=>new p7({checks:[],coerce:t?.coerce||!1,typeName:L.ZodDate,...pL(t)});class p8 extends pZ{_parse(t){if(this._getType(t)!==px.symbol){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.symbol,received:r.parsedType}),pq}return pA(t.data)}}p8.create=t=>new p8({typeName:L.ZodSymbol,...pL(t)});class me extends pZ{_parse(t){if(this._getType(t)!==px.undefined){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.undefined,received:r.parsedType}),pq}return pA(t.data)}}me.create=t=>new me({typeName:L.ZodUndefined,...pL(t)});class mt extends pZ{_parse(t){if(this._getType(t)!==px.null){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.null,received:r.parsedType}),pq}return pA(t.data)}}mt.create=t=>new mt({typeName:L.ZodNull,...pL(t)});class mr extends pZ{constructor(){super(...arguments),this._any=!0}_parse(t){return pA(t.data)}}mr.create=t=>new mr({typeName:L.ZodAny,...pL(t)});class mi extends pZ{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pA(t.data)}}mi.create=t=>new mi({typeName:L.ZodUnknown,...pL(t)});class mn extends pZ{_parse(t){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.never,received:r.parsedType}),pq}}mn.create=t=>new mn({typeName:L.ZodNever,...pL(t)});class ma extends pZ{_parse(t){if(this._getType(t)!==px.undefined){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.void,received:r.parsedType}),pq}return pA(t.data)}}ma.create=t=>new ma({typeName:L.ZodVoid,...pL(t)});class mo extends pZ{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),n=this._def;if(r.parsedType!==px.array)return pE(r,{code:pT.invalid_type,expected:px.array,received:r.parsedType}),pq;if(null!==n.exactLength){let t=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(t||a)&&(pE(r,{code:t?pT.too_big:pT.too_small,minimum:a?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&&(pE(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&&(pE(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 pN(r,t,r.path,i)))).then(t=>pI.mergeArray(i,t));let a=[...r.data].map((t,i)=>n.type._parseSync(new pN(r,t,r.path,i)));return pI.mergeArray(i,a)}get element(){return this._def.type}min(t,r){return new mo({...this._def,minLength:{value:t,message:M.toString(r)}})}max(t,r){return new mo({...this._def,maxLength:{value:t,message:M.toString(r)}})}length(t,r){return new mo({...this._def,exactLength:{value:t,message:M.toString(r)}})}nonempty(t){return this.min(1,t)}}mo.create=(t,r)=>new mo({type:t,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...pL(r)});class ms extends pZ{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=z.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==px.object){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.object,received:r.parsedType}),pq}let{status:r,ctx:i}=this._processInputParams(t),{shape:n,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof mn&&"strip"===this._def.unknownKeys))for(let t in i.data)a.includes(t)||o.push(t);let s=[];for(let t of a){let r=n[t],a=i.data[t];s.push({key:{status:"valid",value:t},value:r._parse(new pN(i,a,i.path,t)),alwaysSet:t in i.data})}if(this._def.catchall instanceof mn){let t=this._def.unknownKeys;if("passthrough"===t)for(let t of o)s.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===t)o.length>0&&(pE(i,{code:pT.unrecognized_keys,keys:o}),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 o){let n=i.data[r];s.push({key:{status:"valid",value:r},value:t._parse(new pN(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=>pI.mergeObjectSync(r,t)):pI.mergeObjectSync(r,s)}get shape(){return this._def.shape()}strict(t){return M.errToObj,new ms({...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:M.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new ms({...this._def,unknownKeys:"strip"})}passthrough(){return new ms({...this._def,unknownKeys:"passthrough"})}extend(t){return new ms({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ms({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:L.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new ms({...this._def,catchall:t})}pick(t){let r={};for(let i of z.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new ms({...this._def,shape:()=>r})}omit(t){let r={};for(let i of z.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new ms({...this._def,shape:()=>r})}deepPartial(){return function t(r){if(r instanceof ms){let i={};for(let n in r.shape){let a=r.shape[n];i[n]=mk.create(t(a))}return new ms({...r._def,shape:()=>i})}if(r instanceof mo)return new mo({...r._def,type:t(r.element)});if(r instanceof mk)return mk.create(t(r.unwrap()));if(r instanceof mx)return mx.create(t(r.unwrap()));if(r instanceof mp)return mp.create(r.items.map(r=>t(r)));else return r}(this)}partial(t){let r={};for(let i of z.objectKeys(this.shape)){let n=this.shape[i];t&&!t[i]?r[i]=n:r[i]=n.optional()}return new ms({...this._def,shape:()=>r})}required(t){let r={};for(let i of z.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let t=this.shape[i];for(;t instanceof mk;)t=t._def.innerType;r[i]=t}return new ms({...this._def,shape:()=>r})}keyof(){return m_(z.objectKeys(this.shape))}}ms.create=(t,r)=>new ms({shape:()=>t,unknownKeys:"strip",catchall:mn.create(),typeName:L.ZodObject,...pL(r)}),ms.strictCreate=(t,r)=>new ms({shape:()=>t,unknownKeys:"strict",catchall:mn.create(),typeName:L.ZodObject,...pL(r)}),ms.lazycreate=(t,r)=>new ms({shape:t,unknownKeys:"strip",catchall:mn.create(),typeName:L.ZodObject,...pL(r)});class ml extends pZ{_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 pO(t.ctx.common.issues));return pE(r,{code:pT.invalid_union,unionErrors:i}),pq});{let t,n=[];for(let a of i){let i={...r,common:{...r.common,issues:[]},parent:null},o=a._parseSync({data:r.data,path:r.path,parent:i});if("valid"===o.status)return o;"dirty"!==o.status||t||(t={result:o,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 a=n.map(t=>new pO(t));return pE(r,{code:pT.invalid_union,unionErrors:a}),pq}}get options(){return this._def.options}}ml.create=(t,r)=>new ml({options:t,typeName:L.ZodUnion,...pL(r)});let mc=t=>{if(t instanceof my)return mc(t.schema);if(t instanceof mR)return mc(t.innerType());if(t instanceof mv)return[t.value];if(t instanceof mb)return t.options;if(t instanceof mS)return z.objectValues(t.enum);else if(t instanceof m$)return mc(t._def.innerType);else if(t instanceof me)return[void 0];else if(t instanceof mt)return[null];else if(t instanceof mk)return[void 0,...mc(t.unwrap())];else if(t instanceof mx)return[null,...mc(t.unwrap())];else if(t instanceof mP)return mc(t.unwrap());else if(t instanceof mE)return mc(t.unwrap());else if(t instanceof mT)return mc(t._def.innerType);else return[]};class mu extends pZ{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==px.object)return pE(r,{code:pT.invalid_type,expected:px.object,received:r.parsedType}),pq;let i=this.discriminator,n=r.data[i],a=this.optionsMap.get(n);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(pE(r,{code:pT.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),pq)}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=mc(i.shape[t]);if(!r.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of r){if(n.has(a))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);n.set(a,i)}}return new mu({typeName:L.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...pL(i)})}}class md extends pZ{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=(t,n)=>{if("aborted"===t.status||"aborted"===n.status)return pq;let a=function t(r,i){let n=p$(r),a=p$(i);if(r===i)return{valid:!0,data:r};if(n===px.object&&a===px.object){let n=z.objectKeys(i),a=z.objectKeys(r).filter(t=>-1!==n.indexOf(t)),o={...r,...i};for(let n of(Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__,a)){if("__proto__"===n)continue;let a=t(r[n],i[n]);if(!a.valid)return{valid:!1};o[n]=a.data}return{valid:!0,data:o}}if(n===px.array&&a===px.array){if(r.length!==i.length)return{valid:!1};let n=[];for(let a=0;a<r.length;a++){let o=t(r[a],i[a]);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}if(n===px.date&&a===px.date&&+r==+i)return{valid:!0,data:r};return{valid:!1}}(t.value,n.value);return a.valid?(("dirty"===t.status||"dirty"===n.status)&&r.dirty(),{status:r.value,value:a.data}):(pE(i,{code:pT.invalid_intersection_types}),pq)};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}))}}md.create=(t,r,i)=>new md({left:t,right:r,typeName:L.ZodIntersection,...pL(i)});class mp extends pZ{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==px.array)return pE(i,{code:pT.invalid_type,expected:px.array,received:i.parsedType}),pq;if(i.data.length<this._def.items.length)return pE(i,{code:pT.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),pq;!this._def.rest&&i.data.length>this._def.items.length&&(pE(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 pN(i,t,i.path,r)):null}).filter(t=>!!t);return i.common.async?Promise.all(n).then(t=>pI.mergeArray(r,t)):pI.mergeArray(r,n)}get items(){return this._def.items}rest(t){return new mp({...this._def,rest:t})}}mp.create=(t,r)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new mp({items:t,typeName:L.ZodTuple,rest:null,...pL(r)})};class mm extends pZ{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!==px.object)return pE(i,{code:pT.invalid_type,expected:px.object,received:i.parsedType}),pq;let n=[],a=this._def.keyType,o=this._def.valueType;for(let t in i.data)n.push({key:a._parse(new pN(i,t,i.path,t)),value:o._parse(new pN(i,i.data[t],i.path,t)),alwaysSet:t in i.data});return i.common.async?pI.mergeObjectAsync(r,n):pI.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,i){return new mm(r instanceof pZ?{keyType:t,valueType:r,typeName:L.ZodRecord,...pL(i)}:{keyType:p4.create(),valueType:t,typeName:L.ZodRecord,...pL(r)})}}class mh extends pZ{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!==px.map)return pE(i,{code:pT.invalid_type,expected:px.map,received:i.parsedType}),pq;let n=this._def.keyType,a=this._def.valueType,o=[...i.data.entries()].map(([t,r],o)=>({key:n._parse(new pN(i,t,i.path,[o,"key"])),value:a._parse(new pN(i,r,i.path,[o,"value"]))}));if(i.common.async){let t=new Map;return Promise.resolve().then(async()=>{for(let i of o){let n=await i.key,a=await i.value;if("aborted"===n.status||"aborted"===a.status)return pq;("dirty"===n.status||"dirty"===a.status)&&r.dirty(),t.set(n.value,a.value)}return{status:r.value,value:t}})}{let t=new Map;for(let i of o){let n=i.key,a=i.value;if("aborted"===n.status||"aborted"===a.status)return pq;("dirty"===n.status||"dirty"===a.status)&&r.dirty(),t.set(n.value,a.value)}return{status:r.value,value:t}}}}mh.create=(t,r,i)=>new mh({valueType:r,keyType:t,typeName:L.ZodMap,...pL(i)});class mf extends pZ{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==px.set)return pE(i,{code:pT.invalid_type,expected:px.set,received:i.parsedType}),pq;let n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(pE(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&&(pE(i,{code:pT.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let a=this._def.valueType;function o(t){let i=new Set;for(let n of t){if("aborted"===n.status)return pq;"dirty"===n.status&&r.dirty(),i.add(n.value)}return{status:r.value,value:i}}let s=[...i.data.values()].map((t,r)=>a._parse(new pN(i,t,i.path,r)));return i.common.async?Promise.all(s).then(t=>o(t)):o(s)}min(t,r){return new mf({...this._def,minSize:{value:t,message:M.toString(r)}})}max(t,r){return new mf({...this._def,maxSize:{value:t,message:M.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}mf.create=(t,r)=>new mf({valueType:t,minSize:null,maxSize:null,typeName:L.ZodSet,...pL(r)});class mg extends pZ{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==px.function)return pE(r,{code:pT.invalid_type,expected:px.function,received:r.parsedType}),pq;function i(t,i){return pC({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pP,pP].filter(t=>!!t),issueData:{code:pT.invalid_arguments,argumentsError:i}})}function n(t,i){return pC({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pP,pP].filter(t=>!!t),issueData:{code:pT.invalid_return_type,returnTypeError:i}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof mw){let t=this;return pA(async function(...r){let s=new pO([]),l=await t._def.args.parseAsync(r,a).catch(t=>{throw s.addIssue(i(r,t)),s}),c=await Reflect.apply(o,this,l);return await t._def.returns._def.type.parseAsync(c,a).catch(t=>{throw s.addIssue(n(c,t)),s})})}{let t=this;return pA(function(...r){let s=t._def.args.safeParse(r,a);if(!s.success)throw new pO([i(r,s.error)]);let l=Reflect.apply(o,this,s.data),c=t._def.returns.safeParse(l,a);if(!c.success)throw new pO([n(l,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new mg({...this._def,args:mp.create(t).rest(mi.create())})}returns(t){return new mg({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new mg({args:t||mp.create([]).rest(mi.create()),returns:r||mi.create(),typeName:L.ZodFunction,...pL(i)})}}class my extends pZ{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})}}my.create=(t,r)=>new my({getter:t,typeName:L.ZodLazy,...pL(r)});class mv extends pZ{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return pE(r,{received:r.data,code:pT.invalid_literal,expected:this._def.value}),pq}return{status:"valid",value:t.data}}get value(){return this._def.value}}function m_(t,r){return new mb({values:t,typeName:L.ZodEnum,...pL(r)})}mv.create=(t,r)=>new mv({value:t,typeName:L.ZodLiteral,...pL(r)});class mb extends pZ{_parse(t){if("string"!=typeof t.data){let r=this._getOrReturnCtx(t),i=this._def.values;return pE(r,{expected:z.joinValues(i),received:r.parsedType,code:pT.invalid_type}),pq}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 pE(r,{received:r.data,code:pT.invalid_enum_value,options:i}),pq}return pA(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 mb.create(t,{...this._def,...r})}exclude(t,r=this._def){return mb.create(this.options.filter(r=>!t.includes(r)),{...this._def,...r})}}mb.create=m_;class mS extends pZ{_parse(t){let r=z.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==px.string&&i.parsedType!==px.number){let t=z.objectValues(r);return pE(i,{expected:z.joinValues(t),received:i.parsedType,code:pT.invalid_type}),pq}if(this._cache||(this._cache=new Set(z.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let t=z.objectValues(r);return pE(i,{received:i.data,code:pT.invalid_enum_value,options:t}),pq}return pA(t.data)}get enum(){return this._def.values}}mS.create=(t,r)=>new mS({values:t,typeName:L.ZodNativeEnum,...pL(r)});class mw extends pZ{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==px.promise&&!1===r.common.async?(pE(r,{code:pT.invalid_type,expected:px.promise,received:r.parsedType}),pq):pA((r.parsedType===px.promise?r.data:Promise.resolve(r.data)).then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}}mw.create=(t,r)=>new mw({type:t,typeName:L.ZodPromise,...pL(r)});class mR extends pZ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=this._def.effect||null,a={addIssue:t=>{pE(i,t),t.fatal?r.abort():r.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===n.type){let t=n.transform(i.data,a);if(i.common.async)return Promise.resolve(t).then(async t=>{if("aborted"===r.value)return pq;let n=await this._def.schema._parseAsync({data:t,path:i.path,parent:i});return"aborted"===n.status?pq:"dirty"===n.status||"dirty"===r.value?pj(n.value):n});{if("aborted"===r.value)return pq;let n=this._def.schema._parseSync({data:t,path:i.path,parent:i});return"aborted"===n.status?pq:"dirty"===n.status||"dirty"===r.value?pj(n.value):n}}if("refinement"===n.type){let t=t=>{let r=n.refinement(t,a);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?pq:("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?pq:("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?pq:Promise.resolve(n.transform(t.value,a)).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 pq;let o=n.transform(t.value,a);if(o instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}z.assertNever(n)}}mR.create=(t,r,i)=>new mR({schema:t,typeName:L.ZodEffects,effect:r,...pL(i)}),mR.createWithPreprocess=(t,r,i)=>new mR({schema:r,effect:{type:"preprocess",transform:t},typeName:L.ZodEffects,...pL(i)});class mk extends pZ{_parse(t){return this._getType(t)===px.undefined?pA(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mk.create=(t,r)=>new mk({innerType:t,typeName:L.ZodOptional,...pL(r)});class mx extends pZ{_parse(t){return this._getType(t)===px.null?pA(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mx.create=(t,r)=>new mx({innerType:t,typeName:L.ZodNullable,...pL(r)});class m$ extends pZ{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===px.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:L.ZodDefault,defaultValue:"function"==typeof r.default?r.default:()=>r.default,...pL(r)});class mT extends pZ{_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 pz(n)?n.then(t=>({status:"valid",value:"valid"===t.status?t.value:this._def.catchValue({get error(){return new pO(i.common.issues)},input:i.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new pO(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}mT.create=(t,r)=>new mT({innerType:t,typeName:L.ZodCatch,catchValue:"function"==typeof r.catch?r.catch:()=>r.catch,...pL(r)});class mO extends pZ{_parse(t){if(this._getType(t)!==px.nan){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.nan,received:r.parsedType}),pq}return{status:"valid",value:t.data}}}mO.create=t=>new mO({typeName:L.ZodNaN,...pL(t)}),Symbol("zod_brand");class mP extends pZ{_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 mC extends pZ{_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?pq:"dirty"===t.status?(r.dirty(),pj(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?pq:"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 mC({in:t,out:r,typeName:L.ZodPipeline})}}class mE extends pZ{_parse(t){let r=this._def.innerType._parse(t),i=t=>("valid"===t.status&&(t.value=Object.freeze(t.value)),t);return pz(r)?r.then(t=>i(t)):i(r)}unwrap(){return this._def.innerType}}mE.create=(t,r)=>new mE({innerType:t,typeName:L.ZodReadonly,...pL(r)}),ms.lazycreate,(I=L||(L={})).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",p4.create,p3.create,mO.create,p6.create,p5.create,p7.create,p8.create,me.create,mt.create,mr.create,mi.create,mn.create,ma.create,mo.create,ms.create,ms.strictCreate,ml.create,mu.create,md.create,mp.create,mm.create,mh.create,mf.create,mg.create,my.create,mv.create,mb.create,mS.create,mw.create,mR.create,mk.create,mx.create,mR.createWithPreprocess,mC.create;let mI=(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 mq(t){if("openAi"!==t.target)return{};let r=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===t.$refStrategy?mI(r,t.currentPath):r.join("/")}}function mj(t,r,i,n){n?.errorMessages&&i&&(t.errorMessage={...t.errorMessage,[r]:i})}function mA(t,r,i,n,a){t[r]=i,mj(t,r,n,a)}function mz(t,r){return m9(t.type._def,r)}let mN=/^[cC][^\s-]{8,}$/,mM=/^[0-9a-z]+$/,mL=/^[0-9A-HJKMNP-TV-Z]{26}$/,mZ=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,mU=()=>(void 0===k&&(k=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),k),mF=/^(?:(?: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])$/,mH=/^([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}(=)?))?$/,mV=/^[a-zA-Z0-9_-]{21}$/,mB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function mW(t,r){let i={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":mA(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r);break;case"max":mA(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":mY(i,"email",n.message,r);break;case"format:idn-email":mY(i,"idn-email",n.message,r);break;case"pattern:zod":mX(i,mZ,n.message,r)}break;case"url":mY(i,"uri",n.message,r);break;case"uuid":mY(i,"uuid",n.message,r);break;case"regex":mX(i,n.regex,n.message,r);break;case"cuid":mX(i,mN,n.message,r);break;case"cuid2":mX(i,mM,n.message,r);break;case"startsWith":mX(i,RegExp(`^${mG(n.value,r)}`),n.message,r);break;case"endsWith":mX(i,RegExp(`${mG(n.value,r)}$`),n.message,r);break;case"datetime":mY(i,"date-time",n.message,r);break;case"date":mY(i,"date",n.message,r);break;case"time":mY(i,"time",n.message,r);break;case"duration":mY(i,"duration",n.message,r);break;case"length":mA(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r),mA(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"includes":mX(i,RegExp(mG(n.value,r)),n.message,r);break;case"ip":"v6"!==n.version&&mY(i,"ipv4",n.message,r),"v4"!==n.version&&mY(i,"ipv6",n.message,r);break;case"base64url":mX(i,mJ,n.message,r);break;case"jwt":mX(i,mB,n.message,r);break;case"cidr":"v6"!==n.version&&mX(i,mF,n.message,r),"v4"!==n.version&&mX(i,mD,n.message,r);break;case"emoji":mX(i,mU(),n.message,r);break;case"ulid":mX(i,mL,n.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":mY(i,"binary",n.message,r);break;case"contentEncoding:base64":mA(i,"contentEncoding","base64",n.message,r);break;case"pattern:zod":mX(i,mH,n.message,r)}break;case"nanoid":mX(i,mV,n.message,r)}return i}function mG(t,r){return"escape"===r.patternStrategy?function(t){let r="";for(let i=0;i<t.length;i++)mK.has(t[i])||(r+="\\"),r+=t[i];return r}(t):t}let mK=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mY(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}}})):mA(t,"format",r,i,n)}function mX(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:mQ(r,n),...i&&n.errorMessages&&{errorMessage:{pattern:i}}})):mA(t,"pattern",mQ(r,n),i,n)}function mQ(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,a="",o=!1,s=!1,l=!1;for(let t=0;t<n.length;t++){if(o){a+=n[t],o=!1;continue}if(i.i){if(s){if(n[t].match(/[a-z]/)){l?(a+=n[t],a+=`${n[t-2]}-${n[t]}`.toUpperCase(),l=!1):"-"===n[t+1]&&n[t+2]?.match(/[a-z]/)?(a+=n[t],l=!0):a+=`${n[t]}${n[t].toUpperCase()}`;continue}}else if(n[t].match(/[a-z]/)){a+=`[${n[t]}${n[t].toUpperCase()}]`;continue}}if(i.m){if("^"===n[t]){a+=`(^|(?<=[\r
|
|
73
|
+
`,t.enqueue(r.encode(a)),!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,a,o,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 dq(t,this._maxRequestBodySize);if(r.tooLarge){let t=dE(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=>od.parse(t)):[od.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=>o$.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{a=await this._checkScopeChallenge(n,r?.authInfo)}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(500,-32603,"Internal server error")}if(a)return a;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=>o$.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=>{o=t},cancel:()=>{void 0!==s&&clearInterval(s),this._streamMapping.get(u)?.controller===o&&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:o,encoder:m,cleanup:()=>{void 0!==s&&clearInterval(s),this._streamMapping.delete(u);try{o.close()}catch{}}}),this._requestToStreamMapping.set(t.id,u));for(let i of(await this.writePrimingEvent(o,m,u,p),n)){let n,a;cX(i)&&this._eventStore&&this.supportsEmptySSEData(p)&&(n=()=>{this.closeSSEStream(i.id)},a=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(i,{authInfo:r?.authInfo,request:t,closeSSEStream:n,closeStandaloneSSEStream:a})}return this._streamMapping.get(u)?.controller===o&&(s=this.startKeepAlive(o,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 a=this._streamMapping.get(n);if(!this._enableJsonResponse){let r;this._eventStore&&(r=await this._eventStore.storeEvent(n,t),a=this._streamMapping.get(n)),a?.controller&&a?.encoder&&(void 0===r||!a.replayedEventIds?.has(r))&&this.writeSSEEvent(a.controller,a.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(!a){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&&a.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?a.resolveJson(Response.json(i[0],{status:200,headers:t})):a.resolveJson(Response.json(i,{status:200,headers:t})),a.cleanup()}else a.cleanup();for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t)}}}};function dA(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 dz(t,r,i,n,a=null){return Response.json({jsonrpc:"2.0",error:{code:r,message:i,...void 0!==n&&{data:n}},id:a},{status:t})}function dN(t,r=null){return dz(t.httpStatus,t.code,t.message,t.data,r)}function dM(t){return t instanceof Error?t:Error(String(t))}function dL(t=null){return dz(500,-32603,"Internal server error",void 0,t)}function dZ(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 dU(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 dF(t,r,i=!0,n=4194304){let a,o=t.method.toUpperCase(),s=r,l=t,c=!1;if("POST"===o){if(void 0===s){let r;i&&(l=t.clone());try{let i=await dq(t,n);if(i.tooLarge)return{step:"body-too-large"};r=i.text}catch{return{step:"unreadable-body"}}try{a=0===r.length?void 0:JSON.parse(r)}catch{c=!0}c||void 0===a||(s=a)}else a=s;if(c||void 0===a)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 uo("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 uo("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 uo("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,a=t.protocolVersionHeader,o=void 0!==a&&a>=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(o)return us("initialize-with-modern-header",a,"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 o=cB(i),s=(void 0===o?[]:cK(o))[0];if(void 0!==s)return uo("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!==a&&void 0!==l&&a!==l?us("header-body-version-mismatch",a,`the body envelope names protocol version ${l} but the MCP-Protocol-Version header names ${a}`):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(o){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:[aG];return uo("envelope","modern-header-without-claim",400,new c_(cv.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${a}, 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!==a&&{requestedVersion:a}}}(t,r):uu(r)&&cQ(r)?function(t,r){let i=r.params,n=r.method,a=t.protocolVersionHeader,o=void 0!==a&&a>=lQ;if(cW(i)){let o=cG(i);if(void 0===o){let t=cB(i),r=(void 0===t?[]:cK(t)).find(t=>t.key===aG)??{key:aG,problem:"expected a protocol version string"};return uo("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!==a&&a!==o)return us("notification-header-body-version-mismatch",a,`the notification envelope names protocol version ${o} but the MCP-Protocol-Version header names ${a}`);let s=ud(o);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 o?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:a}}:{kind:"legacy",reason:"notification",...void 0!==a&&{requestedVersion:a}}}(t,r):uo("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:o,...dU(t),...void 0!==a&&{body:a}}),body:a,parsedBody:s,forwardRequest:l}}let dD=(t,r)=>{globalThis[t]=r},dH=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(dH(i))return dH(i);let a=new x,o=globalThis[n]??{current:null};dD(n,o);let s={provider:(t,i)=>(r&&(o.current=t),a.run(t,i)),getContext:()=>{let i=a.getStore();if(i)return i;if(r&&o.current)return o.current;throw Error(`getContext() can only be used within the ${t} context.`)},setContext:i=>{let n=a.getStore()??(r?o.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 dV=dJ({name:"http-request-context"});dV.setContext;let dB=dV.getContext,dW=dV.provider,dG=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),dK=t=>{if(!dG(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},dY=t=>{if(t&&"initialize"===t.method&&dG(t.params))return dK(t.params.clientInfo)},dX=(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 a=t.trim();return a.length>0?a:void 0}};function dQ(t){let{tags:r,enabled:i,...n}=t;return{...n,_meta:void 0===r?n._meta:{...n._meta,"xmcp/tags":r}}}let d0=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}},d1=dJ({name:"request-context",fallback:!1}),d2=dJ({name:"client-info-context"});d2.setContext;let d9=d2.getContext;d2.provider;let d4=new Set(["message","mode","requestedSchema"]),d3=new Set(["elicitationId","message","mode","url"]),d6=new Set(["properties","required","type"]),d5=new Set(["default","description","format","maxLength","minLength","title","type"]),d7=new Set(["default","description","enum","enumNames","title","type"]),d8=new Set(["default","description","title","type"]),pe=new Set(["default","description","maximum","minimum","title","type"]),pt=new Set(["date","date-time","email","uri"]);async function pr(t,r,i){let n=function(t){let r=t.mode??"form";if("url"===r)return function(t){let r;pn(t,"Elicitation request must be a plain object."),pi(t,d3,"URL elicitation"),pa(t.message,"URL elicitation requires a string message."),po(t.elicitationId,"URL elicitation requires a non-empty elicitationId."),po(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){pn(t,"Elicitation request must be a plain object."),pi(t,d4,"Form elicitation"),pa(t.message,"Form elicitation requires a string message.");let r=t.requestedSchema;if(pn(r,"Form elicitation requires a flat object schema."),pi(r,d6,"Form elicitation schema"),"object"!==r.type)throw Error('Form elicitation schema must use type "object".');for(let[t,i]of(pn(r.properties,"Form elicitation schema requires a properties object."),Object.entries(r.properties)))!function(t,r){if(pn(r,`Form elicitation field "${t}" must be a plain object.`),ps(r.title,`Form elicitation field "${t}" title must be a string.`),ps(r.description,`Form elicitation field "${t}" description must be a string.`),"string"===r.type&&"enum"in r){var i,n;if(pi(r,d7,`Form elicitation field "${t}"`),pc(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&&pc(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(ps(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)){pi(r,d5,`Form elicitation field "${t}"`),pl(r.minLength,`Form elicitation field "${t}" minLength must be a number.`),pl(r.maxLength,`Form elicitation field "${t}" maxLength must be a number.`),ps(r.default,`Form elicitation field "${t}" default must be a string.`);let i=r.format;if(ps(i,`Form elicitation field "${t}" format must be a string.`),void 0!==i&&!pt.has(i))throw Error(`Form elicitation field "${t}" format must be one of: ${Array.from(pt).join(", ")}.`);return}if("boolean"===r.type){if(pi(r,d8,`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){pi(r,pe,`Form elicitation field "${t}"`),pl(r.minimum,`Form elicitation field "${t}" minimum must be a number.`),pl(r.maximum,`Form elicitation field "${t}" maximum must be a number.`),pl(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 pi(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 pn(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 po(t,r){if("string"!=typeof t||0===t.trim().length)throw Error(r)}function ps(t,r){if(void 0!==t&&"string"!=typeof t)throw Error(r)}function pl(t,r){if(void 0!==t&&"number"!=typeof t)throw Error(r)}function pc(t,r){if(!Array.isArray(t)||t.some(t=>"string"!=typeof t))throw Error(r)}let pu=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),pd=new Set(["task","toolChoice","tools"]),pp=new Set(["text","image","audio"]);async function pm(t,r,i){let n=function(t){ph(t,"Sampling request must be a plain object.");let r=Object.keys(t),i=r.filter(t=>pd.has(t));if(i.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${i.join(", ")}.`);let n=r.filter(t=>!pu.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(ph(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;ph(i,`Sampling message at index ${t} requires a content object.`);let n=i.type;if("string"!=typeof n||!pp.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 ph(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}let pf={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 pg(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=pf[t.type];return r?r(t):{valid:!0}}function py(t,r,i,n){if(null===t||"object"!=typeof t||Array.isArray(t))throw Error(`Tool "${i}" ${n}: expected a plain object.`);let a=new Set(Object.keys(r)),o=Object.keys(t).filter(t=>!a.has(t));if(o.length>0)throw Error(`Tool "${i}" ${n}: unrecognized key(s): ${o.join(", ")}`);for(let[a,o]of Object.entries(r))try{o.parse(t[a])}catch(t){throw Error(`Tool "${i}" ${n}: ${t?.message??`invalid field "${a}"`}`)}}function pv(t){return!!(t&&"object"==typeof t&&Object.keys(t).some(t=>t.startsWith("ui/")))}function p_(t){let r=t.mcpReq.envelope,i=dK(r?.[aK]);if(!i)try{let t,r=dB();i=r.clientInfo??(t=r.headers,dK({name:dX(t,"x-mcp-client-name"),version:dX(t,"x-mcp-client-version"),title:dX(t,"x-mcp-client-title"),websiteUrl:dX(t,"x-mcp-client-website-url"),description:dX(t,"x-mcp-client-description")}))}catch{}if(!i)try{i=d9().clientInfo}catch{}return i}function pb(t){let r=[...t];return(t,i,n)=>(function(t,r,i){let n,a=new Map;if(t.http){let t=dB(),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 d1.provider(Object.freeze({clientInfo:r?Object.freeze({...r}):void 0,http:n,authInfo:t.http?.authInfo,signal:t.mcpReq.signal,set(t,r){a.set(t,r)},get:t=>a.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,p_(i),async()=>{if(0===r.length)return n();let i=Object.freeze({...function(){try{return d1.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),...t,params:Object.freeze({...t.params})}),a=-1,o=async t=>{if(t<=a)throw Error("MCP middleware next() can only be called once");a=t;let s=r[t];return s?s(i,()=>o(t+1)):n()};return o(0)})}let pS=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function pw(t){return t.endsWith(".tsx")}let pR=Symbol("Let zodToJsonSchema decide on which parser to use"),pk={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"};(C=z||(z={})).assertEqual=t=>{},C.assertIs=function(t){},C.assertNever=function(t){throw Error()},C.arrayToEnum=t=>{let r={};for(let i of t)r[i]=i;return r},C.getValidEnumValues=t=>{let r=C.objectKeys(t).filter(r=>"number"!=typeof t[t[r]]),i={};for(let n of r)i[n]=t[n];return C.objectValues(i)},C.objectValues=t=>C.objectKeys(t).map(function(r){return t[r]}),C.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},C.find=(t,r)=>{for(let i of t)if(r(i))return i},C.isInteger="function"==typeof Number.isInteger?t=>Number.isInteger(t):t=>"number"==typeof t&&Number.isFinite(t)&&Math.floor(t)===t,C.joinValues=function(t,r=" | "){return t.map(t=>"string"==typeof t?`'${t}'`:t).join(r)},C.jsonStringifyReplacer=(t,r)=>"bigint"==typeof r?r.toString():r,(N||(N={})).mergeShapes=(t,r)=>({...t,...r});let px=z.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 px.undefined;case"string":return px.string;case"number":return Number.isNaN(t)?px.nan:px.number;case"boolean":return px.boolean;case"function":return px.function;case"bigint":return px.bigint;case"symbol":return px.symbol;case"object":if(Array.isArray(t))return px.array;if(null===t)return px.null;if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return px.promise;if("undefined"!=typeof Map&&t instanceof Map)return px.map;if("undefined"!=typeof Set&&t instanceof Set)return px.set;if("undefined"!=typeof Date&&t instanceof Date)return px.date;return px.object;default:return px.unknown}},pT=z.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 pO 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 a of t.issues)if("invalid_union"===a.code)a.unionErrors.map(n);else if("invalid_return_type"===a.code)n(a.returnTypeError);else if("invalid_arguments"===a.code)n(a.argumentsError);else if(0===a.path.length)i._errors.push(r(a));else{let t=i,n=0;for(;n<a.path.length;){let i=a.path[n],o=n===a.path.length-1;if("_errors"===i){o&&t._errors.push(r(a)),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],o&&t._errors.push(r(a)),n++}}};return n(this),i}static assert(t){if(!(t instanceof pO))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,z.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()}}pO.create=t=>new pO(t);let pP=(t,r)=>{let i;switch(t.code){case pT.invalid_type:i=t.received===px.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case pT.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,z.jsonStringifyReplacer)}`;break;case pT.unrecognized_keys:i=`Unrecognized key(s) in object: ${z.joinValues(t.keys,", ")}`;break;case pT.invalid_union:i="Invalid input";break;case pT.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${z.joinValues(t.options)}`;break;case pT.invalid_enum_value:i=`Invalid enum value. Expected ${z.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}"`:z.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,z.assertNever(t)}return{message:i}};(E=M||(M={})).errToObj=t=>"string"==typeof t?{message:t}:t||{},E.toString=t=>"string"==typeof t?t:t?.message;let pC=t=>{let{data:r,path:i,errorMaps:n,issueData:a}=t,o=[...i,...a.path||[]],s={...a,path:o};if(void 0!==a.message)return{...a,path:o,message:a.message};let l="";for(let t of n.filter(t=>!!t).slice().reverse())l=t(s,{data:r,defaultError:l}).message;return{...a,path:o,message:l}};function pE(t,r){let i=pC({issueData:r,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pP,void 0].filter(t=>!!t)});t.common.issues.push(i)}class pI{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 pq;"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 pI.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let n of r){let{key:r,value:a}=n;if("aborted"===r.status||"aborted"===a.status)return pq;"dirty"===r.status&&t.dirty(),"dirty"===a.status&&t.dirty(),"__proto__"!==r.value&&(void 0!==a.value||n.alwaysSet)&&(i[r.value]=a.value)}return{status:t.value,value:i}}}let pq=Object.freeze({status:"aborted"}),pj=t=>({status:"dirty",value:t}),pA=t=>({status:"valid",value:t}),pz=t=>"undefined"!=typeof Promise&&t instanceof Promise;class pN{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 pO(t.common.issues);return this._error=r,this._error}}};function pL(t){if(!t)return{};let{errorMap:r,invalid_type_error:i,required_error:n,description:a}=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:a}:{errorMap:(r,a)=>{let{message:o}=t;return"invalid_enum_value"===r.code?{message:o??a.defaultError}:void 0===a.data?{message:o??n??a.defaultError}:"invalid_type"!==r.code?{message:a.defaultError}:{message:o??i??a.defaultError}},description:a}}class pZ{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 pI,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(pz(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 (pz(n)?n:Promise.resolve(n)))}refine(t,r){return this._refinement((i,n)=>{let a=t(i),o=()=>n.addIssue({code:pT.custom,..."string"==typeof r||void 0===r?{message:r}:"function"==typeof r?r(i):r});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(t=>!!t||(o(),!1)):!!a||(o(),!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 mR({schema:this,typeName:L.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 mk.create(this,this._def)}nullable(){return mx.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mo.create(this)}promise(){return mw.create(this,this._def)}or(t){return ml.create([this,t],this._def)}and(t){return md.create(this,t,this._def)}transform(t){return new mR({...pL(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:t}})}default(t){return new m$({...pL(this._def),innerType:this,defaultValue:"function"==typeof t?t:()=>t,typeName:L.ZodDefault})}brand(){return new mP({typeName:L.ZodBranded,type:this,...pL(this._def)})}catch(t){return new mT({...pL(this._def),innerType:this,catchValue:"function"==typeof t?t:()=>t,typeName:L.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return mC.create(this,t)}readonly(){return mE.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let pU=/^c[^\s-]{8,}$/i,pF=/^[0-9a-z]+$/,pD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pH=/^[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,pV=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pB=/^[-+]?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)?)??$/,pW=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,pG=/^(?:(?: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])$/,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])\/(3[0-2]|[12]?[0-9])$/,pY=/^(([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]))$/,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]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,p0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,p1="((\\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])))",p2=RegExp(`^${p1}$`);function p9(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 p4 extends pZ{_parse(t){var r,i,n,a;let o;if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==px.string){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.string,received:r.parsedType}),pq}let s=new pI;for(let l of this._def.checks)if("min"===l.kind)t.data.length<l.value&&(pE(o=this._getOrReturnCtx(t,o),{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&&(pE(o=this._getOrReturnCtx(t,o),{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)&&(o=this._getOrReturnCtx(t,o),r?pE(o,{code:pT.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):i&&pE(o,{code:pT.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),s.dirty())}else if("email"===l.kind)pW.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{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)||(pE(o=this._getOrReturnCtx(t,o),{validation:"emoji",code:pT.invalid_string,message:l.message}),s.dirty());else if("uuid"===l.kind)pH.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"uuid",code:pT.invalid_string,message:l.message}),s.dirty());else if("nanoid"===l.kind)pJ.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"nanoid",code:pT.invalid_string,message:l.message}),s.dirty());else if("cuid"===l.kind)pU.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"cuid",code:pT.invalid_string,message:l.message}),s.dirty());else if("cuid2"===l.kind)pF.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"cuid2",code:pT.invalid_string,message:l.message}),s.dirty());else if("ulid"===l.kind)pD.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"ulid",code:pT.invalid_string,message:l.message}),s.dirty());else if("url"===l.kind)try{new URL(t.data)}catch{pE(o=this._getOrReturnCtx(t,o),{validation:"url",code:pT.invalid_string,message:l.message}),s.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{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)||(pE(o=this._getOrReturnCtx(t,o),{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)||(pE(o=this._getOrReturnCtx(t,o),{code:pT.invalid_string,validation:{startsWith:l.value},message:l.message}),s.dirty()):"endsWith"===l.kind?t.data.endsWith(l.value)||(pE(o=this._getOrReturnCtx(t,o),{code:pT.invalid_string,validation:{endsWith:l.value},message:l.message}),s.dirty()):"datetime"===l.kind?(function(t){let r=`${p1}T${p9(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)||(pE(o=this._getOrReturnCtx(t,o),{code:pT.invalid_string,validation:"datetime",message:l.message}),s.dirty()):"date"===l.kind?p2.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{code:pT.invalid_string,validation:"date",message:l.message}),s.dirty()):"time"===l.kind?RegExp(`^${p9(l)}$`).test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{code:pT.invalid_string,validation:"time",message:l.message}),s.dirty()):"duration"===l.kind?pB.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"duration",code:pT.invalid_string,message:l.message}),s.dirty()):"ip"===l.kind?(r=t.data,!(("v4"===(i=l.version)||!i)&&pG.test(r)||("v6"===i||!i)&&pY.test(r))&&1&&(pE(o=this._getOrReturnCtx(t,o),{validation:"ip",code:pT.invalid_string,message:l.message}),s.dirty())):"jwt"===l.kind?!function(t,r){if(!pV.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,"="),a=JSON.parse(atob(n));if("object"!=typeof a||null===a||"typ"in a&&a?.typ!=="JWT"||!a.alg||r&&a.alg!==r)return!1;return!0}catch{return!1}}(t.data,l.alg)&&(pE(o=this._getOrReturnCtx(t,o),{validation:"jwt",code:pT.invalid_string,message:l.message}),s.dirty()):"cidr"===l.kind?(n=t.data,!(("v4"===(a=l.version)||!a)&&pK.test(n)||("v6"===a||!a)&&pX.test(n))&&1&&(pE(o=this._getOrReturnCtx(t,o),{validation:"cidr",code:pT.invalid_string,message:l.message}),s.dirty())):"base64"===l.kind?pQ.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"base64",code:pT.invalid_string,message:l.message}),s.dirty()):"base64url"===l.kind?p0.test(t.data)||(pE(o=this._getOrReturnCtx(t,o),{validation:"base64url",code:pT.invalid_string,message:l.message}),s.dirty()):z.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,...M.errToObj(i)})}_addCheck(t){return new p4({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...M.errToObj(t)})}url(t){return this._addCheck({kind:"url",...M.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...M.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...M.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...M.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...M.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...M.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...M.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...M.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...M.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...M.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...M.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...M.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,...M.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,...M.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...M.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...M.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...M.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...M.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...M.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...M.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...M.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...M.errToObj(r)})}nonempty(t){return this.min(1,M.errToObj(t))}trim(){return new p4({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new p4({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new p4({...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}}p4.create=t=>new p4({checks:[],typeName:L.ZodString,coerce:t?.coerce??!1,...pL(t)});class p3 extends pZ{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)!==px.number){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.number,received:r.parsedType}),pq}let i=new pI;for(let n of this._def.checks)"int"===n.kind?z.isInteger(t.data)||(pE(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)&&(pE(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)&&(pE(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,a=i>n?i:n;return Number.parseInt(t.toFixed(a).replace(".",""))%Number.parseInt(r.toFixed(a).replace(".",""))/10**a}(t.data,n.value)&&(pE(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)||(pE(r=this._getOrReturnCtx(t,r),{code:pT.not_finite,message:n.message}),i.dirty()):z.assertNever(n);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,M.toString(r))}gt(t,r){return this.setLimit("min",t,!1,M.toString(r))}lte(t,r){return this.setLimit("max",t,!0,M.toString(r))}lt(t,r){return this.setLimit("max",t,!1,M.toString(r))}setLimit(t,r,i,n){return new p3({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:M.toString(n)}]})}_addCheck(t){return new p3({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:M.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:M.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:M.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.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&&z.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:L.ZodNumber,coerce:t?.coerce||!1,...pL(t)});class p6 extends pZ{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)!==px.bigint)return this._getInvalidInput(t);let i=new pI;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(pE(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)&&(pE(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)&&(pE(r=this._getOrReturnCtx(t,r),{code:pT.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):z.assertNever(n);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.bigint,received:r.parsedType}),pq}gte(t,r){return this.setLimit("min",t,!0,M.toString(r))}gt(t,r){return this.setLimit("min",t,!1,M.toString(r))}lte(t,r){return this.setLimit("max",t,!0,M.toString(r))}lt(t,r){return this.setLimit("max",t,!1,M.toString(r))}setLimit(t,r,i,n){return new p6({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:M.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:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:M.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:L.ZodBigInt,coerce:t?.coerce??!1,...pL(t)});class p5 extends pZ{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==px.boolean){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.boolean,received:r.parsedType}),pq}return pA(t.data)}}p5.create=t=>new p5({typeName:L.ZodBoolean,coerce:t?.coerce||!1,...pL(t)});class p7 extends pZ{_parse(t){let r;if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==px.date){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.date,received:r.parsedType}),pq}if(Number.isNaN(t.data.getTime()))return pE(this._getOrReturnCtx(t),{code:pT.invalid_date}),pq;let i=new pI;for(let n of this._def.checks)"min"===n.kind?t.data.getTime()<n.value&&(pE(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&&(pE(r=this._getOrReturnCtx(t,r),{code:pT.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):z.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new p7({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:M.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:M.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}}p7.create=t=>new p7({checks:[],coerce:t?.coerce||!1,typeName:L.ZodDate,...pL(t)});class p8 extends pZ{_parse(t){if(this._getType(t)!==px.symbol){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.symbol,received:r.parsedType}),pq}return pA(t.data)}}p8.create=t=>new p8({typeName:L.ZodSymbol,...pL(t)});class me extends pZ{_parse(t){if(this._getType(t)!==px.undefined){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.undefined,received:r.parsedType}),pq}return pA(t.data)}}me.create=t=>new me({typeName:L.ZodUndefined,...pL(t)});class mt extends pZ{_parse(t){if(this._getType(t)!==px.null){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.null,received:r.parsedType}),pq}return pA(t.data)}}mt.create=t=>new mt({typeName:L.ZodNull,...pL(t)});class mr extends pZ{constructor(){super(...arguments),this._any=!0}_parse(t){return pA(t.data)}}mr.create=t=>new mr({typeName:L.ZodAny,...pL(t)});class mi extends pZ{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pA(t.data)}}mi.create=t=>new mi({typeName:L.ZodUnknown,...pL(t)});class mn extends pZ{_parse(t){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.never,received:r.parsedType}),pq}}mn.create=t=>new mn({typeName:L.ZodNever,...pL(t)});class ma extends pZ{_parse(t){if(this._getType(t)!==px.undefined){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.void,received:r.parsedType}),pq}return pA(t.data)}}ma.create=t=>new ma({typeName:L.ZodVoid,...pL(t)});class mo extends pZ{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),n=this._def;if(r.parsedType!==px.array)return pE(r,{code:pT.invalid_type,expected:px.array,received:r.parsedType}),pq;if(null!==n.exactLength){let t=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(t||a)&&(pE(r,{code:t?pT.too_big:pT.too_small,minimum:a?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&&(pE(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&&(pE(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 pN(r,t,r.path,i)))).then(t=>pI.mergeArray(i,t));let a=[...r.data].map((t,i)=>n.type._parseSync(new pN(r,t,r.path,i)));return pI.mergeArray(i,a)}get element(){return this._def.type}min(t,r){return new mo({...this._def,minLength:{value:t,message:M.toString(r)}})}max(t,r){return new mo({...this._def,maxLength:{value:t,message:M.toString(r)}})}length(t,r){return new mo({...this._def,exactLength:{value:t,message:M.toString(r)}})}nonempty(t){return this.min(1,t)}}mo.create=(t,r)=>new mo({type:t,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...pL(r)});class ms extends pZ{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=z.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==px.object){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.object,received:r.parsedType}),pq}let{status:r,ctx:i}=this._processInputParams(t),{shape:n,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof mn&&"strip"===this._def.unknownKeys))for(let t in i.data)a.includes(t)||o.push(t);let s=[];for(let t of a){let r=n[t],a=i.data[t];s.push({key:{status:"valid",value:t},value:r._parse(new pN(i,a,i.path,t)),alwaysSet:t in i.data})}if(this._def.catchall instanceof mn){let t=this._def.unknownKeys;if("passthrough"===t)for(let t of o)s.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===t)o.length>0&&(pE(i,{code:pT.unrecognized_keys,keys:o}),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 o){let n=i.data[r];s.push({key:{status:"valid",value:r},value:t._parse(new pN(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=>pI.mergeObjectSync(r,t)):pI.mergeObjectSync(r,s)}get shape(){return this._def.shape()}strict(t){return M.errToObj,new ms({...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:M.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new ms({...this._def,unknownKeys:"strip"})}passthrough(){return new ms({...this._def,unknownKeys:"passthrough"})}extend(t){return new ms({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ms({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:L.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new ms({...this._def,catchall:t})}pick(t){let r={};for(let i of z.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new ms({...this._def,shape:()=>r})}omit(t){let r={};for(let i of z.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new ms({...this._def,shape:()=>r})}deepPartial(){return function t(r){if(r instanceof ms){let i={};for(let n in r.shape){let a=r.shape[n];i[n]=mk.create(t(a))}return new ms({...r._def,shape:()=>i})}if(r instanceof mo)return new mo({...r._def,type:t(r.element)});if(r instanceof mk)return mk.create(t(r.unwrap()));if(r instanceof mx)return mx.create(t(r.unwrap()));if(r instanceof mp)return mp.create(r.items.map(r=>t(r)));else return r}(this)}partial(t){let r={};for(let i of z.objectKeys(this.shape)){let n=this.shape[i];t&&!t[i]?r[i]=n:r[i]=n.optional()}return new ms({...this._def,shape:()=>r})}required(t){let r={};for(let i of z.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let t=this.shape[i];for(;t instanceof mk;)t=t._def.innerType;r[i]=t}return new ms({...this._def,shape:()=>r})}keyof(){return m_(z.objectKeys(this.shape))}}ms.create=(t,r)=>new ms({shape:()=>t,unknownKeys:"strip",catchall:mn.create(),typeName:L.ZodObject,...pL(r)}),ms.strictCreate=(t,r)=>new ms({shape:()=>t,unknownKeys:"strict",catchall:mn.create(),typeName:L.ZodObject,...pL(r)}),ms.lazycreate=(t,r)=>new ms({shape:t,unknownKeys:"strip",catchall:mn.create(),typeName:L.ZodObject,...pL(r)});class ml extends pZ{_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 pO(t.ctx.common.issues));return pE(r,{code:pT.invalid_union,unionErrors:i}),pq});{let t,n=[];for(let a of i){let i={...r,common:{...r.common,issues:[]},parent:null},o=a._parseSync({data:r.data,path:r.path,parent:i});if("valid"===o.status)return o;"dirty"!==o.status||t||(t={result:o,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 a=n.map(t=>new pO(t));return pE(r,{code:pT.invalid_union,unionErrors:a}),pq}}get options(){return this._def.options}}ml.create=(t,r)=>new ml({options:t,typeName:L.ZodUnion,...pL(r)});let mc=t=>{if(t instanceof my)return mc(t.schema);if(t instanceof mR)return mc(t.innerType());if(t instanceof mv)return[t.value];if(t instanceof mb)return t.options;if(t instanceof mS)return z.objectValues(t.enum);else if(t instanceof m$)return mc(t._def.innerType);else if(t instanceof me)return[void 0];else if(t instanceof mt)return[null];else if(t instanceof mk)return[void 0,...mc(t.unwrap())];else if(t instanceof mx)return[null,...mc(t.unwrap())];else if(t instanceof mP)return mc(t.unwrap());else if(t instanceof mE)return mc(t.unwrap());else if(t instanceof mT)return mc(t._def.innerType);else return[]};class mu extends pZ{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==px.object)return pE(r,{code:pT.invalid_type,expected:px.object,received:r.parsedType}),pq;let i=this.discriminator,n=r.data[i],a=this.optionsMap.get(n);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(pE(r,{code:pT.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),pq)}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=mc(i.shape[t]);if(!r.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of r){if(n.has(a))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);n.set(a,i)}}return new mu({typeName:L.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...pL(i)})}}class md extends pZ{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=(t,n)=>{if("aborted"===t.status||"aborted"===n.status)return pq;let a=function t(r,i){let n=p$(r),a=p$(i);if(r===i)return{valid:!0,data:r};if(n===px.object&&a===px.object){let n=z.objectKeys(i),a=z.objectKeys(r).filter(t=>-1!==n.indexOf(t)),o={...r,...i};for(let n of(Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__,a)){if("__proto__"===n)continue;let a=t(r[n],i[n]);if(!a.valid)return{valid:!1};o[n]=a.data}return{valid:!0,data:o}}if(n===px.array&&a===px.array){if(r.length!==i.length)return{valid:!1};let n=[];for(let a=0;a<r.length;a++){let o=t(r[a],i[a]);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}if(n===px.date&&a===px.date&&+r==+i)return{valid:!0,data:r};return{valid:!1}}(t.value,n.value);return a.valid?(("dirty"===t.status||"dirty"===n.status)&&r.dirty(),{status:r.value,value:a.data}):(pE(i,{code:pT.invalid_intersection_types}),pq)};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}))}}md.create=(t,r,i)=>new md({left:t,right:r,typeName:L.ZodIntersection,...pL(i)});class mp extends pZ{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==px.array)return pE(i,{code:pT.invalid_type,expected:px.array,received:i.parsedType}),pq;if(i.data.length<this._def.items.length)return pE(i,{code:pT.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),pq;!this._def.rest&&i.data.length>this._def.items.length&&(pE(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 pN(i,t,i.path,r)):null}).filter(t=>!!t);return i.common.async?Promise.all(n).then(t=>pI.mergeArray(r,t)):pI.mergeArray(r,n)}get items(){return this._def.items}rest(t){return new mp({...this._def,rest:t})}}mp.create=(t,r)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new mp({items:t,typeName:L.ZodTuple,rest:null,...pL(r)})};class mm extends pZ{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!==px.object)return pE(i,{code:pT.invalid_type,expected:px.object,received:i.parsedType}),pq;let n=[],a=this._def.keyType,o=this._def.valueType;for(let t in i.data)n.push({key:a._parse(new pN(i,t,i.path,t)),value:o._parse(new pN(i,i.data[t],i.path,t)),alwaysSet:t in i.data});return i.common.async?pI.mergeObjectAsync(r,n):pI.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,i){return new mm(r instanceof pZ?{keyType:t,valueType:r,typeName:L.ZodRecord,...pL(i)}:{keyType:p4.create(),valueType:t,typeName:L.ZodRecord,...pL(r)})}}class mh extends pZ{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!==px.map)return pE(i,{code:pT.invalid_type,expected:px.map,received:i.parsedType}),pq;let n=this._def.keyType,a=this._def.valueType,o=[...i.data.entries()].map(([t,r],o)=>({key:n._parse(new pN(i,t,i.path,[o,"key"])),value:a._parse(new pN(i,r,i.path,[o,"value"]))}));if(i.common.async){let t=new Map;return Promise.resolve().then(async()=>{for(let i of o){let n=await i.key,a=await i.value;if("aborted"===n.status||"aborted"===a.status)return pq;("dirty"===n.status||"dirty"===a.status)&&r.dirty(),t.set(n.value,a.value)}return{status:r.value,value:t}})}{let t=new Map;for(let i of o){let n=i.key,a=i.value;if("aborted"===n.status||"aborted"===a.status)return pq;("dirty"===n.status||"dirty"===a.status)&&r.dirty(),t.set(n.value,a.value)}return{status:r.value,value:t}}}}mh.create=(t,r,i)=>new mh({valueType:r,keyType:t,typeName:L.ZodMap,...pL(i)});class mf extends pZ{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==px.set)return pE(i,{code:pT.invalid_type,expected:px.set,received:i.parsedType}),pq;let n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(pE(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&&(pE(i,{code:pT.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let a=this._def.valueType;function o(t){let i=new Set;for(let n of t){if("aborted"===n.status)return pq;"dirty"===n.status&&r.dirty(),i.add(n.value)}return{status:r.value,value:i}}let s=[...i.data.values()].map((t,r)=>a._parse(new pN(i,t,i.path,r)));return i.common.async?Promise.all(s).then(t=>o(t)):o(s)}min(t,r){return new mf({...this._def,minSize:{value:t,message:M.toString(r)}})}max(t,r){return new mf({...this._def,maxSize:{value:t,message:M.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}mf.create=(t,r)=>new mf({valueType:t,minSize:null,maxSize:null,typeName:L.ZodSet,...pL(r)});class mg extends pZ{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==px.function)return pE(r,{code:pT.invalid_type,expected:px.function,received:r.parsedType}),pq;function i(t,i){return pC({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pP,pP].filter(t=>!!t),issueData:{code:pT.invalid_arguments,argumentsError:i}})}function n(t,i){return pC({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pP,pP].filter(t=>!!t),issueData:{code:pT.invalid_return_type,returnTypeError:i}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof mw){let t=this;return pA(async function(...r){let s=new pO([]),l=await t._def.args.parseAsync(r,a).catch(t=>{throw s.addIssue(i(r,t)),s}),c=await Reflect.apply(o,this,l);return await t._def.returns._def.type.parseAsync(c,a).catch(t=>{throw s.addIssue(n(c,t)),s})})}{let t=this;return pA(function(...r){let s=t._def.args.safeParse(r,a);if(!s.success)throw new pO([i(r,s.error)]);let l=Reflect.apply(o,this,s.data),c=t._def.returns.safeParse(l,a);if(!c.success)throw new pO([n(l,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new mg({...this._def,args:mp.create(t).rest(mi.create())})}returns(t){return new mg({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new mg({args:t||mp.create([]).rest(mi.create()),returns:r||mi.create(),typeName:L.ZodFunction,...pL(i)})}}class my extends pZ{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})}}my.create=(t,r)=>new my({getter:t,typeName:L.ZodLazy,...pL(r)});class mv extends pZ{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return pE(r,{received:r.data,code:pT.invalid_literal,expected:this._def.value}),pq}return{status:"valid",value:t.data}}get value(){return this._def.value}}function m_(t,r){return new mb({values:t,typeName:L.ZodEnum,...pL(r)})}mv.create=(t,r)=>new mv({value:t,typeName:L.ZodLiteral,...pL(r)});class mb extends pZ{_parse(t){if("string"!=typeof t.data){let r=this._getOrReturnCtx(t),i=this._def.values;return pE(r,{expected:z.joinValues(i),received:r.parsedType,code:pT.invalid_type}),pq}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 pE(r,{received:r.data,code:pT.invalid_enum_value,options:i}),pq}return pA(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 mb.create(t,{...this._def,...r})}exclude(t,r=this._def){return mb.create(this.options.filter(r=>!t.includes(r)),{...this._def,...r})}}mb.create=m_;class mS extends pZ{_parse(t){let r=z.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==px.string&&i.parsedType!==px.number){let t=z.objectValues(r);return pE(i,{expected:z.joinValues(t),received:i.parsedType,code:pT.invalid_type}),pq}if(this._cache||(this._cache=new Set(z.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let t=z.objectValues(r);return pE(i,{received:i.data,code:pT.invalid_enum_value,options:t}),pq}return pA(t.data)}get enum(){return this._def.values}}mS.create=(t,r)=>new mS({values:t,typeName:L.ZodNativeEnum,...pL(r)});class mw extends pZ{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==px.promise&&!1===r.common.async?(pE(r,{code:pT.invalid_type,expected:px.promise,received:r.parsedType}),pq):pA((r.parsedType===px.promise?r.data:Promise.resolve(r.data)).then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}}mw.create=(t,r)=>new mw({type:t,typeName:L.ZodPromise,...pL(r)});class mR extends pZ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=this._def.effect||null,a={addIssue:t=>{pE(i,t),t.fatal?r.abort():r.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===n.type){let t=n.transform(i.data,a);if(i.common.async)return Promise.resolve(t).then(async t=>{if("aborted"===r.value)return pq;let n=await this._def.schema._parseAsync({data:t,path:i.path,parent:i});return"aborted"===n.status?pq:"dirty"===n.status||"dirty"===r.value?pj(n.value):n});{if("aborted"===r.value)return pq;let n=this._def.schema._parseSync({data:t,path:i.path,parent:i});return"aborted"===n.status?pq:"dirty"===n.status||"dirty"===r.value?pj(n.value):n}}if("refinement"===n.type){let t=t=>{let r=n.refinement(t,a);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?pq:("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?pq:("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?pq:Promise.resolve(n.transform(t.value,a)).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 pq;let o=n.transform(t.value,a);if(o instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}z.assertNever(n)}}mR.create=(t,r,i)=>new mR({schema:t,typeName:L.ZodEffects,effect:r,...pL(i)}),mR.createWithPreprocess=(t,r,i)=>new mR({schema:r,effect:{type:"preprocess",transform:t},typeName:L.ZodEffects,...pL(i)});class mk extends pZ{_parse(t){return this._getType(t)===px.undefined?pA(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mk.create=(t,r)=>new mk({innerType:t,typeName:L.ZodOptional,...pL(r)});class mx extends pZ{_parse(t){return this._getType(t)===px.null?pA(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mx.create=(t,r)=>new mx({innerType:t,typeName:L.ZodNullable,...pL(r)});class m$ extends pZ{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===px.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:L.ZodDefault,defaultValue:"function"==typeof r.default?r.default:()=>r.default,...pL(r)});class mT extends pZ{_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 pz(n)?n.then(t=>({status:"valid",value:"valid"===t.status?t.value:this._def.catchValue({get error(){return new pO(i.common.issues)},input:i.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new pO(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}mT.create=(t,r)=>new mT({innerType:t,typeName:L.ZodCatch,catchValue:"function"==typeof r.catch?r.catch:()=>r.catch,...pL(r)});class mO extends pZ{_parse(t){if(this._getType(t)!==px.nan){let r=this._getOrReturnCtx(t);return pE(r,{code:pT.invalid_type,expected:px.nan,received:r.parsedType}),pq}return{status:"valid",value:t.data}}}mO.create=t=>new mO({typeName:L.ZodNaN,...pL(t)}),Symbol("zod_brand");class mP extends pZ{_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 mC extends pZ{_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?pq:"dirty"===t.status?(r.dirty(),pj(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?pq:"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 mC({in:t,out:r,typeName:L.ZodPipeline})}}class mE extends pZ{_parse(t){let r=this._def.innerType._parse(t),i=t=>("valid"===t.status&&(t.value=Object.freeze(t.value)),t);return pz(r)?r.then(t=>i(t)):i(r)}unwrap(){return this._def.innerType}}mE.create=(t,r)=>new mE({innerType:t,typeName:L.ZodReadonly,...pL(r)}),ms.lazycreate,(I=L||(L={})).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",p4.create,p3.create,mO.create,p6.create,p5.create,p7.create,p8.create,me.create,mt.create,mr.create,mi.create,mn.create,ma.create,mo.create,ms.create,ms.strictCreate,ml.create,mu.create,md.create,mp.create,mm.create,mh.create,mf.create,mg.create,my.create,mv.create,mb.create,mS.create,mw.create,mR.create,mk.create,mx.create,mR.createWithPreprocess,mC.create;let mI=(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 mq(t){if("openAi"!==t.target)return{};let r=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===t.$refStrategy?mI(r,t.currentPath):r.join("/")}}function mj(t,r,i,n){n?.errorMessages&&i&&(t.errorMessage={...t.errorMessage,[r]:i})}function mA(t,r,i,n,a){t[r]=i,mj(t,r,n,a)}function mz(t,r){return m9(t.type._def,r)}let mN=/^[cC][^\s-]{8,}$/,mM=/^[0-9a-z]+$/,mL=/^[0-9A-HJKMNP-TV-Z]{26}$/,mZ=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,mU=()=>(void 0===k&&(k=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),k),mF=/^(?:(?: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])$/,mH=/^([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}(=)?))?$/,mV=/^[a-zA-Z0-9_-]{21}$/,mB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function mW(t,r){let i={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":mA(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r);break;case"max":mA(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":mY(i,"email",n.message,r);break;case"format:idn-email":mY(i,"idn-email",n.message,r);break;case"pattern:zod":mX(i,mZ,n.message,r)}break;case"url":mY(i,"uri",n.message,r);break;case"uuid":mY(i,"uuid",n.message,r);break;case"regex":mX(i,n.regex,n.message,r);break;case"cuid":mX(i,mN,n.message,r);break;case"cuid2":mX(i,mM,n.message,r);break;case"startsWith":mX(i,RegExp(`^${mG(n.value,r)}`),n.message,r);break;case"endsWith":mX(i,RegExp(`${mG(n.value,r)}$`),n.message,r);break;case"datetime":mY(i,"date-time",n.message,r);break;case"date":mY(i,"date",n.message,r);break;case"time":mY(i,"time",n.message,r);break;case"duration":mY(i,"duration",n.message,r);break;case"length":mA(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r),mA(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"includes":mX(i,RegExp(mG(n.value,r)),n.message,r);break;case"ip":"v6"!==n.version&&mY(i,"ipv4",n.message,r),"v4"!==n.version&&mY(i,"ipv6",n.message,r);break;case"base64url":mX(i,mJ,n.message,r);break;case"jwt":mX(i,mB,n.message,r);break;case"cidr":"v6"!==n.version&&mX(i,mF,n.message,r),"v4"!==n.version&&mX(i,mD,n.message,r);break;case"emoji":mX(i,mU(),n.message,r);break;case"ulid":mX(i,mL,n.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":mY(i,"binary",n.message,r);break;case"contentEncoding:base64":mA(i,"contentEncoding","base64",n.message,r);break;case"pattern:zod":mX(i,mH,n.message,r)}break;case"nanoid":mX(i,mV,n.message,r)}return i}function mG(t,r){return"escape"===r.patternStrategy?function(t){let r="";for(let i=0;i<t.length;i++)mK.has(t[i])||(r+="\\"),r+=t[i];return r}(t):t}let mK=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mY(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}}})):mA(t,"format",r,i,n)}function mX(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:mQ(r,n),...i&&n.errorMessages&&{errorMessage:{pattern:i}}})):mA(t,"pattern",mQ(r,n),i,n)}function mQ(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,a="",o=!1,s=!1,l=!1;for(let t=0;t<n.length;t++){if(o){a+=n[t],o=!1;continue}if(i.i){if(s){if(n[t].match(/[a-z]/)){l?(a+=n[t],a+=`${n[t-2]}-${n[t]}`.toUpperCase(),l=!1):"-"===n[t+1]&&n[t+2]?.match(/[a-z]/)?(a+=n[t],l=!0):a+=`${n[t]}${n[t].toUpperCase()}`;continue}}else if(n[t].match(/[a-z]/)){a+=`[${n[t]}${n[t].toUpperCase()}]`;continue}}if(i.m){if("^"===n[t]){a+=`(^|(?<=[\r
|
|
74
74
|
]))`;continue}else if("$"===n[t]){a+=`($|(?=[\r
|
|
75
75
|
]))`;continue}}if(i.s&&"."===n[t]){a+=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 hl(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 hs(r);let i=Object.keys(t),n=t.default,a=i.filter(t=>"__esModule"!==t);if(0===i.length||1===a.length&&"default"===a[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 hs(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 hc=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 a=i.length;t.warn(`[xmcp] ${a} resource${1===a?"":"s"} skipped due to empty files or missing default exports`)}}();function hu(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 hd(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 a=r[i].slice(1,-1),o=r.slice(i+1),s=o[o.length-1];if(s&&s.includes(".")){let t=s.split(".")[0];"index"!==t?o[o.length-1]=t:o.pop()}let l=[],c=[],u=o.map(t=>{if(!t.match(/^\[.+\]$/))return c.push(t),t;{let r=t.slice(1,-1);return l.push(r),`{${r}}`}}),d=`${a}://${u.join("/")}`,p=l.length>0?"template":"direct";return{filePath:t,uriTemplate:d,scheme:a,parameters:l,pathSegments:c,type:p}}function hp(t){return Error(`[xmcp] Invalid tool file: ${t}
|
|
82
82
|
-> Default export must be a tool handler function.`)}async function hm(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 hp(r);let i=Object.keys(t),n=t.default,a=i.filter(t=>"__esModule"!==t);if(0===i.length||1===a.length&&"default"===a[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 hp(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 hh=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 a=i.length;t.warn(`[xmcp] ${a} tool${1===a?"":"s"} skipped due to empty files or missing default exports`)}}(),hf=INJECTED_TOOLS,hg=INJECTED_PROMPTS,hy=INJECTED_RESOURCES,hv=SERVER_INFO;async function h_(t,r,i,n){let a=await INJECTED_MIDDLEWARE?.(),o=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}(a?.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,a)=>{let o,s,l;if("tools/call"!==t.method&&"prompts/get"!==t.method&&"resources/read"!==t.method)return a();try{s=performance.now(),o={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 a()}n({...o,event:{kind:"event",category:["api"],type:["start"],action:"execution.start"}});let c="unknown";try{let r=await a();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({...o,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:{...o.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&&o.unshift(s.middleware),
|
|
83
|
+
-> ${i}`)});let a=i.length;t.warn(`[xmcp] ${a} tool${1===a?"":"s"} skipped due to empty files or missing default exports`)}}(),hf=INJECTED_TOOLS,hg=INJECTED_PROMPTS,hy=INJECTED_RESOURCES,hv=SERVER_INFO;async function h_(t,r,i,n){let a=await INJECTED_MIDDLEWARE?.(),o=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}(a?.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,a)=>{let o,s,l;if("tools/call"!==t.method&&"prompts/get"!==t.method&&"resources/read"!==t.method)return a();try{s=performance.now(),o={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 a()}n({...o,event:{kind:"event",category:["api"],type:["start"],action:"execution.start"}});let c="unknown";try{let r=await a();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({...o,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:{...o.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&&o.unshift(s.middleware),d0.clear();let l="undefined"==typeof COMPONENTS_CONFIG?void 0:COMPONENTS_CONFIG;return!function(t,r,i){let n=t.server,a=n.setRequestHandler,o=pb(r);n.setRequestHandler=(t,...r)=>{if(pS.has(t)&&1===r.length&&"function"==typeof r[0]){let t=r[0];r[0]=(r,i)=>o({method:r.method,params:r.params??{}},i,()=>t(r,i))}Reflect.apply(a,n,[t,...r])};try{i()}finally{n.setRequestHandler=a}}(t,o,()=>{var a,c;!function(t,r,i=[]){r.forEach((r,n)=>{var a,o;let s,l,c,u,d={name:ht(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(he(h)?g=h:null!=h&&console.warn(`Invalid schema for tool "${d.name}" at ${n}. Expected Record<string, z.ZodType>`),null!=f)if(he(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={...dQ(d)._meta};let y=pw(n),v=!!(a=d._meta)&&"object"==typeof a&&"ui"in a&&"object"==typeof a.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,a={},o={};for(let[t,r]of Object.entries(n))m7.includes(t)?a[t]=r:m8.includes(t)?o[t]=r:a[t]=r;Object.keys(a).length>0&&(r.ui=a),Object.keys(o).length>0&&(i.ui=o)}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"),d0.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=m5(_),S=v?b:void 0;l=pw(n)&&v?async(t,r)=>({content:[{type:"text",text:""}],_meta:S,structuredContent:{args:t}}):function(t,r,i,n="unknown-tool"){return async(a,o)=>{let s,l,c=t(a,(s=p_(o),l=function(t){if(!t)return;let r={};return t.headers.forEach((t,i)=>{r[i]=t}),r}(o.http?.req),{signal:o.mcpReq.signal,authInfo:o.http?.authInfo,sessionId:o.sessionId,_meta:o.mcpReq._meta,requestId:o.mcpReq.id,requestInfo:l?{headers:l}:void 0,clientInfo:s,sendNotification:t=>o.mcpReq.notify(t),sendRequest:(t,r,i)=>o.mcpReq.send(t,r,i),elicit:(t,r)=>pr(o,t,r),sample:(t,r)=>pm(o,t,r),inputResponses:o.mcpReq.inputResponses,requestState:o.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 pv(r)?{content:[{type:"text",text:""}],structuredContent:{args:a},_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||(py(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(pv(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:a}]}}}(s,a.role||"assistant");he(c)?Object.assign(o,c):null!=c&&console.warn(`Invalid schema for prompt "${a.name}" at ${i}. Expected Record<string, z.ZodType>`),t.registerPrompt(a.name,{title:a.title,description:a.description,icons:a.icons,_meta:
|
|
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:a}]}}}(s,a.role||"assistant");he(c)?Object.assign(o,c):null!=c&&console.warn(`Invalid schema for prompt "${a.name}" at ${i}. Expected Record<string, z.ZodType>`),t.registerPrompt(a.name,{title:a.title,description:a.description,icons:a.icons,_meta:dQ(a)._meta,argsSchema:m6(o)},u)}),a=hi(n,l),c=s?.registerResource,[...d0.getAll()].forEach(([r,i])=>{let n=i.mimeType||"text/html;profile=mcp-app",a=i?._meta?m5(i._meta):void 0,o={name:i.name,description:`Auto-generated resource for ${i.name} tool`,mimeType:i.mimeType,_meta:a},s=async(t,r)=>{if(i.mimeType&&i.toolPath)try{var a;let t,r,o=(a=i.toolPath,IS_CLOUDFLARE?function(t){let{normalizedPath:r,baseName:i}=hu(t),n=5381;for(let t=0;t<r.length;t++)n=Math.imul(n,33)+r.charCodeAt(t)>>>0;let a=n.toString(16).slice(0,6).padStart(6,"0");return`${i}_${a}`}(a):function(t){let{normalizedPath:r,baseName:i}=hu(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}`}(a)),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 a=i.join(n,`${t}.bundle.js`),o=i.join(n,`${t}.bundle.css`);if(r.existsSync(a)){let t,i=r.readFileSync(a,"utf-8");return r.existsSync(o)&&(t=r.readFileSync(o,"utf-8")),{js:i,css:t}}}}catch{}return null}(o);if(!s)throw Error(`React client bundle not found for "${i.name}" (bundle: "${o}").
|
|
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,10 +224,10 @@ 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 o.contents.forEach(t=>{t.uri||(t.uri=r.href)}),o}}(a,i,u);if("direct"===d.type)c?.(n.name,p),t.registerResource(n.name,p,
|
|
227
|
+
}`)}return o.contents.forEach(t=>{t.uri||(t.uri=r.href)}),o}}(a,i,u);if("direct"===d.type)c?.(n.name,p),t.registerResource(n.name,p,dQ(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 db(p,{list:void 0,complete:r}),o=async(t,r,i)=>{let n={};for(let t of d.parameters){let i=r[t],a=u[t];if(void 0===i)throw Error(`Missing required parameter: ${t}. Available variables: ${Object.keys(r)}`);a?n[t]=a.parse(i):n[t]=i}let o=a(n,i);return o instanceof Promise&&(o=await o),"string"==typeof o?{contents:[{uri:t.href,text:o}]}:o};c?.(n.name,i),t.registerResource(n.name,i,dQ(n),o)}})}),t}async function hb(){let{toolModules:t,skippedTools:r}=await hm(hf);return hh(r),t}async function hS(){let{promptModules:t,skippedPrompts:r}=await ha(hg);return ho(r),t}async function hw(){let{resourceModules:t,skippedResources:r}=await hl(hy);return hc(r),t}let hR=function(t,r={}){var i;let{legacy:n,onerror:a,responseMode:o}=r,s=dI(r.maxRequestBodySize);if("function"==typeof n)throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let p=new Set,m=!1,h=t=>{try{a?.(t)}catch{}},f=r.bus??new da(h),g={toolsChanged:()=>f.publish({kind:"tools_list_changed"}),promptsChanged:()=>f.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>f.publish({kind:"resources_list_changed"}),resourceUpdated:t=>f.publish({kind:"resource_updated",uri:t})},y=function(t){let{bus:r,onerror:i}=t,n=t.maxSubscriptions??1024,a=t.keepAliveMs??15e3,o=new Set;return{serve:function(t,s,l,c){var u,d,p;let m,h,f,g,y,v,_;if(o.size>=n)return i?.(Error(`subscriptions/listen refused: subscription limit reached (${n})`)),ds(t.id,-32603,"Subscription limit reached");let b=(u=t,(y=cZ(cL).validateRequest("subscriptions/listen",u)).ok?y.value.params?.notifications:void 0);if(void 0===b)return ds(t.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let S=(d=b,p=l,v={},_=t=>void 0===p||!0===t,!0===d.toolsListChanged&&_(p?.tools?.listChanged)&&(v.toolsListChanged=!0),!0===d.promptsListChanged&&_(p?.prompts?.listChanged)&&(v.promptsListChanged=!0),!0===d.resourcesListChanged&&_(p?.resources?.listChanged)&&(v.resourcesListChanged=!0),void 0!==d.resourceSubscriptions&&d.resourceSubscriptions.length>0&&_(p?.resources?.subscribe)&&(v.resourceSubscriptions=[...d.resourceSubscriptions]),v),w=t.id,R=new TextEncoder,k=!1,x=t=>{if(!k)try{m.enqueue(R.encode(t))}catch(t){i?.(t instanceof Error?t:Error(String(t)))}},$=(t,r)=>{x(`event: message
|
|
228
228
|
data: ${JSON.stringify({jsonrpc:"2.0",method:t,params:r})}
|
|
229
229
|
|
|
230
230
|
`)},T=t=>{if(!k){t&&x(`event: message
|
|
231
231
|
data: ${JSON.stringify({jsonrpc:"2.0",id:w,result:{resultType:"complete",_meta:{[aQ]:w,[aY]:c}}})}
|
|
232
232
|
|
|
233
|
-
`),k=!0;try{h?.()}catch(t){i?.(t instanceof Error?t:Error(String(t)))}void 0!==f&&clearInterval(f),g?.(),o.delete(T);try{m.close()}catch{}}},O=new ReadableStream({start(t){m=t;let i=dl({method:"notifications/subscriptions/acknowledged",params:{notifications:S}},w);($(i.method,i.params),0===Object.keys(S).length)?T(!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=dl(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);$(r.method,r.params)}),f=dn(a,()=>x(": keepalive\n\n")),o.add(T))},cancel(){T(!1)}});if(void 0!==s)if(s.aborted)T(!1);else{let t=()=>T(!1);s.addEventListener("abort",t,{once:!0}),g=()=>s.removeEventListener("abort",t)}return new Response(O,{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 o)t(!0)},get openCount(){return o.size}}}({bus:f,maxSubscriptions:r.maxSubscriptions??1024,keepAliveMs:r.keepAliveMs??15e3,onerror:h});"json"===o&&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 dz(405,-32e3,"Method not allowed.");try{let a=await t({era:"legacy",...n?.authInfo!==void 0&&{authInfo:n.authInfo},requestInfo:r}),o=new dj({sessionIdGenerator:void 0,...void 0!==i&&{keepAliveMs:i},...void 0!==s&&{maxRequestBodySize:s}});await a.connect(o);let l=()=>{o.close().catch(()=>{}),a.close().catch(()=>{})};r.signal?.addEventListener("abort",l,{once:!0});let c=await o.handleRequest(r,{...n?.authInfo!==void 0&&{authInfo:n.authInfo},...n?.parsedBody!==void 0&&{parsedBody:n.parsedBody}});if(null===c.body||"text/event-stream"!==uL(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 dL(dA(n?.parsedBody))}});async function _(i,n,a){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),dz(400,t.code,t.message,t.data,dA(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:a,value:o}=n;if(void 0===t.mcpNameHeader){if(void 0===o)return;return us("name-header-missing","(missing)",`the body carries params.${a}="${o}" 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!==o&&l!==o?us("name-header-mismatch",s,`the body carries params.${a}="${o}" but the Mcp-Name header names "${l}"`,"standard-header-validation"):void 0}({httpMethod:n.method,...dU(n)},i);if(void 0!==g)return h(Error(`Rejected inbound request (${g.cell}): ${g.message}`)),dN(g,dA(i.message));let v="request"===i.messageKind?cB(i.message.params):void 0,_=v?.[aX];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),dz(ua[t.code]??400,t.code,t.message,t.data,i.message.id)}}}let b=await t({era:"modern",...void 0!==a&&{authInfo:a},requestInfo:n}),S=b instanceof d_?b.server:b;if(dZ(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 d_){let t=i.message.params,r="string"==typeof t?.name?t.name:void 0,a=void 0===r?void 0:b.toolInputSchemaJson(r);if(void 0!==a){let r=c6(a);if(r.valid&&r.declarations.length>0){let a=function(t,r,i){for(let n of t){let t=`Mcp-Param-${n.headerName}`,a=i.get(t),o=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==o)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)}}(o);if(void 0===s)continue;if(null===a)return ui("param-header-missing",t,`the body carries ${c8(n.path)}=${JSON.stringify(o)} but the ${t} header is absent`);let l=ur(a);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 o?Number(l)===o: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(o)}`)}}(r.declarations,t?.arguments,n.headers);if(void 0!==a)return b.close().catch(h),h(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),dN(a,i.message.id)}}}if("request"===i.messageKind&&b instanceof d_)try{let t=await dd([i.message],a,t=>b.resolveScopeChallenge(t));if(void 0!==t)return b.close().catch(h),dm(t,dp(a))}catch(t){return b.close().catch(h),h(dM(t)),dL(i.message.id)}dZ(S),l(S,f),u(S,l0),void 0!==v&&(m={clientInfo:v[aK],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 dC(b,i.message,{classification:i.classification,request:n,...void 0!==a&&{authInfo:a},...void 0!==o&&{responseMode:o},...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)),dL(dA(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 a=function(t,r){switch(t.reason){case"http-method":return uo("http-method","modern-only-method-not-allowed",405,new c_(-32e3,"Method not allowed."),!0);case"batch":return uo("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 uo("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 uo("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===a?new Response(null,{status:202}):(h(Error(`Rejected 2025-era request on a modern-only endpoint (${a.cell}): ${a.message}`)),dN(a,dA(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")),dz(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let n=await dF(t,r?.parsedBody,!0,s);if("unreadable-body"===n.step)return dz(400,-32700,"Parse error: the request body could not be read");if("body-too-large"===n.step)return dz(413,-32e3,dE(s));if("no-json-body"===n.step)return void 0!==v?v(n.forwardRequest,{...void 0!==i&&{authInfo:i}}):dz(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:a,body:o,parsedBody:l,forwardRequest:c}=n;try{switch(a.kind){case"reject":return h(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),dN(a,dA(o));case"modern":return await _(a,t,i);case"legacy":return await b(a,c,i,l)}}catch(t){return h(dM(t)),dL(dA(o))}}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)),dL(dA(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)}}}(async function(){let{instructions:t,...r}=hv,i=new d_(r,{instructions:t}),n=hb(),a=hS(),o=hw(),[s,l,c]=await Promise.all([n,a,o]);return h_(i,s,l,c)},{legacy:"stateless"});async function hk(t,r={}){let i="POST"===t.method?await t.clone().json().catch(()=>void 0):void 0;return dK({id:crypto.randomUUID(),headers:Object.fromEntries(t.headers.entries()),clientInfo:(t=>{for(let r of Array.isArray(t)?t:[t]){let t=d2(r);if(t)return t}})(i)},()=>hR.fetch(t,{parsedBody:i,authInfo:r.authInfo}))}var hx=D.r;export{hx as xmcpHandler};
|
|
233
|
+
`),k=!0;try{h?.()}catch(t){i?.(t instanceof Error?t:Error(String(t)))}void 0!==f&&clearInterval(f),g?.(),o.delete(T);try{m.close()}catch{}}},O=new ReadableStream({start(t){m=t;let i=dl({method:"notifications/subscriptions/acknowledged",params:{notifications:S}},w);($(i.method,i.params),0===Object.keys(S).length)?T(!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=dl(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);$(r.method,r.params)}),f=dn(a,()=>x(": keepalive\n\n")),o.add(T))},cancel(){T(!1)}});if(void 0!==s)if(s.aborted)T(!1);else{let t=()=>T(!1);s.addEventListener("abort",t,{once:!0}),g=()=>s.removeEventListener("abort",t)}return new Response(O,{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 o)t(!0)},get openCount(){return o.size}}}({bus:f,maxSubscriptions:r.maxSubscriptions??1024,keepAliveMs:r.keepAliveMs??15e3,onerror:h});"json"===o&&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 dz(405,-32e3,"Method not allowed.");try{let a=await t({era:"legacy",...n?.authInfo!==void 0&&{authInfo:n.authInfo},requestInfo:r}),o=new dj({sessionIdGenerator:void 0,...void 0!==i&&{keepAliveMs:i},...void 0!==s&&{maxRequestBodySize:s}});await a.connect(o);let l=()=>{o.close().catch(()=>{}),a.close().catch(()=>{})};r.signal?.addEventListener("abort",l,{once:!0});let c=await o.handleRequest(r,{...n?.authInfo!==void 0&&{authInfo:n.authInfo},...n?.parsedBody!==void 0&&{parsedBody:n.parsedBody}});if(null===c.body||"text/event-stream"!==uL(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 dL(dA(n?.parsedBody))}});async function _(i,n,a){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),dz(400,t.code,t.message,t.data,dA(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:a,value:o}=n;if(void 0===t.mcpNameHeader){if(void 0===o)return;return us("name-header-missing","(missing)",`the body carries params.${a}="${o}" 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!==o&&l!==o?us("name-header-mismatch",s,`the body carries params.${a}="${o}" but the Mcp-Name header names "${l}"`,"standard-header-validation"):void 0}({httpMethod:n.method,...dU(n)},i);if(void 0!==g)return h(Error(`Rejected inbound request (${g.cell}): ${g.message}`)),dN(g,dA(i.message));let v="request"===i.messageKind?cB(i.message.params):void 0,_=v?.[aX];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),dz(ua[t.code]??400,t.code,t.message,t.data,i.message.id)}}}let b=await t({era:"modern",...void 0!==a&&{authInfo:a},requestInfo:n}),S=b instanceof d_?b.server:b;if(dZ(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 d_){let t=i.message.params,r="string"==typeof t?.name?t.name:void 0,a=void 0===r?void 0:b.toolInputSchemaJson(r);if(void 0!==a){let r=c6(a);if(r.valid&&r.declarations.length>0){let a=function(t,r,i){for(let n of t){let t=`Mcp-Param-${n.headerName}`,a=i.get(t),o=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==o)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)}}(o);if(void 0===s)continue;if(null===a)return ui("param-header-missing",t,`the body carries ${c8(n.path)}=${JSON.stringify(o)} but the ${t} header is absent`);let l=ur(a);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 o?Number(l)===o: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(o)}`)}}(r.declarations,t?.arguments,n.headers);if(void 0!==a)return b.close().catch(h),h(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),dN(a,i.message.id)}}}if("request"===i.messageKind&&b instanceof d_)try{let t=await dd([i.message],a,t=>b.resolveScopeChallenge(t));if(void 0!==t)return b.close().catch(h),dm(t,dp(a))}catch(t){return b.close().catch(h),h(dM(t)),dL(i.message.id)}dZ(S),l(S,f),u(S,l0),void 0!==v&&(m={clientInfo:v[aK],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 dC(b,i.message,{classification:i.classification,request:n,...void 0!==a&&{authInfo:a},...void 0!==o&&{responseMode:o},...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)),dL(dA(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 a=function(t,r){switch(t.reason){case"http-method":return uo("http-method","modern-only-method-not-allowed",405,new c_(-32e3,"Method not allowed."),!0);case"batch":return uo("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 uo("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 uo("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===a?new Response(null,{status:202}):(h(Error(`Rejected 2025-era request on a modern-only endpoint (${a.cell}): ${a.message}`)),dN(a,dA(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")),dz(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let n=await dF(t,r?.parsedBody,!0,s);if("unreadable-body"===n.step)return dz(400,-32700,"Parse error: the request body could not be read");if("body-too-large"===n.step)return dz(413,-32e3,dE(s));if("no-json-body"===n.step)return void 0!==v?v(n.forwardRequest,{...void 0!==i&&{authInfo:i}}):dz(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:a,body:o,parsedBody:l,forwardRequest:c}=n;try{switch(a.kind){case"reject":return h(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),dN(a,dA(o));case"modern":return await _(a,t,i);case"legacy":return await b(a,c,i,l)}}catch(t){return h(dM(t)),dL(dA(o))}}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)),dL(dA(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)}}}(async function(){let{instructions:t,...r}=hv,i=new d_(r,{instructions:t}),n=hb(),a=hS(),o=hw(),[s,l,c]=await Promise.all([n,a,o]);return h_(i,s,l,c)},{legacy:"stateless",maxSubscriptions:HTTP_CONFIG.maxSubscriptions});async function hk(t,r={}){let i="POST"===t.method?await t.clone().json().catch(()=>void 0):void 0;return dW({id:crypto.randomUUID(),headers:Object.fromEntries(t.headers.entries()),clientInfo:(t=>{for(let r of Array.isArray(t)?t:[t]){let t=dY(r);if(t)return t}})(i)},()=>hR.fetch(t,{parsedBody:i,authInfo:r.authInfo}))}var hx=D.r;export{hx as xmcpHandler};
|