@onyxsecurity/mcp-gateway 1.0.9 → 1.0.10

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/dist/index.d.ts CHANGED
@@ -114,6 +114,7 @@ declare class AccessControlClient {
114
114
  interface AccessControlConfig {
115
115
  client?: AccessControlClient;
116
116
  enabled: boolean;
117
+ serverName?: string;
117
118
  }
118
119
  /**
119
120
  * Authorizes MCP servers based on access control configuration.
@@ -123,6 +124,7 @@ declare class AccessControlAuthorizer {
123
124
  private client?;
124
125
  private enabled;
125
126
  private lastBlockReason?;
127
+ private serverName?;
126
128
  constructor(config: AccessControlConfig);
127
129
  /**
128
130
  * Get human-readable reason for why a server was blocked.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{Client as e,InMemoryEventStore as t,SSEClientTransport as n,Server as r,StdioServerTransport as i,StreamableHTTPClientTransport as a,config as o,proxyServer as s,startHTTPServer as c}from"./stdio-BRHpVFf0.js";let l=function(e){return e.HTTPStream=`HTTPStream`,e.SSE=`SSE`,e}({});const u=async({initStdioServer:t,initStreamClient:c,serverType:u,transportOptions:d={},url:f})=>{let p;switch(u){case l.SSE:p=new n(new URL(f),d);break;default:p=new a(new URL(f),d)}let m=c?await c():new e({name:`mcp-gateway`,version:o.appVersion},{capabilities:{}});await m.connect(p);let h=m.getServerVersion(),g=m.getServerCapabilities(),_=t?await t():new r(h,{capabilities:g}),v=new i;return await _.connect(v),await s({authorizer:void 0,client:m,server:_,serverCapabilities:g}),_},d=(e,t)=>{let n=e.close.bind(e),r=e.onclose?.bind(e),i=e.onerror?.bind(e),a=e.onmessage?.bind(e),o=e.send.bind(e),s=e.start.bind(e);return e.close=async()=>(t({type:`close`}),n?.()),e.onclose=async()=>(t({type:`onclose`}),r?.()),e.onerror=async e=>(t({error:e,type:`onerror`}),i?.(e)),e.onmessage=async e=>(t({message:e,type:`onmessage`}),a?.(e)),e.send=async e=>(t({message:e,type:`send`}),o?.(e)),e.start=async()=>(t({type:`start`}),s?.()),e};export{t as InMemoryEventStore,l as ServerType,s as proxyServer,c as startHTTPServer,u as startStdioServer,d as tapTransport};
1
+ import{Client as e,InMemoryEventStore as t,SSEClientTransport as n,Server as r,StdioServerTransport as i,StreamableHTTPClientTransport as a,config as o,proxyServer as s,startHTTPServer as c}from"./stdio-DLhH1AFQ.js";let l=function(e){return e.HTTPStream=`HTTPStream`,e.SSE=`SSE`,e}({});const u=async({initStdioServer:t,initStreamClient:c,serverType:u,transportOptions:d={},url:f})=>{let p;switch(u){case l.SSE:p=new n(new URL(f),d);break;default:p=new a(new URL(f),d)}let m=c?await c():new e({name:`mcp-gateway`,version:o.appVersion},{capabilities:{}});await m.connect(p);let h=m.getServerVersion(),g=m.getServerCapabilities(),_=t?await t():new r(h,{capabilities:g}),v=new i;return await _.connect(v),await s({authorizer:void 0,client:m,server:_,serverCapabilities:g}),_},d=(e,t)=>{let n=e.close.bind(e),r=e.onclose?.bind(e),i=e.onerror?.bind(e),a=e.onmessage?.bind(e),o=e.send.bind(e),s=e.start.bind(e);return e.close=async()=>(t({type:`close`}),n?.()),e.onclose=async()=>(t({type:`onclose`}),r?.()),e.onerror=async e=>(t({error:e,type:`onerror`}),i?.(e)),e.onmessage=async e=>(t({message:e,type:`onmessage`}),a?.(e)),e.send=async e=>(t({message:e,type:`send`}),o?.(e)),e.start=async()=>(t({type:`start`}),s?.()),e};export{t as InMemoryEventStore,l as ServerType,s as proxyServer,c as startHTTPServer,u as startStdioServer,d as tapTransport};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import{createRequire as e}from"node:module";import{randomUUID as t}from"crypto";import{existsSync as n,mkdirSync as r,readFileSync as i}from"node:fs";import{join as a}from"node:path";import o from"winston";import s from"winston-daily-rotate-file";import{homedir as c,hostname as l}from"node:os";import u from"env-var";import"dotenv/config";import*as d from"@sentry/node";import f from"ps-list";import{deflateSync as p}from"node:zlib";import{randomUUID as m}from"node:crypto";import{URL as h}from"url";import g from"node:http";import _ from"node:process";var v=Object.create,y=Object.defineProperty,b=Object.getOwnPropertyDescriptor,x=Object.getOwnPropertyNames,S=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty,w=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),T=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=x(t),a=0,o=i.length,s;a<o;a++)s=i[a],!C.call(e,s)&&s!==n&&y(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=b(t,s))||r.enumerable});return e},E=(e,t,n)=>(n=e==null?{}:v(S(e)),T(t||!e||!e.__esModule?y(n,`default`,{value:e,enumerable:!0}):n,e)),D=e(import.meta.url),O=class{events=new Map;async replayEventsAfter(e,{send:t}){if(!e||!this.events.has(e))return``;let n=this.getStreamIdFromEventId(e);if(!n)return``;let r=!1,i=[...this.events.entries()].sort((e,t)=>e[0].localeCompare(t[0]));for(let[a,{message:o,streamId:s}]of i){if(s!==n)continue;if(a===e){r=!0;continue}r&&await t(a,o)}return n}async storeEvent(e,t){let n=this.generateEventId(e);return this.events.set(n,{message:t,streamId:e}),n}generateEventId(e){return`${e}_${Date.now()}_${Math.random().toString(36).substring(2,10)}`}getStreamIdFromEventId(e){let t=e.split(`_`);return t.length>0?t[0]:``}},k;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(k||={});var A;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(A||={});const j=k.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),M=e=>{switch(typeof e){case`undefined`:return j.undefined;case`string`:return j.string;case`number`:return Number.isNaN(e)?j.nan:j.number;case`boolean`:return j.boolean;case`function`:return j.function;case`bigint`:return j.bigint;case`symbol`:return j.symbol;case`object`:return Array.isArray(e)?j.array:e===null?j.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?j.promise:typeof Map<`u`&&e instanceof Map?j.map:typeof Set<`u`&&e instanceof Set?j.set:typeof Date<`u`&&e instanceof Date?j.date:j.object;default:return j.unknown}},N=k.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var P=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,k.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};P.create=e=>new P(e);var F=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===j.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,k.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${k.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${k.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${k.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:k.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case N.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,k.assertNever(e)}return{message:n}};let ee=F;function te(){return ee}const I=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function L(e,t){let n=te(),r=I({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===F?void 0:F].filter(e=>!!e)});e.common.issues.push(r)}var R=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return z;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return z;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const z=Object.freeze({status:`aborted`}),ne=e=>({status:`dirty`,value:e}),B=e=>({status:`valid`,value:e}),re=e=>e.status===`aborted`,V=e=>e.status===`dirty`,ie=e=>e.status===`valid`,ae=e=>typeof Promise<`u`&&e instanceof Promise;var H;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(H||={});var U=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}};const oe=(e,t)=>{if(ie(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new P(e.common.issues),this._error}}};function W(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var G=class{get description(){return this._def.description}_getType(e){return M(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:M(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new R,ctx:{common:e.parent.common,data:e.data,parsedType:M(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ae(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:M(e)},r=this._parseSync({data:e,path:n.path,parent:n});return oe(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:M(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ie(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ie(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:M(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(ae(r)?r:Promise.resolve(r));return oe(n,i)}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:N.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ct({schema:this,typeName:K.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:e=>this[`~validate`](e)}}optional(){return lt.create(this,this._def)}nullable(){return ut.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ue.create(this)}promise(){return st.create(this,this._def)}or(e){return Ke.create([this,e],this._def)}and(e){return Xe.create(this,e,this._def)}transform(e){return new ct({...W(this._def),schema:this,typeName:K.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new dt({...W(this._def),innerType:this,defaultValue:t,typeName:K.ZodDefault})}brand(){return new mt({typeName:K.ZodBranded,type:this,...W(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ft({...W(this._def),innerType:this,catchValue:t,typeName:K.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ht.create(this,e)}readonly(){return gt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const se=/^c[^\s-]{8,}$/i,ce=/^[0-9a-z]+$/,le=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ue=/^[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,de=/^[a-z0-9_-]{21}$/i,fe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pe=/^[-+]?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)?)??$/,me=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let he;const ge=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_e=/^(?:(?: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])$/,ve=/^(([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]))$/,ye=/^(([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])$/,be=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Se=`((\\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])))`,Ce=RegExp(`^${Se}$`);function we(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Te(e){return RegExp(`^${we(e)}$`)}function Ee(e){let t=`${Se}T${we(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function De(e,t){return!!((t===`v4`||!t)&&ge.test(e)||(t===`v6`||!t)&&ve.test(e))}function Oe(e,t){if(!fe.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function ke(e,t){return!!((t===`v4`||!t)&&_e.test(e)||(t===`v6`||!t)&&ye.test(e))}var Ae=class e extends G{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.string,received:t.parsedType}),z}let t=new R,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),L(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),L(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?L(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&L(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)me.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)he||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),he.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ue.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)de.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)se.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ce.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)le.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),L(n,{validation:`url`,code:N.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`regex`,code:N.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Ee(r).test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Ce.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Te(r).test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?pe.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?De(e.data,r.version)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Oe(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?ke(e.data,r.version)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?be.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?xe.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):k.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...H.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...H.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...H.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...H.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...H.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...H.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...H.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...H.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...H.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...H.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...H.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...H.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...H.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...H.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...H.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...H.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...H.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...H.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...H.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...H.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...H.errToObj(t)})}nonempty(e){return this.min(1,H.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ae.create=e=>new Ae({checks:[],typeName:K.ZodString,coerce:e?.coerce??!1,...W(e)});function je(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r,a=Number.parseInt(e.toFixed(i).replace(`.`,``)),o=Number.parseInt(t.toFixed(i).replace(`.`,``));return a%o/10**i}var Me=class e extends G{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==j.number){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.number,received:t.parsedType}),z}let t,n=new R;for(let r of this._def.checks)r.kind===`int`?k.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),L(t,{code:N.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?je(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),L(t,{code:N.not_finite,message:r.message}),n.dirty()):k.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,H.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,H.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,H.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,H.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:H.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:H.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:H.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:H.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:H.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:H.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&k.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Me.create=e=>new Me({checks:[],typeName:K.ZodNumber,coerce:e?.coerce||!1,...W(e)});var Ne=class e extends G{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==j.bigint)return this._getInvalidInput(e);let t,n=new R;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):k.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.bigint,received:t.parsedType}),z}gte(e,t){return this.setLimit(`min`,e,!0,H.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,H.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,H.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,H.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:H.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:H.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ne.create=e=>new Ne({checks:[],typeName:K.ZodBigInt,coerce:e?.coerce??!1,...W(e)});var Pe=class extends G{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.boolean,received:t.parsedType}),z}return B(e.data)}};Pe.create=e=>new Pe({typeName:K.ZodBoolean,coerce:e?.coerce||!1,...W(e)});var Fe=class e extends G{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.date,received:t.parsedType}),z}if(Number.isNaN(e.data.getTime())){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_date}),z}let t=new R,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),L(n,{code:N.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),L(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):k.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:H.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:H.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Fe.create=e=>new Fe({checks:[],coerce:e?.coerce||!1,typeName:K.ZodDate,...W(e)});var Ie=class extends G{_parse(e){if(this._getType(e)!==j.symbol){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.symbol,received:t.parsedType}),z}return B(e.data)}};Ie.create=e=>new Ie({typeName:K.ZodSymbol,...W(e)});var Le=class extends G{_parse(e){if(this._getType(e)!==j.undefined){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.undefined,received:t.parsedType}),z}return B(e.data)}};Le.create=e=>new Le({typeName:K.ZodUndefined,...W(e)});var Re=class extends G{_parse(e){if(this._getType(e)!==j.null){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.null,received:t.parsedType}),z}return B(e.data)}};Re.create=e=>new Re({typeName:K.ZodNull,...W(e)});var ze=class extends G{constructor(){super(...arguments),this._any=!0}_parse(e){return B(e.data)}};ze.create=e=>new ze({typeName:K.ZodAny,...W(e)});var Be=class extends G{constructor(){super(...arguments),this._unknown=!0}_parse(e){return B(e.data)}};Be.create=e=>new Be({typeName:K.ZodUnknown,...W(e)});var Ve=class extends G{_parse(e){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.never,received:t.parsedType}),z}};Ve.create=e=>new Ve({typeName:K.ZodNever,...W(e)});var He=class extends G{_parse(e){if(this._getType(e)!==j.undefined){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.void,received:t.parsedType}),z}return B(e.data)}};He.create=e=>new He({typeName:K.ZodVoid,...W(e)});var Ue=class e extends G{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==j.array)return L(t,{code:N.invalid_type,expected:j.array,received:t.parsedType}),z;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(L(t,{code:e?N.too_big:N.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(L(t,{code:N.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(L(t,{code:N.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new U(t,e,t.path,n)))).then(e=>R.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new U(t,e,t.path,n)));return R.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:H.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:H.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:H.toString(n)}})}nonempty(e){return this.min(1,e)}};Ue.create=(e,t)=>new Ue({type:e,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...W(t)});function We(e){if(e instanceof Ge){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=lt.create(We(r))}return new Ge({...e._def,shape:()=>t})}else if(e instanceof Ue)return new Ue({...e._def,type:We(e.element)});else if(e instanceof lt)return lt.create(We(e.unwrap()));else if(e instanceof ut)return ut.create(We(e.unwrap()));else if(e instanceof Ze)return Ze.create(e.items.map(e=>We(e)));else return e}var Ge=class e extends G{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=k.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==j.object){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.object,received:t.parsedType}),z}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ve&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new U(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Ve){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(L(n,{code:N.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new U(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>R.mergeObjectSync(t,e)):R.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return H.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:H.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:K.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of k.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of k.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return We(this)}partial(t){let n={};for(let e of k.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of k.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof lt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return it(k.objectKeys(this.shape))}};Ge.create=(e,t)=>new Ge({shape:()=>e,unknownKeys:`strip`,catchall:Ve.create(),typeName:K.ZodObject,...W(t)}),Ge.strictCreate=(e,t)=>new Ge({shape:()=>e,unknownKeys:`strict`,catchall:Ve.create(),typeName:K.ZodObject,...W(t)}),Ge.lazycreate=(e,t)=>new Ge({shape:e,unknownKeys:`strip`,catchall:Ve.create(),typeName:K.ZodObject,...W(t)});var Ke=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new P(e.ctx.common.issues));return L(t,{code:N.invalid_union,unionErrors:n}),z}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new P(e));return L(t,{code:N.invalid_union,unionErrors:i}),z}}get options(){return this._def.options}};Ke.create=(e,t)=>new Ke({options:e,typeName:K.ZodUnion,...W(t)});const qe=e=>e instanceof nt?qe(e.schema):e instanceof ct?qe(e.innerType()):e instanceof rt?[e.value]:e instanceof at?e.options:e instanceof ot?k.objectValues(e.enum):e instanceof dt?qe(e._def.innerType):e instanceof Le?[void 0]:e instanceof Re?[null]:e instanceof lt?[void 0,...qe(e.unwrap())]:e instanceof ut?[null,...qe(e.unwrap())]:e instanceof mt||e instanceof gt?qe(e.unwrap()):e instanceof ft?qe(e._def.innerType):[];var Je=class e extends G{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.object)return L(t,{code:N.invalid_type,expected:j.object,received:t.parsedType}),z;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(L(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=qe(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:K.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...W(r)})}};function Ye(e,t){let n=M(e),r=M(t);if(e===t)return{valid:!0,data:e};if(n===j.object&&r===j.object){let n=k.objectKeys(t),r=k.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Ye(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===j.array&&r===j.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Ye(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===j.date&&r===j.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Xe=class extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(re(e)||re(r))return z;let i=Ye(e.value,r.value);return i.valid?((V(e)||V(r))&&t.dirty(),{status:t.value,value:i.data}):(L(n,{code:N.invalid_intersection_types}),z)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Xe.create=(e,t,n)=>new Xe({left:e,right:t,typeName:K.ZodIntersection,...W(n)});var Ze=class e extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.array)return L(n,{code:N.invalid_type,expected:j.array,received:n.parsedType}),z;if(n.data.length<this._def.items.length)return L(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),z;!this._def.rest&&n.data.length>this._def.items.length&&(L(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new U(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>R.mergeArray(t,e)):R.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ze.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Ze({items:e,typeName:K.ZodTuple,rest:null,...W(t)})};var Qe=class e extends G{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.object)return L(n,{code:N.invalid_type,expected:j.object,received:n.parsedType}),z;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new U(n,e,n.path,e)),value:a._parse(new U(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?R.mergeObjectAsync(t,r):R.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof G?new e({keyType:t,valueType:n,typeName:K.ZodRecord,...W(r)}):new e({keyType:Ae.create(),valueType:t,typeName:K.ZodRecord,...W(n)})}},$e=class extends G{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.map)return L(n,{code:N.invalid_type,expected:j.map,received:n.parsedType}),z;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new U(n,e,n.path,[a,`key`])),value:i._parse(new U(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return z;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return z;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};$e.create=(e,t,n)=>new $e({valueType:t,keyType:e,typeName:K.ZodMap,...W(n)});var et=class e extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.set)return L(n,{code:N.invalid_type,expected:j.set,received:n.parsedType}),z;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(L(n,{code:N.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(L(n,{code:N.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return z;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new U(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:H.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:H.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};et.create=(e,t)=>new et({valueType:e,minSize:null,maxSize:null,typeName:K.ZodSet,...W(t)});var tt=class e extends G{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.function)return L(t,{code:N.invalid_type,expected:j.function,received:t.parsedType}),z;function n(e,n){return I({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,te(),F].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return I({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,te(),F].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof st){let e=this;return B(async function(...t){let o=new P([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return B(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new P([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new P([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ze.create(t).rest(Be.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Ze.create([]).rest(Be.create()),returns:n||Be.create(),typeName:K.ZodFunction,...W(r)})}},nt=class extends G{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};nt.create=(e,t)=>new nt({getter:e,typeName:K.ZodLazy,...W(t)});var rt=class extends G{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return L(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),z}return{status:`valid`,value:e.data}}get value(){return this._def.value}};rt.create=(e,t)=>new rt({value:e,typeName:K.ZodLiteral,...W(t)});function it(e,t){return new at({values:e,typeName:K.ZodEnum,...W(t)})}var at=class e extends G{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return L(t,{expected:k.joinValues(n),received:t.parsedType,code:N.invalid_type}),z}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return L(t,{received:t.data,code:N.invalid_enum_value,options:n}),z}return B(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};at.create=it;var ot=class extends G{_parse(e){let t=k.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==j.string&&n.parsedType!==j.number){let e=k.objectValues(t);return L(n,{expected:k.joinValues(e),received:n.parsedType,code:N.invalid_type}),z}if(this._cache||=new Set(k.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=k.objectValues(t);return L(n,{received:n.data,code:N.invalid_enum_value,options:e}),z}return B(e.data)}get enum(){return this._def.values}};ot.create=(e,t)=>new ot({values:e,typeName:K.ZodNativeEnum,...W(t)});var st=class extends G{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.promise&&t.common.async===!1)return L(t,{code:N.invalid_type,expected:j.promise,received:t.parsedType}),z;let n=t.parsedType===j.promise?t.data:Promise.resolve(t.data);return B(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};st.create=(e,t)=>new st({type:e,typeName:K.ZodPromise,...W(t)});var ct=class extends G{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{L(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return z;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?z:r.status===`dirty`||t.value===`dirty`?ne(r.value):r});{if(t.value===`aborted`)return z;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?z:r.status===`dirty`||t.value===`dirty`?ne(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?z:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?z:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ie(e))return z;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>ie(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):z);k.assertNever(r)}};ct.create=(e,t,n)=>new ct({schema:e,typeName:K.ZodEffects,effect:t,...W(n)}),ct.createWithPreprocess=(e,t,n)=>new ct({schema:t,effect:{type:`preprocess`,transform:e},typeName:K.ZodEffects,...W(n)});var lt=class extends G{_parse(e){return this._getType(e)===j.undefined?B(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lt.create=(e,t)=>new lt({innerType:e,typeName:K.ZodOptional,...W(t)});var ut=class extends G{_parse(e){return this._getType(e)===j.null?B(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ut.create=(e,t)=>new ut({innerType:e,typeName:K.ZodNullable,...W(t)});var dt=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===j.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};dt.create=(e,t)=>new dt({innerType:e,typeName:K.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...W(t)});var ft=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ae(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new P(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new P(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ft.create=(e,t)=>new ft({innerType:e,typeName:K.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...W(t)});var pt=class extends G{_parse(e){if(this._getType(e)!==j.nan){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.nan,received:t.parsedType}),z}return{status:`valid`,value:e.data}}};pt.create=e=>new pt({typeName:K.ZodNaN,...W(e)});var mt=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ht=class e extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?z:e.status===`dirty`?(t.dirty(),ne(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?z:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:K.ZodPipeline})}},gt=class extends G{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ie(e)&&(e.value=Object.freeze(e.value)),e);return ae(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};gt.create=(e,t)=>new gt({innerType:e,typeName:K.ZodReadonly,...W(t)}),Ge.lazycreate;var K;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(K||={});const q=Ae.create,_t=Me.create;pt.create,Ne.create;const vt=Pe.create;Fe.create,Ie.create,Le.create,Re.create;const yt=ze.create,bt=Be.create;Ve.create,He.create;const J=Ue.create,Y=Ge.create;Ge.strictCreate;const xt=Ke.create,St=Je.create;Xe.create,Ze.create;const Ct=Qe.create;$e.create,et.create,tt.create,nt.create;const X=rt.create,wt=at.create;ot.create,st.create,ct.create;const Z=lt.create;ut.create,ct.createWithPreprocess,ht.create;const Tt=z,Et=`2025-06-18`,Dt=[Et,`2025-03-26`,`2024-11-05`,`2024-10-07`],Ot=xt([q(),_t().int()]),kt=q(),At=Y({progressToken:Z(Ot)}).passthrough(),jt=Y({_meta:Z(At)}).passthrough(),Mt=Y({method:q(),params:Z(jt)}),Nt=Y({_meta:Z(Y({}).passthrough())}).passthrough(),Pt=Y({method:q(),params:Z(Nt)}),Ft=Y({_meta:Z(Y({}).passthrough())}).passthrough(),It=xt([q(),_t().int()]),Lt=Y({jsonrpc:X(`2.0`),id:It}).merge(Mt).strict(),Rt=e=>Lt.safeParse(e).success,zt=Y({jsonrpc:X(`2.0`)}).merge(Pt).strict(),Bt=e=>zt.safeParse(e).success,Vt=Y({jsonrpc:X(`2.0`),id:It,result:Ft}).strict(),Ht=e=>Vt.safeParse(e).success;var Ut;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`})(Ut||={});const Wt=Y({jsonrpc:X(`2.0`),id:It,error:Y({code:_t().int(),message:q(),data:Z(bt())})}).strict(),Gt=e=>Wt.safeParse(e).success,Kt=xt([Lt,zt,Vt,Wt]),qt=Ft.strict(),Jt=Pt.extend({method:X(`notifications/cancelled`),params:Nt.extend({requestId:It,reason:q().optional()})}),Yt=Y({src:q(),mimeType:Z(q()),sizes:Z(q())}).passthrough(),Xt=Y({name:q(),title:Z(q())}).passthrough(),Zt=Xt.extend({version:q(),websiteUrl:Z(q()),icons:Z(J(Yt))}),Qt=Y({experimental:Z(Y({}).passthrough()),sampling:Z(Y({}).passthrough()),elicitation:Z(Y({}).passthrough()),roots:Z(Y({listChanged:Z(vt())}).passthrough())}).passthrough(),$t=Mt.extend({method:X(`initialize`),params:jt.extend({protocolVersion:q(),capabilities:Qt,clientInfo:Zt})}),en=e=>$t.safeParse(e).success,tn=Y({experimental:Z(Y({}).passthrough()),logging:Z(Y({}).passthrough()),completions:Z(Y({}).passthrough()),prompts:Z(Y({listChanged:Z(vt())}).passthrough()),resources:Z(Y({subscribe:Z(vt()),listChanged:Z(vt())}).passthrough()),tools:Z(Y({listChanged:Z(vt())}).passthrough())}).passthrough(),nn=Ft.extend({protocolVersion:q(),capabilities:tn,serverInfo:Zt,instructions:Z(q())}),rn=Pt.extend({method:X(`notifications/initialized`)}),an=e=>rn.safeParse(e).success,on=Mt.extend({method:X(`ping`)}),sn=Y({progress:_t(),total:Z(_t()),message:Z(q())}).passthrough(),cn=Pt.extend({method:X(`notifications/progress`),params:Nt.merge(sn).extend({progressToken:Ot})}),ln=Mt.extend({params:jt.extend({cursor:Z(kt)}).optional()}),un=Ft.extend({nextCursor:Z(kt)}),dn=Y({uri:q(),mimeType:Z(q()),_meta:Z(Y({}).passthrough())}).passthrough(),fn=dn.extend({text:q()}),pn=q().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),mn=dn.extend({blob:pn}),hn=Xt.extend({uri:q(),description:Z(q()),mimeType:Z(q()),icons:Z(J(Yt)),_meta:Z(Y({}).passthrough())}),gn=Xt.extend({uriTemplate:q(),description:Z(q()),mimeType:Z(q()),_meta:Z(Y({}).passthrough())}),_n=ln.extend({method:X(`resources/list`)}),vn=un.extend({resources:J(hn)}),yn=ln.extend({method:X(`resources/templates/list`)}),bn=un.extend({resourceTemplates:J(gn)}),xn=Mt.extend({method:X(`resources/read`),params:jt.extend({uri:q()})}),Sn=Ft.extend({contents:J(xt([fn,mn]))}),Cn=Pt.extend({method:X(`notifications/resources/list_changed`)}),wn=Mt.extend({method:X(`resources/subscribe`),params:jt.extend({uri:q()})}),Tn=Mt.extend({method:X(`resources/unsubscribe`),params:jt.extend({uri:q()})}),En=Pt.extend({method:X(`notifications/resources/updated`),params:Nt.extend({uri:q()})}),Dn=Y({name:q(),description:Z(q()),required:Z(vt())}).passthrough(),On=Xt.extend({description:Z(q()),arguments:Z(J(Dn)),icons:Z(J(Yt)),_meta:Z(Y({}).passthrough())}),kn=ln.extend({method:X(`prompts/list`)}),An=un.extend({prompts:J(On)}),jn=Mt.extend({method:X(`prompts/get`),params:jt.extend({name:q(),arguments:Z(Ct(q()))})}),Mn=Y({type:X(`text`),text:q(),_meta:Z(Y({}).passthrough())}).passthrough(),Nn=Y({type:X(`image`),data:pn,mimeType:q(),_meta:Z(Y({}).passthrough())}).passthrough(),Pn=Y({type:X(`audio`),data:pn,mimeType:q(),_meta:Z(Y({}).passthrough())}).passthrough(),Fn=Y({type:X(`resource`),resource:xt([fn,mn]),_meta:Z(Y({}).passthrough())}).passthrough(),In=hn.extend({type:X(`resource_link`)}),Ln=xt([Mn,Nn,Pn,In,Fn]),Rn=Y({role:wt([`user`,`assistant`]),content:Ln}).passthrough(),zn=Ft.extend({description:Z(q()),messages:J(Rn)}),Bn=Pt.extend({method:X(`notifications/prompts/list_changed`)}),Vn=Y({title:Z(q()),readOnlyHint:Z(vt()),destructiveHint:Z(vt()),idempotentHint:Z(vt()),openWorldHint:Z(vt())}).passthrough(),Hn=Xt.extend({description:Z(q()),inputSchema:Y({type:X(`object`),properties:Z(Y({}).passthrough()),required:Z(J(q()))}).passthrough(),outputSchema:Z(Y({type:X(`object`),properties:Z(Y({}).passthrough()),required:Z(J(q()))}).passthrough()),annotations:Z(Vn),icons:Z(J(Yt)),_meta:Z(Y({}).passthrough())}),Un=ln.extend({method:X(`tools/list`)}),Wn=un.extend({tools:J(Hn)}),Gn=Ft.extend({content:J(Ln).default([]),structuredContent:Y({}).passthrough().optional(),isError:Z(vt())});Gn.or(Ft.extend({toolResult:bt()}));const Kn=Mt.extend({method:X(`tools/call`),params:jt.extend({name:q(),arguments:Z(Ct(bt()))})}),qn=Pt.extend({method:X(`notifications/tools/list_changed`)}),Jn=wt([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Yn=Mt.extend({method:X(`logging/setLevel`),params:jt.extend({level:Jn})}),Xn=Pt.extend({method:X(`notifications/message`),params:Nt.extend({level:Jn,logger:Z(q()),data:bt()})}),Zn=Y({name:q().optional()}).passthrough(),Qn=Y({hints:Z(J(Zn)),costPriority:Z(_t().min(0).max(1)),speedPriority:Z(_t().min(0).max(1)),intelligencePriority:Z(_t().min(0).max(1))}).passthrough(),$n=Y({role:wt([`user`,`assistant`]),content:xt([Mn,Nn,Pn])}).passthrough(),er=Mt.extend({method:X(`sampling/createMessage`),params:jt.extend({messages:J($n),systemPrompt:Z(q()),includeContext:Z(wt([`none`,`thisServer`,`allServers`])),temperature:Z(_t()),maxTokens:_t().int(),stopSequences:Z(J(q())),metadata:Z(Y({}).passthrough()),modelPreferences:Z(Qn)})}),tr=Ft.extend({model:q(),stopReason:Z(wt([`endTurn`,`stopSequence`,`maxTokens`]).or(q())),role:wt([`user`,`assistant`]),content:St(`type`,[Mn,Nn,Pn])}),nr=Y({type:X(`boolean`),title:Z(q()),description:Z(q()),default:Z(vt())}).passthrough(),rr=Y({type:X(`string`),title:Z(q()),description:Z(q()),minLength:Z(_t()),maxLength:Z(_t()),format:Z(wt([`email`,`uri`,`date`,`date-time`]))}).passthrough(),ir=Y({type:wt([`number`,`integer`]),title:Z(q()),description:Z(q()),minimum:Z(_t()),maximum:Z(_t())}).passthrough(),ar=Y({type:X(`string`),title:Z(q()),description:Z(q()),enum:J(q()),enumNames:Z(J(q()))}).passthrough(),or=xt([nr,rr,ir,ar]),sr=Mt.extend({method:X(`elicitation/create`),params:jt.extend({message:q(),requestedSchema:Y({type:X(`object`),properties:Ct(q(),or),required:Z(J(q()))}).passthrough()})}),cr=Ft.extend({action:wt([`accept`,`decline`,`cancel`]),content:Z(Ct(q(),bt()))}),lr=Y({type:X(`ref/resource`),uri:q()}).passthrough(),ur=Y({type:X(`ref/prompt`),name:q()}).passthrough(),dr=Mt.extend({method:X(`completion/complete`),params:jt.extend({ref:xt([ur,lr]),argument:Y({name:q(),value:q()}).passthrough(),context:Z(Y({arguments:Z(Ct(q(),q()))}))})}),fr=Ft.extend({completion:Y({values:J(q()).max(100),total:Z(_t().int()),hasMore:Z(vt())}).passthrough()}),pr=Y({uri:q().startsWith(`file://`),name:Z(q()),_meta:Z(Y({}).passthrough())}).passthrough(),mr=Mt.extend({method:X(`roots/list`)}),hr=Ft.extend({roots:J(pr)}),gr=Pt.extend({method:X(`notifications/roots/list_changed`)});xt([on,$t,dr,Yn,jn,kn,_n,yn,xn,wn,Tn,Kn,Un]),xt([Jt,cn,rn,gr]),xt([qt,tr,cr,hr]),xt([on,er,sr,mr]),xt([Jt,cn,Xn,En,Cn,qn,Bn]),xt([qt,nn,fr,zn,An,vn,bn,Sn,Gn,Wn]);var _r=class extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}},vr=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},yr=class extends vr{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},br=class extends vr{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},xr=class extends vr{constructor(e,t,n,r={}){super(`HTTPServerError`,e,{feature:`http`,module:`server`,operation:`request`},{endpoint:t,statusCode:n,...r})}},Sr=class extends vr{constructor(e,t,n,r={}){super(`ProcessSpawnError`,e,{feature:`stdio`,module:`transport`,operation:`spawn`},{argCount:n?.length,command:t,...r})}},Cr=class extends vr{constructor(e,t,n,r={}){super(`ProxyConnectionError`,e,{feature:`connection`,module:`proxy`,operation:`connect`,transport:n||`unknown`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...r})}},wr=class extends vr{constructor(e,t,n=`unknown`,r={}){super(`ProxyServerError`,e,{feature:`server`,module:`proxy`,operation:n},{handler:t,...r})}},Tr=class extends vr{constructor(e,t=`unknown`,n=`unknown`,r={}){super(`TransportError`,e,{feature:t,module:`transport`,operation:n},r)}};const Er={APP_VERSION:`1.0.9`,NODE_ENV:`development`,SENTRY_DSN:null,SENTRY_ENABLED:!1},Dr=u.get,Or=Er.APP_VERSION,kr=e=>{let t={};if(e){let n=e.split(`,`);for(let e of n){let[n,...r]=e.split(`:`);n&&r.length>0&&(t[n.trim()]=r.join(`:`).trim())}}return t},Ar=e=>{try{let t=new URL(e),n=`/guard/evaluate/v1`;return t.pathname.includes(n)?(t.pathname=t.pathname.replace(n,`/access-control/authorize`),t.toString()):(console.warn(`[mcp-gateway] Warning: SCANNER_URL does not contain expected path "${n}". Access control URL derivation skipped. Current path: "${t.pathname}". Please set MCP_GATEWAY_ACCESS_CONTROL_URL explicitly.`),null)}catch(e){return console.warn(`[mcp-gateway] Warning: Failed to parse SCANNER_URL as valid URL: ${e instanceof Error?e.message:String(e)}. Please set MCP_GATEWAY_ACCESS_CONTROL_URL explicitly.`),null}},jr=t(),Mr=Dr(`NODE_ENV`).default(Er.NODE_ENV||`development`).asEnum([`development`,`production`,`staging`,`test`]),Nr=Dr(`MCP_GATEWAY_SENTRY_DSN`).default(Er.SENTRY_DSN||``).asString()||null,Pr=Dr(`MCP_GATEWAY_SENTRY_ENABLED`).default(String(Er.SENTRY_ENABLED??!1)).asBool(),Fr=Dr(`DEBUG`).default(`false`).asBool()||Dr(`MCP_GATEWAY_DEBUG`).default(`false`).asBool(),Ir=Dr(`MCP_GATEWAY_SCANNER_URL`).default(``).asString()||null,Lr=Dr(`MCP_GATEWAY_SCANNER_API_KEY`).default(``).asString()||void 0,Rr=(()=>{let e=Dr(`MCP_GATEWAY_SCANNER_HEADERS`).required(!1).asString();return e?kr(e):{}})(),zr=Dr(`MCP_GATEWAY_SCANNER_TIMEOUT_MS`).default(`20000`).asIntPositive(),Br=Dr(`MCP_GATEWAY_SCANNER_FAIL_OPEN`).default(`true`).asBool(),Vr=Dr(`MCP_GATEWAY_COMMAND`).default(`mcp-gateway`).asString(),Hr=Dr(`CLIENT_APP_NAME`).default(``).asString(),Ur=Dr(`MCP_GATEWAY_LOG_DIR`).default(a(c(),`.onyx`,`mcp-gateway`,`logs`)).asString(),Wr=(()=>Dr(`MCP_GATEWAY_ACCESS_CONTROL_URL`).default(``).asString()||(Ir?Ar(Ir):null))(),Gr=(()=>{let e=Dr(`MCP_GATEWAY_ACCESS_CONTROL_HEADERS`).required(!1).asString();return e?kr(e):{}})(),Kr=Dr(`MCP_GATEWAY_ACCESS_CONTROL_TIMEOUT_MS`).default(`3000`).asIntPositive(),qr={accessControl:{enabled:!!(Wr&&Lr),headers:Gr,timeoutMs:Kr,url:Wr},appVersion:Or,clientAppName:Hr,debug:Fr,environment:Mr,logDir:Ur,proxyCommand:Vr,scanner:{apiKey:Lr,enabled:!!Ir,failOpen:Br,headers:Rr,timeoutMs:zr,url:Ir},sentry:{debug:Fr&&Mr===`development`,dsn:Nr||void 0,enabled:Pr,environment:Mr,release:`mcp-gateway@${Or}`,tracesSampleRate:Mr===`production`?1:0}},Jr=qr.logDir,Yr=qr.debug?`debug`:`info`;let Xr=!1;try{n(Jr)||r(Jr,{recursive:!0}),Xr=!0}catch(e){let t=e instanceof Error?e.message:String(e),n=t.includes(`EACCES`)||t.includes(`permission denied`);console.error(`[mcp-gateway] WARNING: Failed to create log directory: ${Jr}`),console.error(`[mcp-gateway] Error: ${t}`),n&&(console.error(`[mcp-gateway] This appears to be a permission issue. Possible solutions:`),console.error(`[mcp-gateway] 1. Fix directory permissions: sudo chown -R $USER ~/.onyx`),console.error(`[mcp-gateway] 2. Use a different log directory: export MCP_GATEWAY_LOG_DIR=/tmp/mcp-gateway-logs`)),console.error(`[mcp-gateway] File logging will be disabled. The gateway will continue to function.`)}const Zr=o.format.combine(o.format.timestamp(),o.format.errors({stack:!0}),o.format.json());let Qr=null;const $r=[];if(Xr){let e=new s({datePattern:`YYYY-MM-DD`,filename:a(Jr,`mcp-gateway-%DATE%.log`),format:Zr,handleExceptions:!1,handleRejections:!1,level:Yr,maxFiles:10,maxSize:`10m`});$r.push(e)}const ei=o.createLogger({defaultMeta:{service:`mcp-gateway`,version:qr.appVersion},format:o.format.combine(o.format.errors({stack:!0}),o.format.metadata()),level:Yr,transports:$r}),ti=e=>{let[t,...n]=e;if(typeof t!=`string`)throw Error(`First argument must be a string message`);if(n.length>0&&n[0]&&typeof n[0]==`object`&&`proxyType`in n[0]){let e=n[0],r=n[1];return{message:t,meta:r,sessionData:e}}let r=n[0];return{message:t,meta:r,sessionData:Qr||void 0}},Q={debug:(...e)=>{let{message:t,meta:n,sessionData:r}=ti(e);ei.debug(t,{sessionData:r,...n})},error:(...e)=>{let{message:t,meta:n,sessionData:r}=ti(e);ei.error(t,{sessionData:r,...n})},getSessionData:()=>Qr,info:(...e)=>{let{message:t,meta:n,sessionData:r}=ti(e);ei.info(t,{sessionData:r,...n})},setSessionData:e=>{Qr=e,Q.debug(`Session data set for logger`,e)},warn:(...e)=>{let{message:t,meta:n,sessionData:r}=ti(e);ei.warn(t,{sessionData:r,...n})}};Q.info(`MCP Gateway logger initialized`,{debug:qr.debug,fileLoggingEnabled:Xr,logDir:Jr,logLevel:Yr});let ni={"proxy.version":qr.appVersion};function ri(e,t=`default`,n=`info`,r){try{if(!qr.sentry.enabled){Q.debug(`Breadcrumb: [${t}] ${e}`,r);return}d.addBreadcrumb({category:t,data:r?si(r):void 0,level:n,message:e,timestamp:Date.now()/1e3})}catch(e){Q.warn(`Failed to add breadcrumb to Sentry`,{error:e})}}function ii(e){ni={...ni,...e}}function ai(e,t,n){try{let r=e instanceof vr?{...e.tags,...n}:n,i=e instanceof vr?{...e.extra,...t}:t;if(!qr.sentry.enabled){let t=e instanceof Error?e.message:String(e);Q.error(`Exception captured: ${t}`,{error:e instanceof Error?e.stack||e.message:e,extra:i,tags:r});return}let a=e instanceof Error?e.message:String(e);Q.error(`Sending exception to Sentry: ${a}`,{error:e instanceof Error?e.stack||e.message:e,extra:i,tags:r}),d.withScope(t=>{r&&Object.entries(r).forEach(([e,n])=>{let r=e.startsWith(`mcp.gateway.`)?e:`mcp.gateway.${e}`;t.setTag(r,n)}),i&&Object.entries(si(i)).forEach(([e,n])=>{t.setExtra(e,n)}),t.setLevel(`error`),d.captureException(e)})}catch(e){Q.warn(`Failed to capture exception to Sentry`,{sentryError:e instanceof Error?e.message:e})}}function oi(){try{if(!qr.sentry.enabled){Q.debug(`Sentry disabled (no DSN provided or in development mode)`);return}d.init({beforeSend(e){return e.tags={...e.tags,...ni},e.extra&&=si(e.extra),e.contexts?.runtime?.name&&(e.contexts.runtime.name=`node`),e},beforeSendTransaction(e){return e.tags={...e.tags,...ni},e},debug:qr.sentry.debug,dsn:qr.sentry.dsn,environment:qr.sentry.environment,release:qr.sentry.release,tracesSampleRate:qr.sentry.tracesSampleRate}),Q.debug(`Sentry initialized`,{dsn:qr.sentry.dsn?`***configured***`:`not configured`,environment:qr.sentry.environment,release:qr.sentry.release})}catch(e){Q.warn(`Failed to initialize Sentry, continuing without error tracking`,{error:e})}}function si(e){let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.toLowerCase();if(r.includes(`password`)||r.includes(`token`)||r.includes(`key`)||r.includes(`secret`)||r.includes(`auth`)||r===`env`||r===`environment`){t[e]=`[FILTERED]`;return}if(typeof n==`string`&&(r.includes(`url`)||n.startsWith(`http`)))try{let r=new URL(n);t[e]=`${r.protocol}//${r.host}${r.pathname}`}catch{t[e]=n}else t[e]=n}),t}function ci(){return a(c(),`.claude.json`)}function li(){try{return l()}catch{return`unknown-device`}}async function ui(e){try{return(await f()).find(t=>t.pid===e)?.name||`unknown`}catch{return`unknown`}}function di(){try{let e=fi();return e?e.oauthAccount.emailAddress:void 0}catch{return}}function fi(){try{let e=ci();if(!n(e))return null;let t=i(e,`utf-8`);return JSON.parse(t)}catch{return null}}const pi=async()=>{let e=process.pid,t=process.ppid;try{let n=li(),r=di(),i=await ui(t);return{clientAppName:Hr||`unknown`,deviceName:n,email:r,parentProcessId:t,parentProcessName:i,processId:e}}catch{return{clientAppName:Hr||`unknown`,deviceName:`unknown-device`,email:void 0,parentProcessId:t,parentProcessName:`unknown`,processId:e}}};function mi(e){let t=p(JSON.stringify(e));return Buffer.from(t).toString(`base64url`)}var hi=class{clientAppName;clientInfoBase64;sessionData;get scannerConfig(){return{apiKey:this.config.scanApiKey,enabled:this.config.scanEnabled,failOpen:this.config.scanFailOpen,headers:this.config.scanHeaders,timeoutMs:this.config.scanTimeoutMs,url:this.config.scanUrl}}config;constructor(e,t){this.config=e,this.sessionData=t,this.clientAppName=t.clientAppName||``,this.clientInfoBase64=this.getClientInfoBase64()}async evaluate(e){let t={action:`allow`};if(this.isScanEnabled())try{if(t=await this.scan({data:e.data,id:e.id,method:e.method,originalRequestId:e.originalRequestId,timestamp:e.timestamp,type:e.type}),Q.info(`Scan result`,{action:t.action,id:e.id,method:e.method,originalRequestId:e.originalRequestId}),t.action===`block`)return Q.warn(`Request blocked by security policy`),t}catch(t){if(Q.error(`Scanning failed`,{error:t}),ai(t instanceof Error?t:Error(String(t)),{method:e.method,requestType:e.type,scannerUrl:this.config.scanUrl},{feature:`traffic-scanner`,module:`evaluator`,operation:`scan`}),!this.config.scanFailOpen)return Q.warn(`Scanning service unavailable, blocking traffic (fail-closed)`),{action:`block`};Q.warn(`Scanning service unavailable, allowing traffic (fail-open)`)}return t}isEnabled(){return this.isScanEnabled()}isScanEnabled(){return this.config.scanEnabled&&!!this.config.scanUrl}async scan(e){if(!this.isScanEnabled())return{action:`allow`};let t={data:e.data,id:e.id,metadata:this.sessionData,method:e.method,originalRequestId:e.originalRequestId,type:e.type};Q.info(`Scanning traffic`,{id:e.id,method:e.method,originalRequestId:e.originalRequestId,type:e.type});let n=await this.sendScanRequest(t);return Q.info(`Scan result`,{action:n.action,blockReason:n.block_reason,hasModifiedData:!!n.modified_data,id:e.id,originalRequestId:e.originalRequestId}),n}updateConfig(e){this.config={...this.config,...e}}getClientInfoBase64(){return mi(this.sessionData)}async sendScanRequest(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.scanTimeoutMs);try{let n=`${this.config.scanUrl}/${this.config.scanApiKey}/mcp/${this.clientInfoBase64}`,r={data:e.data,id:e.id,metadata:e.metadata,method:e.method,sessionId:jr,...e.originalRequestId&&{original_request_id:String(e.originalRequestId)},type:e.type},i=await fetch(n,{body:JSON.stringify(r),headers:{"Content-Type":`application/json`,...this.config.scanHeaders},method:`POST`,signal:t.signal});if(!i.ok)throw Error(`Sanitization service returned ${i.status}: ${i.statusText}`);let a=await i.json();if(!a.action||![`allow`,`block`,`modify`].includes(a.action))throw Error(`Invalid scan response format: action="${a.action}"`);return a}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Scan request timed out after ${this.config.scanTimeoutMs}ms`):e}finally{clearTimeout(n)}}};let gi=null;const _i=async e=>{let t=await pi(),n=e.cliArgs.proxyType,r={...t,proxyType:n,remoteCliArgs:n===`remote`?e.cliArgs:void 0,stdioCliArgs:n===`stdio`?e.cliArgs:void 0};return Q.setSessionData(r),gi=new hi(e,r),gi},vi=()=>gi,yi=e=>e.length>1&&e[1]&&typeof e[1]==`object`&&`requestId`in e[1]?e[1].requestId:void 0,bi=(e,n,r,i)=>async(...a)=>{let o=vi(),s=e,c=a[0],l=t(),u=yi(a)?.toString();c&&typeof c==`object`&&`method`in c&&typeof c.method==`string`&&(s=c.method);let d=async(e,t,n)=>{try{if(!o?.isEnabled()&&!o?.isScanEnabled())return;let r;try{r=await o.evaluate({data:t,id:l,method:s,originalRequestId:u,timestamp:new Date().toISOString(),type:e})}catch(t){if(Q.error(`${e} evaluation failed, applying fail-safe`,{error:t}),o?.isScanEnabled()&&!o.scannerConfig?.failOpen)throw Error(`Security scanning service unavailable`);return}if(Q.info(`${e} scan result`,{action:r.action,id:l,method:s,...e===`request`&&{originalRequestId:u}}),r.action===`block`||r.action===`modify`){let t=r.action===`block`?`blocked`:`modified`,i=r.action===`block`&&e===`request`?`warn`:`log`;if(r.modified_data){if(r.action===`block`){let n=`${e} ${t} by security policy${e===`request`?`, returning error response`:``}`;return i===`warn`?Q.warn(n):Q.info(n),r.modified_data}if(n){let a=`${e} ${t} by security policy`;i===`warn`?Q.warn(a):Q.info(a),n(r.modified_data);return}return r.modified_data}Q.warn(`${r.action} action without modified_data, allowing original ${e}`)}return}catch(t){if(Q.error(`Unexpected error during ${e} processing`,{error:t}),ai(t),e===`request`&&t instanceof Error&&t.message===`Security scanning service unavailable`)throw t;return}},f;try{f=await d(`request`,c,e=>{a[0]=e})}catch(t){if(t instanceof Error&&t.message===`Security scanning service unavailable`){let r=new wr(`Security scanning unavailable (fail-closed)`,e,n,{errorMessage:t.message});throw ai(r),t}Q.error(`Unexpected error during request processing, continuing`,{error:t}),ai(t)}if(f!==void 0)return f;if(i&&!await i.isAllowed()){let t=i.getBlockReason();throw Q.warn(`MCP server blocked by access control`,{handlerName:e,operation:n,reason:t}),new yr(t,`policy_block`)}try{let e=await r(...a);try{if(e){let t=await d(`response`,e);if(t!==void 0)return t}}catch(e){Q.error(`Error during response processing, returning original result`,{error:e}),ai(e)}return e}catch(t){if(t instanceof yr)throw Q.info(`Request blocked by access control`,{error:t.message,handlerName:e,operation:n,reason:t.reason}),t;try{await d(`error`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}catch(e){Q.warn(`Failed to evaluate error`,{evalError:e})}let r=new wr(`Handler error: ${t}`,e,n,{argsCount:a.length,errorMessage:t instanceof Error?t.message:String(t)});throw ai(r),t}},xi=async({authorizer:e,client:t,server:n,serverCapabilities:r})=>{r?.logging&&(n.setNotificationHandler(Xn,bi(`notifications/message`,`server-to-client`,async e=>t.notification(e),e)),t.setNotificationHandler(Xn,bi(`notifications/message`,`client-to-server`,async e=>n.notification(e),e))),r?.prompts&&(n.setRequestHandler(jn,bi(`prompts/get`,`get`,async e=>t.getPrompt(e.params),e)),n.setRequestHandler(kn,bi(`prompts/list`,`list`,async e=>t.listPrompts(e.params),e))),r?.resources&&(n.setRequestHandler(_n,bi(`resources/list`,`list`,async e=>t.listResources(e.params),e)),n.setRequestHandler(yn,bi(`resources/templates/list`,`list`,async e=>t.listResourceTemplates(e.params),e)),n.setRequestHandler(xn,bi(`resources/read`,`read`,async e=>t.readResource(e.params),e)),r?.resources.subscribe&&(n.setNotificationHandler(En,bi(`notifications/resources/updated`,`notify`,async e=>t.notification(e),e)),n.setRequestHandler(wn,bi(`resources/subscribe`,`subscribe`,async e=>t.subscribeResource(e.params),e)),n.setRequestHandler(Tn,bi(`resources/unsubscribe`,`unsubscribe`,async e=>t.unsubscribeResource(e.params),e)))),r?.tools&&(n.setRequestHandler(Kn,bi(`tools/call`,`call`,async e=>t.callTool(e.params),e)),n.setRequestHandler(Un,bi(`tools/list`,`list`,async e=>t.listTools(e.params),e))),n.setRequestHandler(dr,bi(`completion/complete`,`complete`,async e=>t.complete(e.params),e))};var Si=w(((exports,t)=>{t.exports=o,t.exports.format=s,t.exports.parse=c;var n=/\B(?=(\d{3})+(?!\d))/g,r=/(?:\.0*|(\.[^0]+)0+)$/,i={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:1024**4,pb:1024**5},a=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function o(e,t){return typeof e==`string`?c(e):typeof e==`number`?s(e,t):null}function s(e,t){if(!Number.isFinite(e))return null;var a=Math.abs(e),o=t&&t.thousandsSeparator||``,s=t&&t.unitSeparator||``,c=t&&t.decimalPlaces!==void 0?t.decimalPlaces:2,l=!!(t&&t.fixedDecimals),u=t&&t.unit||``;(!u||!i[u.toLowerCase()])&&(u=a>=i.pb?`PB`:a>=i.tb?`TB`:a>=i.gb?`GB`:a>=i.mb?`MB`:a>=i.kb?`KB`:`B`);var d=(e/i[u.toLowerCase()]).toFixed(c);return l||(d=d.replace(r,`$1`)),o&&(d=d.split(`.`).map(function(e,t){return t===0?e.replace(n,o):e}).join(`.`)),d+s+u}function c(e){if(typeof e==`number`&&!isNaN(e))return e;if(typeof e!=`string`)return null;var t=a.exec(e),n,r=`b`;return t?(n=parseFloat(t[1]),r=t[4].toLowerCase()):(n=parseInt(e,10),r=`b`),isNaN(n)?null:Math.floor(i[r]*n)}})),Ci=w(((exports,t)=>{
1
+ import{createRequire as e}from"node:module";import{randomUUID as t}from"crypto";import{existsSync as n,mkdirSync as r,readFileSync as i}from"node:fs";import{join as a}from"node:path";import o from"winston";import s from"winston-daily-rotate-file";import{homedir as c,hostname as l}from"node:os";import u from"env-var";import"dotenv/config";import*as d from"@sentry/node";import f from"ps-list";import{deflateSync as p}from"node:zlib";import{randomUUID as m}from"node:crypto";import{URL as h}from"url";import g from"node:http";import _ from"node:process";var v=Object.create,y=Object.defineProperty,b=Object.getOwnPropertyDescriptor,x=Object.getOwnPropertyNames,S=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty,w=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),T=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=x(t),a=0,o=i.length,s;a<o;a++)s=i[a],!C.call(e,s)&&s!==n&&y(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=b(t,s))||r.enumerable});return e},E=(e,t,n)=>(n=e==null?{}:v(S(e)),T(t||!e||!e.__esModule?y(n,`default`,{value:e,enumerable:!0}):n,e)),D=e(import.meta.url),O=class{events=new Map;async replayEventsAfter(e,{send:t}){if(!e||!this.events.has(e))return``;let n=this.getStreamIdFromEventId(e);if(!n)return``;let r=!1,i=[...this.events.entries()].sort((e,t)=>e[0].localeCompare(t[0]));for(let[a,{message:o,streamId:s}]of i){if(s!==n)continue;if(a===e){r=!0;continue}r&&await t(a,o)}return n}async storeEvent(e,t){let n=this.generateEventId(e);return this.events.set(n,{message:t,streamId:e}),n}generateEventId(e){return`${e}_${Date.now()}_${Math.random().toString(36).substring(2,10)}`}getStreamIdFromEventId(e){let t=e.split(`_`);return t.length>0?t[0]:``}},k;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(k||={});var A;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(A||={});const j=k.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),M=e=>{switch(typeof e){case`undefined`:return j.undefined;case`string`:return j.string;case`number`:return Number.isNaN(e)?j.nan:j.number;case`boolean`:return j.boolean;case`function`:return j.function;case`bigint`:return j.bigint;case`symbol`:return j.symbol;case`object`:return Array.isArray(e)?j.array:e===null?j.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?j.promise:typeof Map<`u`&&e instanceof Map?j.map:typeof Set<`u`&&e instanceof Set?j.set:typeof Date<`u`&&e instanceof Date?j.date:j.object;default:return j.unknown}},N=k.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var P=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,k.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};P.create=e=>new P(e);var F=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===j.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,k.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${k.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${k.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${k.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:k.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case N.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,k.assertNever(e)}return{message:n}};let ee=F;function te(){return ee}const I=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function L(e,t){let n=te(),r=I({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===F?void 0:F].filter(e=>!!e)});e.common.issues.push(r)}var R=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return z;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return z;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const z=Object.freeze({status:`aborted`}),ne=e=>({status:`dirty`,value:e}),B=e=>({status:`valid`,value:e}),re=e=>e.status===`aborted`,V=e=>e.status===`dirty`,ie=e=>e.status===`valid`,ae=e=>typeof Promise<`u`&&e instanceof Promise;var H;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(H||={});var U=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}};const oe=(e,t)=>{if(ie(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new P(e.common.issues),this._error}}};function W(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var G=class{get description(){return this._def.description}_getType(e){return M(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:M(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new R,ctx:{common:e.parent.common,data:e.data,parsedType:M(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ae(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:M(e)},r=this._parseSync({data:e,path:n.path,parent:n});return oe(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:M(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ie(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ie(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:M(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(ae(r)?r:Promise.resolve(r));return oe(n,i)}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:N.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ct({schema:this,typeName:K.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:e=>this[`~validate`](e)}}optional(){return lt.create(this,this._def)}nullable(){return ut.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ue.create(this)}promise(){return st.create(this,this._def)}or(e){return Ke.create([this,e],this._def)}and(e){return Xe.create(this,e,this._def)}transform(e){return new ct({...W(this._def),schema:this,typeName:K.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new dt({...W(this._def),innerType:this,defaultValue:t,typeName:K.ZodDefault})}brand(){return new mt({typeName:K.ZodBranded,type:this,...W(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ft({...W(this._def),innerType:this,catchValue:t,typeName:K.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ht.create(this,e)}readonly(){return gt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const se=/^c[^\s-]{8,}$/i,ce=/^[0-9a-z]+$/,le=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ue=/^[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,de=/^[a-z0-9_-]{21}$/i,fe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pe=/^[-+]?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)?)??$/,me=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let he;const ge=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_e=/^(?:(?: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])$/,ve=/^(([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]))$/,ye=/^(([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])$/,be=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Se=`((\\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])))`,Ce=RegExp(`^${Se}$`);function we(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Te(e){return RegExp(`^${we(e)}$`)}function Ee(e){let t=`${Se}T${we(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function De(e,t){return!!((t===`v4`||!t)&&ge.test(e)||(t===`v6`||!t)&&ve.test(e))}function Oe(e,t){if(!fe.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function ke(e,t){return!!((t===`v4`||!t)&&_e.test(e)||(t===`v6`||!t)&&ye.test(e))}var Ae=class e extends G{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.string,received:t.parsedType}),z}let t=new R,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),L(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),L(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?L(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&L(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)me.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)he||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),he.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ue.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)de.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)se.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ce.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)le.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),L(n,{validation:`url`,code:N.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`regex`,code:N.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Ee(r).test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Ce.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Te(r).test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?pe.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?De(e.data,r.version)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Oe(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?ke(e.data,r.version)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?be.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?xe.test(e.data)||(n=this._getOrReturnCtx(e,n),L(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):k.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...H.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...H.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...H.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...H.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...H.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...H.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...H.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...H.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...H.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...H.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...H.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...H.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...H.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...H.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...H.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...H.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...H.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...H.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...H.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...H.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...H.errToObj(t)})}nonempty(e){return this.min(1,H.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ae.create=e=>new Ae({checks:[],typeName:K.ZodString,coerce:e?.coerce??!1,...W(e)});function je(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r,a=Number.parseInt(e.toFixed(i).replace(`.`,``)),o=Number.parseInt(t.toFixed(i).replace(`.`,``));return a%o/10**i}var Me=class e extends G{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==j.number){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.number,received:t.parsedType}),z}let t,n=new R;for(let r of this._def.checks)r.kind===`int`?k.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),L(t,{code:N.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?je(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),L(t,{code:N.not_finite,message:r.message}),n.dirty()):k.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,H.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,H.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,H.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,H.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:H.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:H.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:H.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:H.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:H.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:H.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&k.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Me.create=e=>new Me({checks:[],typeName:K.ZodNumber,coerce:e?.coerce||!1,...W(e)});var Ne=class e extends G{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==j.bigint)return this._getInvalidInput(e);let t,n=new R;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),L(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):k.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.bigint,received:t.parsedType}),z}gte(e,t){return this.setLimit(`min`,e,!0,H.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,H.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,H.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,H.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:H.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:H.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ne.create=e=>new Ne({checks:[],typeName:K.ZodBigInt,coerce:e?.coerce??!1,...W(e)});var Pe=class extends G{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.boolean,received:t.parsedType}),z}return B(e.data)}};Pe.create=e=>new Pe({typeName:K.ZodBoolean,coerce:e?.coerce||!1,...W(e)});var Fe=class e extends G{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.date,received:t.parsedType}),z}if(Number.isNaN(e.data.getTime())){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_date}),z}let t=new R,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),L(n,{code:N.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),L(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):k.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:H.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:H.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Fe.create=e=>new Fe({checks:[],coerce:e?.coerce||!1,typeName:K.ZodDate,...W(e)});var Ie=class extends G{_parse(e){if(this._getType(e)!==j.symbol){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.symbol,received:t.parsedType}),z}return B(e.data)}};Ie.create=e=>new Ie({typeName:K.ZodSymbol,...W(e)});var Le=class extends G{_parse(e){if(this._getType(e)!==j.undefined){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.undefined,received:t.parsedType}),z}return B(e.data)}};Le.create=e=>new Le({typeName:K.ZodUndefined,...W(e)});var Re=class extends G{_parse(e){if(this._getType(e)!==j.null){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.null,received:t.parsedType}),z}return B(e.data)}};Re.create=e=>new Re({typeName:K.ZodNull,...W(e)});var ze=class extends G{constructor(){super(...arguments),this._any=!0}_parse(e){return B(e.data)}};ze.create=e=>new ze({typeName:K.ZodAny,...W(e)});var Be=class extends G{constructor(){super(...arguments),this._unknown=!0}_parse(e){return B(e.data)}};Be.create=e=>new Be({typeName:K.ZodUnknown,...W(e)});var Ve=class extends G{_parse(e){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.never,received:t.parsedType}),z}};Ve.create=e=>new Ve({typeName:K.ZodNever,...W(e)});var He=class extends G{_parse(e){if(this._getType(e)!==j.undefined){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.void,received:t.parsedType}),z}return B(e.data)}};He.create=e=>new He({typeName:K.ZodVoid,...W(e)});var Ue=class e extends G{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==j.array)return L(t,{code:N.invalid_type,expected:j.array,received:t.parsedType}),z;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(L(t,{code:e?N.too_big:N.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(L(t,{code:N.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(L(t,{code:N.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new U(t,e,t.path,n)))).then(e=>R.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new U(t,e,t.path,n)));return R.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:H.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:H.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:H.toString(n)}})}nonempty(e){return this.min(1,e)}};Ue.create=(e,t)=>new Ue({type:e,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...W(t)});function We(e){if(e instanceof Ge){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=lt.create(We(r))}return new Ge({...e._def,shape:()=>t})}else if(e instanceof Ue)return new Ue({...e._def,type:We(e.element)});else if(e instanceof lt)return lt.create(We(e.unwrap()));else if(e instanceof ut)return ut.create(We(e.unwrap()));else if(e instanceof Ze)return Ze.create(e.items.map(e=>We(e)));else return e}var Ge=class e extends G{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=k.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==j.object){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.object,received:t.parsedType}),z}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ve&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new U(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Ve){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(L(n,{code:N.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new U(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>R.mergeObjectSync(t,e)):R.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return H.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:H.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:K.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of k.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of k.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return We(this)}partial(t){let n={};for(let e of k.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of k.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof lt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return it(k.objectKeys(this.shape))}};Ge.create=(e,t)=>new Ge({shape:()=>e,unknownKeys:`strip`,catchall:Ve.create(),typeName:K.ZodObject,...W(t)}),Ge.strictCreate=(e,t)=>new Ge({shape:()=>e,unknownKeys:`strict`,catchall:Ve.create(),typeName:K.ZodObject,...W(t)}),Ge.lazycreate=(e,t)=>new Ge({shape:e,unknownKeys:`strip`,catchall:Ve.create(),typeName:K.ZodObject,...W(t)});var Ke=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new P(e.ctx.common.issues));return L(t,{code:N.invalid_union,unionErrors:n}),z}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new P(e));return L(t,{code:N.invalid_union,unionErrors:i}),z}}get options(){return this._def.options}};Ke.create=(e,t)=>new Ke({options:e,typeName:K.ZodUnion,...W(t)});const qe=e=>e instanceof nt?qe(e.schema):e instanceof ct?qe(e.innerType()):e instanceof rt?[e.value]:e instanceof at?e.options:e instanceof ot?k.objectValues(e.enum):e instanceof dt?qe(e._def.innerType):e instanceof Le?[void 0]:e instanceof Re?[null]:e instanceof lt?[void 0,...qe(e.unwrap())]:e instanceof ut?[null,...qe(e.unwrap())]:e instanceof mt||e instanceof gt?qe(e.unwrap()):e instanceof ft?qe(e._def.innerType):[];var Je=class e extends G{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.object)return L(t,{code:N.invalid_type,expected:j.object,received:t.parsedType}),z;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(L(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=qe(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:K.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...W(r)})}};function Ye(e,t){let n=M(e),r=M(t);if(e===t)return{valid:!0,data:e};if(n===j.object&&r===j.object){let n=k.objectKeys(t),r=k.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Ye(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===j.array&&r===j.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Ye(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===j.date&&r===j.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Xe=class extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(re(e)||re(r))return z;let i=Ye(e.value,r.value);return i.valid?((V(e)||V(r))&&t.dirty(),{status:t.value,value:i.data}):(L(n,{code:N.invalid_intersection_types}),z)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Xe.create=(e,t,n)=>new Xe({left:e,right:t,typeName:K.ZodIntersection,...W(n)});var Ze=class e extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.array)return L(n,{code:N.invalid_type,expected:j.array,received:n.parsedType}),z;if(n.data.length<this._def.items.length)return L(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),z;!this._def.rest&&n.data.length>this._def.items.length&&(L(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new U(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>R.mergeArray(t,e)):R.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ze.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Ze({items:e,typeName:K.ZodTuple,rest:null,...W(t)})};var Qe=class e extends G{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.object)return L(n,{code:N.invalid_type,expected:j.object,received:n.parsedType}),z;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new U(n,e,n.path,e)),value:a._parse(new U(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?R.mergeObjectAsync(t,r):R.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof G?new e({keyType:t,valueType:n,typeName:K.ZodRecord,...W(r)}):new e({keyType:Ae.create(),valueType:t,typeName:K.ZodRecord,...W(n)})}},$e=class extends G{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.map)return L(n,{code:N.invalid_type,expected:j.map,received:n.parsedType}),z;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new U(n,e,n.path,[a,`key`])),value:i._parse(new U(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return z;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return z;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};$e.create=(e,t,n)=>new $e({valueType:t,keyType:e,typeName:K.ZodMap,...W(n)});var et=class e extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.set)return L(n,{code:N.invalid_type,expected:j.set,received:n.parsedType}),z;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(L(n,{code:N.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(L(n,{code:N.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return z;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new U(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:H.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:H.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};et.create=(e,t)=>new et({valueType:e,minSize:null,maxSize:null,typeName:K.ZodSet,...W(t)});var tt=class e extends G{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.function)return L(t,{code:N.invalid_type,expected:j.function,received:t.parsedType}),z;function n(e,n){return I({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,te(),F].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return I({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,te(),F].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof st){let e=this;return B(async function(...t){let o=new P([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return B(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new P([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new P([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ze.create(t).rest(Be.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Ze.create([]).rest(Be.create()),returns:n||Be.create(),typeName:K.ZodFunction,...W(r)})}},nt=class extends G{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};nt.create=(e,t)=>new nt({getter:e,typeName:K.ZodLazy,...W(t)});var rt=class extends G{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return L(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),z}return{status:`valid`,value:e.data}}get value(){return this._def.value}};rt.create=(e,t)=>new rt({value:e,typeName:K.ZodLiteral,...W(t)});function it(e,t){return new at({values:e,typeName:K.ZodEnum,...W(t)})}var at=class e extends G{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return L(t,{expected:k.joinValues(n),received:t.parsedType,code:N.invalid_type}),z}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return L(t,{received:t.data,code:N.invalid_enum_value,options:n}),z}return B(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};at.create=it;var ot=class extends G{_parse(e){let t=k.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==j.string&&n.parsedType!==j.number){let e=k.objectValues(t);return L(n,{expected:k.joinValues(e),received:n.parsedType,code:N.invalid_type}),z}if(this._cache||=new Set(k.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=k.objectValues(t);return L(n,{received:n.data,code:N.invalid_enum_value,options:e}),z}return B(e.data)}get enum(){return this._def.values}};ot.create=(e,t)=>new ot({values:e,typeName:K.ZodNativeEnum,...W(t)});var st=class extends G{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.promise&&t.common.async===!1)return L(t,{code:N.invalid_type,expected:j.promise,received:t.parsedType}),z;let n=t.parsedType===j.promise?t.data:Promise.resolve(t.data);return B(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};st.create=(e,t)=>new st({type:e,typeName:K.ZodPromise,...W(t)});var ct=class extends G{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{L(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return z;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?z:r.status===`dirty`||t.value===`dirty`?ne(r.value):r});{if(t.value===`aborted`)return z;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?z:r.status===`dirty`||t.value===`dirty`?ne(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?z:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?z:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ie(e))return z;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>ie(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):z);k.assertNever(r)}};ct.create=(e,t,n)=>new ct({schema:e,typeName:K.ZodEffects,effect:t,...W(n)}),ct.createWithPreprocess=(e,t,n)=>new ct({schema:t,effect:{type:`preprocess`,transform:e},typeName:K.ZodEffects,...W(n)});var lt=class extends G{_parse(e){return this._getType(e)===j.undefined?B(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lt.create=(e,t)=>new lt({innerType:e,typeName:K.ZodOptional,...W(t)});var ut=class extends G{_parse(e){return this._getType(e)===j.null?B(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ut.create=(e,t)=>new ut({innerType:e,typeName:K.ZodNullable,...W(t)});var dt=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===j.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};dt.create=(e,t)=>new dt({innerType:e,typeName:K.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...W(t)});var ft=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ae(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new P(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new P(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ft.create=(e,t)=>new ft({innerType:e,typeName:K.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...W(t)});var pt=class extends G{_parse(e){if(this._getType(e)!==j.nan){let t=this._getOrReturnCtx(e);return L(t,{code:N.invalid_type,expected:j.nan,received:t.parsedType}),z}return{status:`valid`,value:e.data}}};pt.create=e=>new pt({typeName:K.ZodNaN,...W(e)});var mt=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ht=class e extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?z:e.status===`dirty`?(t.dirty(),ne(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?z:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:K.ZodPipeline})}},gt=class extends G{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ie(e)&&(e.value=Object.freeze(e.value)),e);return ae(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};gt.create=(e,t)=>new gt({innerType:e,typeName:K.ZodReadonly,...W(t)}),Ge.lazycreate;var K;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(K||={});const q=Ae.create,_t=Me.create;pt.create,Ne.create;const vt=Pe.create;Fe.create,Ie.create,Le.create,Re.create;const yt=ze.create,bt=Be.create;Ve.create,He.create;const J=Ue.create,Y=Ge.create;Ge.strictCreate;const xt=Ke.create,St=Je.create;Xe.create,Ze.create;const Ct=Qe.create;$e.create,et.create,tt.create,nt.create;const X=rt.create,wt=at.create;ot.create,st.create,ct.create;const Z=lt.create;ut.create,ct.createWithPreprocess,ht.create;const Tt=z,Et=`2025-06-18`,Dt=[Et,`2025-03-26`,`2024-11-05`,`2024-10-07`],Ot=xt([q(),_t().int()]),kt=q(),At=Y({progressToken:Z(Ot)}).passthrough(),jt=Y({_meta:Z(At)}).passthrough(),Mt=Y({method:q(),params:Z(jt)}),Nt=Y({_meta:Z(Y({}).passthrough())}).passthrough(),Pt=Y({method:q(),params:Z(Nt)}),Ft=Y({_meta:Z(Y({}).passthrough())}).passthrough(),It=xt([q(),_t().int()]),Lt=Y({jsonrpc:X(`2.0`),id:It}).merge(Mt).strict(),Rt=e=>Lt.safeParse(e).success,zt=Y({jsonrpc:X(`2.0`)}).merge(Pt).strict(),Bt=e=>zt.safeParse(e).success,Vt=Y({jsonrpc:X(`2.0`),id:It,result:Ft}).strict(),Ht=e=>Vt.safeParse(e).success;var Ut;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`})(Ut||={});const Wt=Y({jsonrpc:X(`2.0`),id:It,error:Y({code:_t().int(),message:q(),data:Z(bt())})}).strict(),Gt=e=>Wt.safeParse(e).success,Kt=xt([Lt,zt,Vt,Wt]),qt=Ft.strict(),Jt=Pt.extend({method:X(`notifications/cancelled`),params:Nt.extend({requestId:It,reason:q().optional()})}),Yt=Y({src:q(),mimeType:Z(q()),sizes:Z(q())}).passthrough(),Xt=Y({name:q(),title:Z(q())}).passthrough(),Zt=Xt.extend({version:q(),websiteUrl:Z(q()),icons:Z(J(Yt))}),Qt=Y({experimental:Z(Y({}).passthrough()),sampling:Z(Y({}).passthrough()),elicitation:Z(Y({}).passthrough()),roots:Z(Y({listChanged:Z(vt())}).passthrough())}).passthrough(),$t=Mt.extend({method:X(`initialize`),params:jt.extend({protocolVersion:q(),capabilities:Qt,clientInfo:Zt})}),en=e=>$t.safeParse(e).success,tn=Y({experimental:Z(Y({}).passthrough()),logging:Z(Y({}).passthrough()),completions:Z(Y({}).passthrough()),prompts:Z(Y({listChanged:Z(vt())}).passthrough()),resources:Z(Y({subscribe:Z(vt()),listChanged:Z(vt())}).passthrough()),tools:Z(Y({listChanged:Z(vt())}).passthrough())}).passthrough(),nn=Ft.extend({protocolVersion:q(),capabilities:tn,serverInfo:Zt,instructions:Z(q())}),rn=Pt.extend({method:X(`notifications/initialized`)}),an=e=>rn.safeParse(e).success,on=Mt.extend({method:X(`ping`)}),sn=Y({progress:_t(),total:Z(_t()),message:Z(q())}).passthrough(),cn=Pt.extend({method:X(`notifications/progress`),params:Nt.merge(sn).extend({progressToken:Ot})}),ln=Mt.extend({params:jt.extend({cursor:Z(kt)}).optional()}),un=Ft.extend({nextCursor:Z(kt)}),dn=Y({uri:q(),mimeType:Z(q()),_meta:Z(Y({}).passthrough())}).passthrough(),fn=dn.extend({text:q()}),pn=q().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),mn=dn.extend({blob:pn}),hn=Xt.extend({uri:q(),description:Z(q()),mimeType:Z(q()),icons:Z(J(Yt)),_meta:Z(Y({}).passthrough())}),gn=Xt.extend({uriTemplate:q(),description:Z(q()),mimeType:Z(q()),_meta:Z(Y({}).passthrough())}),_n=ln.extend({method:X(`resources/list`)}),vn=un.extend({resources:J(hn)}),yn=ln.extend({method:X(`resources/templates/list`)}),bn=un.extend({resourceTemplates:J(gn)}),xn=Mt.extend({method:X(`resources/read`),params:jt.extend({uri:q()})}),Sn=Ft.extend({contents:J(xt([fn,mn]))}),Cn=Pt.extend({method:X(`notifications/resources/list_changed`)}),wn=Mt.extend({method:X(`resources/subscribe`),params:jt.extend({uri:q()})}),Tn=Mt.extend({method:X(`resources/unsubscribe`),params:jt.extend({uri:q()})}),En=Pt.extend({method:X(`notifications/resources/updated`),params:Nt.extend({uri:q()})}),Dn=Y({name:q(),description:Z(q()),required:Z(vt())}).passthrough(),On=Xt.extend({description:Z(q()),arguments:Z(J(Dn)),icons:Z(J(Yt)),_meta:Z(Y({}).passthrough())}),kn=ln.extend({method:X(`prompts/list`)}),An=un.extend({prompts:J(On)}),jn=Mt.extend({method:X(`prompts/get`),params:jt.extend({name:q(),arguments:Z(Ct(q()))})}),Mn=Y({type:X(`text`),text:q(),_meta:Z(Y({}).passthrough())}).passthrough(),Nn=Y({type:X(`image`),data:pn,mimeType:q(),_meta:Z(Y({}).passthrough())}).passthrough(),Pn=Y({type:X(`audio`),data:pn,mimeType:q(),_meta:Z(Y({}).passthrough())}).passthrough(),Fn=Y({type:X(`resource`),resource:xt([fn,mn]),_meta:Z(Y({}).passthrough())}).passthrough(),In=hn.extend({type:X(`resource_link`)}),Ln=xt([Mn,Nn,Pn,In,Fn]),Rn=Y({role:wt([`user`,`assistant`]),content:Ln}).passthrough(),zn=Ft.extend({description:Z(q()),messages:J(Rn)}),Bn=Pt.extend({method:X(`notifications/prompts/list_changed`)}),Vn=Y({title:Z(q()),readOnlyHint:Z(vt()),destructiveHint:Z(vt()),idempotentHint:Z(vt()),openWorldHint:Z(vt())}).passthrough(),Hn=Xt.extend({description:Z(q()),inputSchema:Y({type:X(`object`),properties:Z(Y({}).passthrough()),required:Z(J(q()))}).passthrough(),outputSchema:Z(Y({type:X(`object`),properties:Z(Y({}).passthrough()),required:Z(J(q()))}).passthrough()),annotations:Z(Vn),icons:Z(J(Yt)),_meta:Z(Y({}).passthrough())}),Un=ln.extend({method:X(`tools/list`)}),Wn=un.extend({tools:J(Hn)}),Gn=Ft.extend({content:J(Ln).default([]),structuredContent:Y({}).passthrough().optional(),isError:Z(vt())});Gn.or(Ft.extend({toolResult:bt()}));const Kn=Mt.extend({method:X(`tools/call`),params:jt.extend({name:q(),arguments:Z(Ct(bt()))})}),qn=Pt.extend({method:X(`notifications/tools/list_changed`)}),Jn=wt([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Yn=Mt.extend({method:X(`logging/setLevel`),params:jt.extend({level:Jn})}),Xn=Pt.extend({method:X(`notifications/message`),params:Nt.extend({level:Jn,logger:Z(q()),data:bt()})}),Zn=Y({name:q().optional()}).passthrough(),Qn=Y({hints:Z(J(Zn)),costPriority:Z(_t().min(0).max(1)),speedPriority:Z(_t().min(0).max(1)),intelligencePriority:Z(_t().min(0).max(1))}).passthrough(),$n=Y({role:wt([`user`,`assistant`]),content:xt([Mn,Nn,Pn])}).passthrough(),er=Mt.extend({method:X(`sampling/createMessage`),params:jt.extend({messages:J($n),systemPrompt:Z(q()),includeContext:Z(wt([`none`,`thisServer`,`allServers`])),temperature:Z(_t()),maxTokens:_t().int(),stopSequences:Z(J(q())),metadata:Z(Y({}).passthrough()),modelPreferences:Z(Qn)})}),tr=Ft.extend({model:q(),stopReason:Z(wt([`endTurn`,`stopSequence`,`maxTokens`]).or(q())),role:wt([`user`,`assistant`]),content:St(`type`,[Mn,Nn,Pn])}),nr=Y({type:X(`boolean`),title:Z(q()),description:Z(q()),default:Z(vt())}).passthrough(),rr=Y({type:X(`string`),title:Z(q()),description:Z(q()),minLength:Z(_t()),maxLength:Z(_t()),format:Z(wt([`email`,`uri`,`date`,`date-time`]))}).passthrough(),ir=Y({type:wt([`number`,`integer`]),title:Z(q()),description:Z(q()),minimum:Z(_t()),maximum:Z(_t())}).passthrough(),ar=Y({type:X(`string`),title:Z(q()),description:Z(q()),enum:J(q()),enumNames:Z(J(q()))}).passthrough(),or=xt([nr,rr,ir,ar]),sr=Mt.extend({method:X(`elicitation/create`),params:jt.extend({message:q(),requestedSchema:Y({type:X(`object`),properties:Ct(q(),or),required:Z(J(q()))}).passthrough()})}),cr=Ft.extend({action:wt([`accept`,`decline`,`cancel`]),content:Z(Ct(q(),bt()))}),lr=Y({type:X(`ref/resource`),uri:q()}).passthrough(),ur=Y({type:X(`ref/prompt`),name:q()}).passthrough(),dr=Mt.extend({method:X(`completion/complete`),params:jt.extend({ref:xt([ur,lr]),argument:Y({name:q(),value:q()}).passthrough(),context:Z(Y({arguments:Z(Ct(q(),q()))}))})}),fr=Ft.extend({completion:Y({values:J(q()).max(100),total:Z(_t().int()),hasMore:Z(vt())}).passthrough()}),pr=Y({uri:q().startsWith(`file://`),name:Z(q()),_meta:Z(Y({}).passthrough())}).passthrough(),mr=Mt.extend({method:X(`roots/list`)}),hr=Ft.extend({roots:J(pr)}),gr=Pt.extend({method:X(`notifications/roots/list_changed`)});xt([on,$t,dr,Yn,jn,kn,_n,yn,xn,wn,Tn,Kn,Un]),xt([Jt,cn,rn,gr]),xt([qt,tr,cr,hr]),xt([on,er,sr,mr]),xt([Jt,cn,Xn,En,Cn,qn,Bn]),xt([qt,nn,fr,zn,An,vn,bn,Sn,Gn,Wn]);var _r=class extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}},vr=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},yr=class extends vr{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},br=class extends vr{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},xr=class extends vr{constructor(e,t,n,r={}){super(`HTTPServerError`,e,{feature:`http`,module:`server`,operation:`request`},{endpoint:t,statusCode:n,...r})}},Sr=class extends vr{constructor(e,t,n,r={}){super(`ProcessSpawnError`,e,{feature:`stdio`,module:`transport`,operation:`spawn`},{argCount:n?.length,command:t,...r})}},Cr=class extends vr{constructor(e,t,n,r={}){super(`ProxyConnectionError`,e,{feature:`connection`,module:`proxy`,operation:`connect`,transport:n||`unknown`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...r})}},wr=class extends vr{constructor(e,t,n=`unknown`,r={}){super(`ProxyServerError`,e,{feature:`server`,module:`proxy`,operation:n},{handler:t,...r})}},Tr=class extends vr{constructor(e,t=`unknown`,n=`unknown`,r={}){super(`TransportError`,e,{feature:t,module:`transport`,operation:n},r)}};const Er={APP_VERSION:`1.0.10`,NODE_ENV:`development`,SENTRY_DSN:null,SENTRY_ENABLED:!1},Dr=u.get,Or=Er.APP_VERSION,kr=e=>{let t={};if(e){let n=e.split(`,`);for(let e of n){let[n,...r]=e.split(`:`);n&&r.length>0&&(t[n.trim()]=r.join(`:`).trim())}}return t},Ar=e=>{try{let t=new URL(e),n=`/guard/evaluate/v1`;return t.pathname.includes(n)?(t.pathname=t.pathname.replace(n,`/access-control/authorize`),t.toString()):(console.warn(`[mcp-gateway] Warning: SCANNER_URL does not contain expected path "${n}". Access control URL derivation skipped. Current path: "${t.pathname}". Please set MCP_GATEWAY_ACCESS_CONTROL_URL explicitly.`),null)}catch(e){return console.warn(`[mcp-gateway] Warning: Failed to parse SCANNER_URL as valid URL: ${e instanceof Error?e.message:String(e)}. Please set MCP_GATEWAY_ACCESS_CONTROL_URL explicitly.`),null}},jr=t(),Mr=Dr(`NODE_ENV`).default(Er.NODE_ENV||`development`).asEnum([`development`,`production`,`staging`,`test`]),Nr=Dr(`MCP_GATEWAY_SENTRY_DSN`).default(Er.SENTRY_DSN||``).asString()||null,Pr=Dr(`MCP_GATEWAY_SENTRY_ENABLED`).default(String(Er.SENTRY_ENABLED??!1)).asBool(),Fr=Dr(`DEBUG`).default(`false`).asBool()||Dr(`MCP_GATEWAY_DEBUG`).default(`false`).asBool(),Ir=Dr(`MCP_GATEWAY_SCANNER_URL`).default(``).asString()||null,Lr=Dr(`MCP_GATEWAY_SCANNER_API_KEY`).default(``).asString()||void 0,Rr=(()=>{let e=Dr(`MCP_GATEWAY_SCANNER_HEADERS`).required(!1).asString();return e?kr(e):{}})(),zr=Dr(`MCP_GATEWAY_SCANNER_TIMEOUT_MS`).default(`20000`).asIntPositive(),Br=Dr(`MCP_GATEWAY_SCANNER_FAIL_OPEN`).default(`true`).asBool(),Vr=Dr(`MCP_GATEWAY_COMMAND`).default(`mcp-gateway`).asString(),Hr=Dr(`CLIENT_APP_NAME`).default(``).asString(),Ur=Dr(`MCP_GATEWAY_LOG_DIR`).default(a(c(),`.onyx`,`mcp-gateway`,`logs`)).asString(),Wr=(()=>Dr(`MCP_GATEWAY_ACCESS_CONTROL_URL`).default(``).asString()||(Ir?Ar(Ir):null))(),Gr=(()=>{let e=Dr(`MCP_GATEWAY_ACCESS_CONTROL_HEADERS`).required(!1).asString();return e?kr(e):{}})(),Kr=Dr(`MCP_GATEWAY_ACCESS_CONTROL_TIMEOUT_MS`).default(`3000`).asIntPositive(),qr={accessControl:{enabled:!!(Wr&&Lr),headers:Gr,timeoutMs:Kr,url:Wr},appVersion:Or,clientAppName:Hr,debug:Fr,environment:Mr,logDir:Ur,proxyCommand:Vr,scanner:{apiKey:Lr,enabled:!!Ir,failOpen:Br,headers:Rr,timeoutMs:zr,url:Ir},sentry:{debug:Fr&&Mr===`development`,dsn:Nr||void 0,enabled:Pr,environment:Mr,release:`mcp-gateway@${Or}`,tracesSampleRate:Mr===`production`?1:0}},Jr=qr.logDir,Yr=qr.debug?`debug`:`info`;let Xr=!1;try{n(Jr)||r(Jr,{recursive:!0}),Xr=!0}catch(e){let t=e instanceof Error?e.message:String(e),n=t.includes(`EACCES`)||t.includes(`permission denied`);console.error(`[mcp-gateway] WARNING: Failed to create log directory: ${Jr}`),console.error(`[mcp-gateway] Error: ${t}`),n&&(console.error(`[mcp-gateway] This appears to be a permission issue. Possible solutions:`),console.error(`[mcp-gateway] 1. Fix directory permissions: sudo chown -R $USER ~/.onyx`),console.error(`[mcp-gateway] 2. Use a different log directory: export MCP_GATEWAY_LOG_DIR=/tmp/mcp-gateway-logs`)),console.error(`[mcp-gateway] File logging will be disabled. The gateway will continue to function.`)}const Zr=o.format.combine(o.format.timestamp(),o.format.errors({stack:!0}),o.format.json());let Qr=null;const $r=[];if(Xr){let e=new s({datePattern:`YYYY-MM-DD`,filename:a(Jr,`mcp-gateway-%DATE%.log`),format:Zr,handleExceptions:!1,handleRejections:!1,level:Yr,maxFiles:10,maxSize:`10m`});$r.push(e)}const ei=o.createLogger({defaultMeta:{service:`mcp-gateway`,version:qr.appVersion},format:o.format.combine(o.format.errors({stack:!0}),o.format.metadata()),level:Yr,transports:$r}),ti=e=>{let[t,...n]=e;if(typeof t!=`string`)throw Error(`First argument must be a string message`);if(n.length>0&&n[0]&&typeof n[0]==`object`&&`proxyType`in n[0]){let e=n[0],r=n[1];return{message:t,meta:r,sessionData:e}}let r=n[0];return{message:t,meta:r,sessionData:Qr||void 0}},Q={debug:(...e)=>{let{message:t,meta:n,sessionData:r}=ti(e);ei.debug(t,{sessionData:r,...n})},error:(...e)=>{let{message:t,meta:n,sessionData:r}=ti(e);ei.error(t,{sessionData:r,...n})},getSessionData:()=>Qr,info:(...e)=>{let{message:t,meta:n,sessionData:r}=ti(e);ei.info(t,{sessionData:r,...n})},setSessionData:e=>{Qr=e,Q.debug(`Session data set for logger`,e)},warn:(...e)=>{let{message:t,meta:n,sessionData:r}=ti(e);ei.warn(t,{sessionData:r,...n})}};Q.info(`MCP Gateway logger initialized`,{debug:qr.debug,fileLoggingEnabled:Xr,logDir:Jr,logLevel:Yr});let ni={"proxy.version":qr.appVersion};function ri(e,t=`default`,n=`info`,r){try{if(!qr.sentry.enabled){Q.debug(`Breadcrumb: [${t}] ${e}`,r);return}d.addBreadcrumb({category:t,data:r?si(r):void 0,level:n,message:e,timestamp:Date.now()/1e3})}catch(e){Q.warn(`Failed to add breadcrumb to Sentry`,{error:e})}}function ii(e){ni={...ni,...e}}function ai(e,t,n){try{let r=e instanceof vr?{...e.tags,...n}:n,i=e instanceof vr?{...e.extra,...t}:t;if(!qr.sentry.enabled){let t=e instanceof Error?e.message:String(e);Q.error(`Exception captured: ${t}`,{error:e instanceof Error?e.stack||e.message:e,extra:i,tags:r});return}let a=e instanceof Error?e.message:String(e);Q.error(`Sending exception to Sentry: ${a}`,{error:e instanceof Error?e.stack||e.message:e,extra:i,tags:r}),d.withScope(t=>{r&&Object.entries(r).forEach(([e,n])=>{let r=e.startsWith(`mcp.gateway.`)?e:`mcp.gateway.${e}`;t.setTag(r,n)}),i&&Object.entries(si(i)).forEach(([e,n])=>{t.setExtra(e,n)}),t.setLevel(`error`),d.captureException(e)})}catch(e){Q.warn(`Failed to capture exception to Sentry`,{sentryError:e instanceof Error?e.message:e})}}function oi(){try{if(!qr.sentry.enabled){Q.debug(`Sentry disabled (no DSN provided or in development mode)`);return}d.init({beforeSend(e){return e.tags={...e.tags,...ni},e.extra&&=si(e.extra),e.contexts?.runtime?.name&&(e.contexts.runtime.name=`node`),e},beforeSendTransaction(e){return e.tags={...e.tags,...ni},e},debug:qr.sentry.debug,dsn:qr.sentry.dsn,environment:qr.sentry.environment,release:qr.sentry.release,tracesSampleRate:qr.sentry.tracesSampleRate}),Q.debug(`Sentry initialized`,{dsn:qr.sentry.dsn?`***configured***`:`not configured`,environment:qr.sentry.environment,release:qr.sentry.release})}catch(e){Q.warn(`Failed to initialize Sentry, continuing without error tracking`,{error:e})}}function si(e){let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.toLowerCase();if(r.includes(`password`)||r.includes(`token`)||r.includes(`key`)||r.includes(`secret`)||r.includes(`auth`)||r===`env`||r===`environment`){t[e]=`[FILTERED]`;return}if(typeof n==`string`&&(r.includes(`url`)||n.startsWith(`http`)))try{let r=new URL(n);t[e]=`${r.protocol}//${r.host}${r.pathname}`}catch{t[e]=n}else t[e]=n}),t}function ci(){return a(c(),`.claude.json`)}function li(){try{return l()}catch{return`unknown-device`}}async function ui(e){try{return(await f()).find(t=>t.pid===e)?.name||`unknown`}catch{return`unknown`}}function di(){try{let e=fi();return e?e.oauthAccount.emailAddress:void 0}catch{return}}function fi(){try{let e=ci();if(!n(e))return null;let t=i(e,`utf-8`);return JSON.parse(t)}catch{return null}}const pi=async()=>{let e=process.pid,t=process.ppid;try{let n=li(),r=di(),i=await ui(t);return{clientAppName:Hr||`unknown`,deviceName:n,email:r,parentProcessId:t,parentProcessName:i,processId:e}}catch{return{clientAppName:Hr||`unknown`,deviceName:`unknown-device`,email:void 0,parentProcessId:t,parentProcessName:`unknown`,processId:e}}};function mi(e){let t=p(JSON.stringify(e));return Buffer.from(t).toString(`base64url`)}var hi=class{clientAppName;clientInfoBase64;sessionData;get scannerConfig(){return{apiKey:this.config.scanApiKey,enabled:this.config.scanEnabled,failOpen:this.config.scanFailOpen,headers:this.config.scanHeaders,timeoutMs:this.config.scanTimeoutMs,url:this.config.scanUrl}}config;constructor(e,t){this.config=e,this.sessionData=t,this.clientAppName=t.clientAppName||``,this.clientInfoBase64=this.getClientInfoBase64()}async evaluate(e){let t={action:`allow`};if(this.isScanEnabled())try{if(t=await this.scan({data:e.data,id:e.id,method:e.method,originalRequestId:e.originalRequestId,timestamp:e.timestamp,type:e.type}),Q.info(`Scan result`,{action:t.action,id:e.id,method:e.method,originalRequestId:e.originalRequestId}),t.action===`block`)return Q.warn(`Request blocked by security policy`),t}catch(t){if(Q.error(`Scanning failed`,{error:t}),ai(t instanceof Error?t:Error(String(t)),{method:e.method,requestType:e.type,scannerUrl:this.config.scanUrl},{feature:`traffic-scanner`,module:`evaluator`,operation:`scan`}),!this.config.scanFailOpen)return Q.warn(`Scanning service unavailable, blocking traffic (fail-closed)`),{action:`block`};Q.warn(`Scanning service unavailable, allowing traffic (fail-open)`)}return t}isEnabled(){return this.isScanEnabled()}isScanEnabled(){return this.config.scanEnabled&&!!this.config.scanUrl}async scan(e){if(!this.isScanEnabled())return{action:`allow`};let t={data:e.data,id:e.id,metadata:this.sessionData,method:e.method,originalRequestId:e.originalRequestId,type:e.type};Q.info(`Scanning traffic`,{id:e.id,method:e.method,originalRequestId:e.originalRequestId,type:e.type});let n=await this.sendScanRequest(t);return Q.info(`Scan result`,{action:n.action,blockReason:n.block_reason,hasModifiedData:!!n.modified_data,id:e.id,originalRequestId:e.originalRequestId}),n}updateConfig(e){this.config={...this.config,...e}}getClientInfoBase64(){return mi(this.sessionData)}async sendScanRequest(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.scanTimeoutMs);try{let n=`${this.config.scanUrl}/${this.config.scanApiKey}/mcp/${this.clientInfoBase64}`,r={data:e.data,id:e.id,metadata:e.metadata,method:e.method,sessionId:jr,...e.originalRequestId&&{original_request_id:String(e.originalRequestId)},type:e.type},i=await fetch(n,{body:JSON.stringify(r),headers:{"Content-Type":`application/json`,...this.config.scanHeaders},method:`POST`,signal:t.signal});if(!i.ok)throw Error(`Sanitization service returned ${i.status}: ${i.statusText}`);let a=await i.json();if(!a.action||![`allow`,`block`,`modify`].includes(a.action))throw Error(`Invalid scan response format: action="${a.action}"`);return a}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Scan request timed out after ${this.config.scanTimeoutMs}ms`):e}finally{clearTimeout(n)}}};let gi=null;const _i=async e=>{let t=await pi(),n=e.cliArgs.proxyType,r={...t,proxyType:n,remoteCliArgs:n===`remote`?e.cliArgs:void 0,stdioCliArgs:n===`stdio`?e.cliArgs:void 0};return Q.setSessionData(r),gi=new hi(e,r),gi},vi=()=>gi,yi=e=>e.length>1&&e[1]&&typeof e[1]==`object`&&`requestId`in e[1]?e[1].requestId:void 0,bi=(e,n,r,i)=>async(...a)=>{let o=vi(),s=e,c=a[0],l=t(),u=yi(a)?.toString();c&&typeof c==`object`&&`method`in c&&typeof c.method==`string`&&(s=c.method);let d=async(e,t,n)=>{try{if(!o?.isEnabled()&&!o?.isScanEnabled())return;let r;try{r=await o.evaluate({data:t,id:l,method:s,originalRequestId:u,timestamp:new Date().toISOString(),type:e})}catch(t){if(Q.error(`${e} evaluation failed, applying fail-safe`,{error:t}),o?.isScanEnabled()&&!o.scannerConfig?.failOpen)throw Error(`Security scanning service unavailable`);return}if(Q.info(`${e} scan result`,{action:r.action,id:l,method:s,...e===`request`&&{originalRequestId:u}}),r.action===`block`||r.action===`modify`){let t=r.action===`block`?`blocked`:`modified`,i=r.action===`block`&&e===`request`?`warn`:`log`;if(r.modified_data){if(r.action===`block`){let n=`${e} ${t} by security policy${e===`request`?`, returning error response`:``}`;return i===`warn`?Q.warn(n):Q.info(n),r.modified_data}if(n){let a=`${e} ${t} by security policy`;i===`warn`?Q.warn(a):Q.info(a),n(r.modified_data);return}return r.modified_data}Q.warn(`${r.action} action without modified_data, allowing original ${e}`)}return}catch(t){if(Q.error(`Unexpected error during ${e} processing`,{error:t}),ai(t),e===`request`&&t instanceof Error&&t.message===`Security scanning service unavailable`)throw t;return}},f;try{f=await d(`request`,c,e=>{a[0]=e})}catch(t){if(t instanceof Error&&t.message===`Security scanning service unavailable`){let r=new wr(`Security scanning unavailable (fail-closed)`,e,n,{errorMessage:t.message});throw ai(r),t}Q.error(`Unexpected error during request processing, continuing`,{error:t}),ai(t)}if(f!==void 0)return f;if(i&&!await i.isAllowed()){let t=i.getBlockReason();throw Q.warn(`MCP server blocked by access control`,{handlerName:e,operation:n,reason:t}),new yr(t,`policy_block`)}try{let e=await r(...a);try{if(e){let t=await d(`response`,e);if(t!==void 0)return t}}catch(e){Q.error(`Error during response processing, returning original result`,{error:e}),ai(e)}return e}catch(t){if(t instanceof yr)throw Q.info(`Request blocked by access control`,{error:t.message,handlerName:e,operation:n,reason:t.reason}),t;try{await d(`error`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}catch(e){Q.warn(`Failed to evaluate error`,{evalError:e})}let r=new wr(`Handler error: ${t}`,e,n,{argsCount:a.length,errorMessage:t instanceof Error?t.message:String(t)});throw ai(r),t}},xi=async({authorizer:e,client:t,server:n,serverCapabilities:r})=>{r?.logging&&(n.setNotificationHandler(Xn,bi(`notifications/message`,`server-to-client`,async e=>t.notification(e),e)),t.setNotificationHandler(Xn,bi(`notifications/message`,`client-to-server`,async e=>n.notification(e),e))),r?.prompts&&(n.setRequestHandler(jn,bi(`prompts/get`,`get`,async e=>t.getPrompt(e.params),e)),n.setRequestHandler(kn,bi(`prompts/list`,`list`,async e=>t.listPrompts(e.params),e))),r?.resources&&(n.setRequestHandler(_n,bi(`resources/list`,`list`,async e=>t.listResources(e.params),e)),n.setRequestHandler(yn,bi(`resources/templates/list`,`list`,async e=>t.listResourceTemplates(e.params),e)),n.setRequestHandler(xn,bi(`resources/read`,`read`,async e=>t.readResource(e.params),e)),r?.resources.subscribe&&(n.setNotificationHandler(En,bi(`notifications/resources/updated`,`notify`,async e=>t.notification(e),e)),n.setRequestHandler(wn,bi(`resources/subscribe`,`subscribe`,async e=>t.subscribeResource(e.params),e)),n.setRequestHandler(Tn,bi(`resources/unsubscribe`,`unsubscribe`,async e=>t.unsubscribeResource(e.params),e)))),r?.tools&&(n.setRequestHandler(Kn,bi(`tools/call`,`call`,async e=>t.callTool(e.params),e)),n.setRequestHandler(Un,bi(`tools/list`,`list`,async e=>t.listTools(e.params),e))),n.setRequestHandler(dr,bi(`completion/complete`,`complete`,async e=>t.complete(e.params),e))};var Si=w(((exports,t)=>{t.exports=o,t.exports.format=s,t.exports.parse=c;var n=/\B(?=(\d{3})+(?!\d))/g,r=/(?:\.0*|(\.[^0]+)0+)$/,i={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:1024**4,pb:1024**5},a=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function o(e,t){return typeof e==`string`?c(e):typeof e==`number`?s(e,t):null}function s(e,t){if(!Number.isFinite(e))return null;var a=Math.abs(e),o=t&&t.thousandsSeparator||``,s=t&&t.unitSeparator||``,c=t&&t.decimalPlaces!==void 0?t.decimalPlaces:2,l=!!(t&&t.fixedDecimals),u=t&&t.unit||``;(!u||!i[u.toLowerCase()])&&(u=a>=i.pb?`PB`:a>=i.tb?`TB`:a>=i.gb?`GB`:a>=i.mb?`MB`:a>=i.kb?`KB`:`B`);var d=(e/i[u.toLowerCase()]).toFixed(c);return l||(d=d.replace(r,`$1`)),o&&(d=d.split(`.`).map(function(e,t){return t===0?e.replace(n,o):e}).join(`.`)),d+s+u}function c(e){if(typeof e==`number`&&!isNaN(e))return e;if(typeof e!=`string`)return null;var t=a.exec(e),n,r=`b`;return t?(n=parseFloat(t[1]),r=t[4].toLowerCase()):(n=parseInt(e,10),r=`b`),isNaN(n)?null:Math.floor(i[r]*n)}})),Ci=w(((exports,t)=>{
2
2
  /*!
3
3
  * depd
4
4
  * Copyright(c) 2014-2018 Douglas Christopher Wilson
@@ -26,4 +26,4 @@ return fn.apply(this, arguments)
26
26
  `&&r++}}return[t,n]}var _o=class extends Event{constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(bo(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(bo(this),t)}};function vo(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function yo(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(yo).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${yo(e.cause)}`:e.message:`${e}`}function bo(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var xo=e=>{throw TypeError(e)},So=(e,t,n)=>t.has(e)||xo(`Cannot `+n),$=(e,t,n)=>(So(e,t,`read from private field`),n?n.call(e):t.get(e)),Co=(e,t,n)=>t.has(e)?xo(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),wo=(e,t,n,r)=>(So(e,t,`write to private field`),t.set(e,n),n),To=(e,t,n)=>(So(e,t,`access private method`),n),Eo,Do,Oo,ko,Ao,jo,Mo,No,Po,Fo,Io,Lo,Ro,zo,Bo,Vo,Ho,Uo,Wo,Go,Ko,qo,Jo,Yo=class extends EventTarget{constructor(e,t){super(),Co(this,zo),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Co(this,Eo),Co(this,Do),Co(this,Oo),Co(this,ko),Co(this,Ao),Co(this,jo),Co(this,Mo),Co(this,No,null),Co(this,Po),Co(this,Fo),Co(this,Io,null),Co(this,Lo,null),Co(this,Ro,null),Co(this,Vo,async e=>{var t;$(this,Fo).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){To(this,zo,Ko).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?wo(this,Oo,new URL(e.url)):wo(this,Oo,void 0),i!==200){To(this,zo,Ko).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){To(this,zo,Ko).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if($(this,Eo)===this.CLOSED)return;wo(this,Eo,this.OPEN);let o=new Event(`open`);if((t=$(this,Ro))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){To(this,zo,Ko).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&$(this,Fo).feed(s.decode(t,{stream:!e})),e&&(l=!1,$(this,Fo).reset(),To(this,zo,qo).call(this))}while(l)}),Co(this,Ho,e=>{wo(this,Po,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&To(this,zo,qo).call(this,yo(e))}),Co(this,Wo,e=>{typeof e.id==`string`&&wo(this,No,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:$(this,Oo)?$(this,Oo).origin:$(this,Do).origin,lastEventId:e.id||``});$(this,Lo)&&(!e.event||e.event===`message`)&&$(this,Lo).call(this,t),this.dispatchEvent(t)}),Co(this,Go,e=>{wo(this,jo,e)}),Co(this,Jo,()=>{wo(this,Mo,void 0),$(this,Eo)===this.CONNECTING&&To(this,zo,Bo).call(this)});try{if(e instanceof URL)wo(this,Do,e);else if(typeof e==`string`)wo(this,Do,new URL(e,Xo()));else throw Error(`Invalid URL`)}catch{throw vo(`An invalid or illegal string was specified`)}wo(this,Fo,ho({onEvent:$(this,Wo),onRetry:$(this,Go)})),wo(this,Eo,this.CONNECTING),wo(this,jo,3e3),wo(this,Ao,t?.fetch??globalThis.fetch),wo(this,ko,t?.withCredentials??!1),To(this,zo,Bo).call(this)}get readyState(){return $(this,Eo)}get url(){return $(this,Do).href}get withCredentials(){return $(this,ko)}get onerror(){return $(this,Io)}set onerror(e){wo(this,Io,e)}get onmessage(){return $(this,Lo)}set onmessage(e){wo(this,Lo,e)}get onopen(){return $(this,Ro)}set onopen(e){wo(this,Ro,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){$(this,Mo)&&clearTimeout($(this,Mo)),$(this,Eo)!==this.CLOSED&&($(this,Po)&&$(this,Po).abort(),wo(this,Eo,this.CLOSED),wo(this,Po,void 0))}};Eo=new WeakMap,Do=new WeakMap,Oo=new WeakMap,ko=new WeakMap,Ao=new WeakMap,jo=new WeakMap,Mo=new WeakMap,No=new WeakMap,Po=new WeakMap,Fo=new WeakMap,Io=new WeakMap,Lo=new WeakMap,Ro=new WeakMap,zo=new WeakSet,Bo=function(){wo(this,Eo,this.CONNECTING),wo(this,Po,new AbortController),$(this,Ao)($(this,Do),To(this,zo,Uo).call(this)).then($(this,Vo)).catch($(this,Ho))},Vo=new WeakMap,Ho=new WeakMap,Uo=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...$(this,No)?{"Last-Event-ID":$(this,No)}:void 0},cache:`no-store`,signal:$(this,Po)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},Wo=new WeakMap,Go=new WeakMap,Ko=function(e,t){var n;$(this,Eo)!==this.CLOSED&&wo(this,Eo,this.CLOSED);let r=new _o(`error`,{code:t,message:e});(n=$(this,Io))==null||n.call(this,r),this.dispatchEvent(r)},qo=function(e,t){var n;if($(this,Eo)===this.CLOSED)return;wo(this,Eo,this.CONNECTING);let r=new _o(`error`,{code:t,message:e});(n=$(this,Io))==null||n.call(this,r),this.dispatchEvent(r),wo(this,Mo,setTimeout($(this,Jo),$(this,jo)))},Jo=new WeakMap,Yo.CONNECTING=0,Yo.OPEN=1,Yo.CLOSED=2;function Xo(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}let Zo;Zo=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function Qo(e){return(await Zo).getRandomValues(new Uint8Array(e))}async function $o(e){let t=``,n=await Qo(e);for(let r=0;r<e;r++){let e=n[r]%66;t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e]}return t}async function es(e){return await $o(e)}async function ts(e){let t=await(await Zo).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function ns(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await es(e),n=await ts(t);return{code_verifier:t,code_challenge:n}}const rs=q().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:N.custom,message:`URL must be parseable`,fatal:!0}),Tt}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),os=Y({resource:q().url(),authorization_servers:J(rs).optional(),jwks_uri:q().url().optional(),scopes_supported:J(q()).optional(),bearer_methods_supported:J(q()).optional(),resource_signing_alg_values_supported:J(q()).optional(),resource_name:q().optional(),resource_documentation:q().optional(),resource_policy_uri:q().url().optional(),resource_tos_uri:q().url().optional(),tls_client_certificate_bound_access_tokens:vt().optional(),authorization_details_types_supported:J(q()).optional(),dpop_signing_alg_values_supported:J(q()).optional(),dpop_bound_access_tokens_required:vt().optional()}).passthrough(),ss=Y({issuer:q(),authorization_endpoint:rs,token_endpoint:rs,registration_endpoint:rs.optional(),scopes_supported:J(q()).optional(),response_types_supported:J(q()),response_modes_supported:J(q()).optional(),grant_types_supported:J(q()).optional(),token_endpoint_auth_methods_supported:J(q()).optional(),token_endpoint_auth_signing_alg_values_supported:J(q()).optional(),service_documentation:rs.optional(),revocation_endpoint:rs.optional(),revocation_endpoint_auth_methods_supported:J(q()).optional(),revocation_endpoint_auth_signing_alg_values_supported:J(q()).optional(),introspection_endpoint:q().optional(),introspection_endpoint_auth_methods_supported:J(q()).optional(),introspection_endpoint_auth_signing_alg_values_supported:J(q()).optional(),code_challenge_methods_supported:J(q()).optional()}).passthrough(),cs=Y({issuer:q(),authorization_endpoint:rs,token_endpoint:rs,userinfo_endpoint:rs.optional(),jwks_uri:rs,registration_endpoint:rs.optional(),scopes_supported:J(q()).optional(),response_types_supported:J(q()),response_modes_supported:J(q()).optional(),grant_types_supported:J(q()).optional(),acr_values_supported:J(q()).optional(),subject_types_supported:J(q()),id_token_signing_alg_values_supported:J(q()),id_token_encryption_alg_values_supported:J(q()).optional(),id_token_encryption_enc_values_supported:J(q()).optional(),userinfo_signing_alg_values_supported:J(q()).optional(),userinfo_encryption_alg_values_supported:J(q()).optional(),userinfo_encryption_enc_values_supported:J(q()).optional(),request_object_signing_alg_values_supported:J(q()).optional(),request_object_encryption_alg_values_supported:J(q()).optional(),request_object_encryption_enc_values_supported:J(q()).optional(),token_endpoint_auth_methods_supported:J(q()).optional(),token_endpoint_auth_signing_alg_values_supported:J(q()).optional(),display_values_supported:J(q()).optional(),claim_types_supported:J(q()).optional(),claims_supported:J(q()).optional(),service_documentation:q().optional(),claims_locales_supported:J(q()).optional(),ui_locales_supported:J(q()).optional(),claims_parameter_supported:vt().optional(),request_parameter_supported:vt().optional(),request_uri_parameter_supported:vt().optional(),require_request_uri_registration:vt().optional(),op_policy_uri:rs.optional(),op_tos_uri:rs.optional()}).passthrough().merge(ss.pick({code_challenge_methods_supported:!0})),ls=Y({access_token:q(),id_token:q().optional(),token_type:q(),expires_in:_t().optional(),scope:q().optional(),refresh_token:q().optional()}).strip(),us=Y({error:q(),error_description:q().optional(),error_uri:q().optional()}),ds=Y({redirect_uris:J(rs),token_endpoint_auth_method:q().optional(),grant_types:J(q()).optional(),response_types:J(q()).optional(),client_name:q().optional(),client_uri:rs.optional(),logo_uri:rs.optional(),scope:q().optional(),contacts:J(q()).optional(),tos_uri:rs.optional(),policy_uri:q().optional(),jwks_uri:rs.optional(),jwks:yt().optional(),software_id:q().optional(),software_version:q().optional(),software_statement:q().optional()}).strip(),fs=Y({client_id:q(),client_secret:q().optional(),client_id_issued_at:_t().optional(),client_secret_expires_at:_t().optional()}).strip(),ps=ds.merge(fs);Y({error:q(),error_description:q().optional()}).strip(),Y({token:q(),token_type_hint:q().optional()}).strip();function ms(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function hs({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var gs=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},_s=class extends gs{};_s.errorCode=`invalid_request`;var vs=class extends gs{};vs.errorCode=`invalid_client`;var ys=class extends gs{};ys.errorCode=`invalid_grant`;var bs=class extends gs{};bs.errorCode=`unauthorized_client`;var xs=class extends gs{};xs.errorCode=`unsupported_grant_type`;var Ss=class extends gs{};Ss.errorCode=`invalid_scope`;var Cs=class extends gs{};Cs.errorCode=`access_denied`;var ws=class extends gs{};ws.errorCode=`server_error`;var Ts=class extends gs{};Ts.errorCode=`temporarily_unavailable`;var Es=class extends gs{};Es.errorCode=`unsupported_response_type`;var Ds=class extends gs{};Ds.errorCode=`unsupported_token_type`;var Os=class extends gs{};Os.errorCode=`invalid_token`;var ks=class extends gs{};ks.errorCode=`method_not_allowed`;var As=class extends gs{};As.errorCode=`too_many_requests`;var js=class extends gs{};js.errorCode=`invalid_client_metadata`;var Ms=class extends gs{};Ms.errorCode=`insufficient_scope`;const Ns={[_s.errorCode]:_s,[vs.errorCode]:vs,[ys.errorCode]:ys,[bs.errorCode]:bs,[xs.errorCode]:xs,[Ss.errorCode]:Ss,[Cs.errorCode]:Cs,[ws.errorCode]:ws,[Ts.errorCode]:Ts,[Es.errorCode]:Es,[Ds.errorCode]:Ds,[Os.errorCode]:Os,[ks.errorCode]:ks,[As.errorCode]:As,[js.errorCode]:js,[Ms.errorCode]:Ms};var Ps=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Fs(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Is(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Ls(i,a,n);return;case`client_secret_post`:Rs(i,a,r);return;case`none`:zs(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Ls(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Rs(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function zs(e,t){t.set(`client_id`,e)}async function Bs(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=us.parse(JSON.parse(n));return new(Ns[e]||ws)(t||``,r)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new ws(r)}}async function Vs(e,t){try{return await Hs(e,t)}catch(n){if(n instanceof vs||n instanceof bs)return await e.invalidateCredentials?.call(e,`all`),await Hs(e,t);if(n instanceof ys)return await e.invalidateCredentials?.call(e,`tokens`),await Hs(e,t);throw n}}async function Hs(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o,s;try{o=await Gs(t,{resourceMetadataUrl:i},a),o.authorization_servers&&o.authorization_servers.length>0&&(s=o.authorization_servers[0])}catch{}s||=t;let c=await Us(t,e,o),l=await Qs(s,{fetchFn:a}),u=await Promise.resolve(e.clientInformation());if(!u){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await nc(s,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(t),u=t}if(n!==void 0){let t=await e.codeVerifier(),r=await ec(s,{metadata:l,clientInformation:u,authorizationCode:n,codeVerifier:t,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(r),`AUTHORIZED`}let d=await e.tokens();if(d?.refresh_token)try{let t=await tc(s,{metadata:l,clientInformation:u,refreshToken:d.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof gs)||e instanceof ws))throw e}let f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:m}=await $s(s,{metadata:l,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:r||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(p),`REDIRECT`}async function Us(e,t,n){let r=ms(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!hs({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function Ws(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=/resource_metadata="([^"]*)"/.exec(t);if(i)try{return new URL(i[1])}catch{return}}async function Gs(e,t,n=fetch){let r=await Xs(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return os.parse(await r.json())}async function Ks(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Ks(e,void 0,n):void 0;throw r}}function qs(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Js(e,t,n=fetch){return await Ks(e,{"MCP-Protocol-Version":t},n)}function Ys(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Xs(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??Et,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=qs(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await Js(o,a,n);if(!r?.metadataUrl&&Ys(s,i.pathname)){let e=new URL(`/.well-known/${t}`,i);s=await Js(e,a,n)}return s}function Zs(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function Qs(e,{fetchFn:t=fetch,protocolVersion:n=Et}={}){let r={"MCP-Protocol-Version":n},i=Zs(e);for(let{url:e,type:n}of i){let i=await Ks(e,r,t);if(!i)continue;if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`)return ss.parse(await i.json());{let t=cs.parse(await i.json());if(!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}async function $s(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await ns(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,o.href),{authorizationUrl:l,codeVerifier:d}}async function ec(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});if(s)s(d,f,e,t);else{let e=t?.token_endpoint_auth_methods_supported??[],r=Fs(n,e);Is(r,n,d,f)}o&&f.set(`resource`,o.href);let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Bs(p);return ls.parse(await p.json())}async function tc(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`}),u=new URLSearchParams({grant_type:s,refresh_token:r});if(a)a(l,u,e,t);else{let e=t?.token_endpoint_auth_methods_supported??[],r=Fs(n,e);Is(r,n,l,u)}i&&u.set(`resource`,i.href);let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Bs(d);return ls.parse({refresh_token:r,...await d.json()})}async function nc(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Bs(a);return ps.parse(await a.json())}var rc=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},ic=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new Ps(`No auth provider`);let t;try{t=await Vs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw(e=this.onerror)==null||e.call(this,t),t}if(t!==`AUTHORIZED`)throw new Ps;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}return this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion),new Headers({...e,...this._requestInit?.headers})}_startOrAuth(){let e=(this===null||this===void 0?void 0:this._eventSourceInit)?.fetch??this._fetch??fetch;return new Promise((t,n)=>{this._eventSource=new Yo(this._url.href,{...this._eventSourceInit,fetch:async(t,n)=>{let r=await this._commonHeaders();r.set(`Accept`,`text/event-stream`);let i=await e(t,{...n,headers:r});return i.status===401&&i.headers.has(`www-authenticate`)&&(this._resourceMetadataUrl=Ws(i)),i}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{var r;if(e.code===401&&this._authProvider){this._authThenStart().then(t,n);return}let i=new rc(e.code,e.message,e);n(i),(r=this.onerror)==null||r.call(this,i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener(`endpoint`,e=>{var r;let i=e;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){n(e),(r=this.onerror)==null||r.call(this,e),this.close();return}t()}),this._eventSource.onmessage=e=>{var t,n;let r=e,i;try{i=Kt.parse(JSON.parse(r.data))}catch(e){(t=this.onerror)==null||t.call(this,e);return}(n=this.onmessage)==null||n.call(this,i)}})}async start(){if(this._eventSource)throw Error(`SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Ps(`No auth provider`);if(await Vs(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ps(`Failed to authorize`)}async close(){var e,t,n;(e=this._abortController)==null||e.abort(),(t=this._eventSource)==null||t.close(),(n=this.onclose)==null||n.call(this)}async send(e){var t;if(!this._endpoint)throw Error(`Not connected`);try{let t=await this._commonHeaders();t.set(`content-type`,`application/json`);let n={...this._requestInit,method:`POST`,headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._endpoint,n);if(!r.ok){if(r.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ws(r),await Vs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ps;return this.send(e)}let t=await r.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${r.status}): ${t}`)}}catch(e){throw(t=this.onerror)==null||t.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}},ac=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=ho({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const oc={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var sc=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},cc=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??oc}async _authThenStart(){var e;if(!this._authProvider)throw new Ps(`No auth provider`);let t;try{t=await Vs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw(e=this.onerror)==null||e.call(this,t),t}if(t!==`AUTHORIZED`)throw new Ps;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=this._normalizeHeaders(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){var t;let{resumptionToken:n}=e;try{let t=await this._commonHeaders();t.set(`Accept`,`text/event-stream`),n&&t.set(`last-event-id`,n);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:t,signal:this._abortController?.signal});if(!r.ok){if(r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new sc(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw(t=this.onerror)==null||t.call(this,e),e}}_getNextReconnectionDelay(e){let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,t=0){var n;let r=this._reconnectionOptions.maxRetries;if(r>0&&t>=r){(n=this.onerror)==null||n.call(this,Error(`Maximum reconnection attempts (${r}) exceeded.`));return}let i=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{var r;(r=this.onerror)==null||r.call(this,Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a;(async()=>{var t,o,s,c;try{let n=e.pipeThrough(new TextDecoderStream).pipeThrough(new ac).getReader();for(;;){let{value:e,done:s}=await n.read();if(s)break;if(e.id&&(a=e.id,r?.(e.id)),!e.event||e.event===`message`)try{let n=Kt.parse(JSON.parse(e.data));i!==void 0&&Ht(n)&&(n.id=i),(t=this.onmessage)==null||t.call(this,n)}catch(e){(o=this.onerror)==null||o.call(this,e)}}}catch(e){if((s=this.onerror)==null||s.call(this,Error(`SSE stream disconnected: ${e}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){(c=this.onerror)==null||c.call(this,Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Ps(`No auth provider`);if(await Vs(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ps(`Failed to authorize`)}async close(){var e,t;(e=this._abortController)==null||e.abort(),(t=this.onclose)==null||t.call(this)}async send(e,t){var n,r;try{let{resumptionToken:r,onresumptiontoken:i}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:Rt(e)?e.id:void 0}).catch(e=>this.onerror?.call(this,e));return}let a=await this._commonHeaders();a.set(`content-type`,`application/json`),a.set(`accept`,`application/json, text/event-stream`);let o={...this._requestInit,method:`POST`,headers:a,body:JSON.stringify(e),signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._url,o),c=s.headers.get(`mcp-session-id`);if(c&&(this._sessionId=c),!s.ok){if(s.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ws(s),await Vs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ps;return this.send(e)}let t=await s.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${s.status}): ${t}`)}if(s.status===202){an(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.call(this,e));return}let l=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,u=s.headers.get(`content-type`);if(l)if(u?.includes(`text/event-stream`))this._handleSseStream(s.body,{onresumptiontoken:i},!1);else if(u?.includes(`application/json`)){let e=await s.json(),t=Array.isArray(e)?e.map(e=>Kt.parse(e)):[Kt.parse(e)];for(let e of t)(n=this.onmessage)==null||n.call(this,e)}else throw new sc(-1,`Unexpected content type: ${u}`)}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e;if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(!n.ok&&n.status!==405)throw new sc(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw(e=this.onerror)==null||e.call(this,t),t}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}},lc=E(lo(),1),uc=class extends ga{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Jn.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this.setRequestHandler($t,e=>this._oninitialize(e)),this.setNotificationHandler(rn,()=>this.oninitialized?.call(this)),this._capabilities.logging&&this.setRequestHandler(Yn,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Jn.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=_a(this._capabilities,e)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Server does not support sampling (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`ping`:case`initialize`:break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Dt.includes(t)?t:Et,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},qt)}async createMessage(e,t){return this.request({method:`sampling/createMessage`,params:e},tr,t)}async elicitInput(e,t){let n=await this.request({method:`elicitation/create`,params:e},cr,t);if(n.action===`accept`&&n.content)try{let t=new lc.default,r=t.compile(e.requestedSchema);if(!r(n.content))throw new _r(Ut.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(r.errors)}`)}catch(e){throw e instanceof _r?e:new _r(Ut.InternalError,`Error validating elicitation response: ${e}`)}return n}async listRoots(e,t){return this.request({method:`roots/list`,params:e},hr,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},dc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
27
27
  `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),fc(t)}clear(){this._buffer=void 0}};function fc(e){return Kt.parse(JSON.parse(e))}function pc(e){return JSON.stringify(e)+`
28
28
  `}var mc=class{constructor(e=_.stdin,t=_.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new dc,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{var t;(t=this.onerror)==null||t.call(this,e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(var e,t;;)try{let t=this._readBuffer.readMessage();if(t===null)break;(e=this.onmessage)==null||e.call(this,t)}catch(e){(t=this.onerror)==null||t.call(this,e)}}async close(){var e;this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)==null||e.call(this)}send(e){return new Promise(t=>{let n=pc(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};export{yr as AccessControlBlockError,fo as Client,br as ConfigurationError,O as InMemoryEventStore,Sr as ProcessSpawnError,Cr as ProxyConnectionError,dc as ReadBuffer,ic as SSEClientTransport,uc as Server,mc as StdioServerTransport,cc as StreamableHTTPClientTransport,Tr as TransportError,w as __commonJSMin,E as __toESM,ri as addBreadcrumbSafe,ii as addGlobalTags,ai as captureExceptionSafe,mi as compressClientInfo,qr as config,ho as createParser,pi as getSessionData,oi as initSentrySafe,_i as initializeTrafficMirror,Q as logger,xi as proxyServer,pc as serializeMessage,ha as startHTTPServer};
29
- //# sourceMappingURL=stdio-BRHpVFf0.js.map
29
+ //# sourceMappingURL=stdio-DLhH1AFQ.js.map