@onyxsecurity/mcp-gateway 1.0.48 → 1.0.49
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/bin/mcp-gateway.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{main-Dc7hWPe7.js → main-ChR3eaOT.js} +2 -2
- package/dist/{main-Dc7hWPe7.js.map → main-ChR3eaOT.js.map} +1 -1
- package/dist/{normalizeUrl-DWilbohl.js → normalizeUrl-DwqzAC5_.js} +2 -2
- package/dist/{normalizeUrl-DWilbohl.js.map → normalizeUrl-DwqzAC5_.js.map} +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-CrDKVgUD.js";import{randomUUID as r}from"crypto";import{existsSync as i,mkdirSync as a,readFileSync as o}from"node:fs";import{join as s}from"node:path";import c from"winston";import l from"winston-daily-rotate-file";import u from"env-var";import{homedir as d,hostname as f,userInfo as p}from"node:os";import"dotenv/config";import*as m from"@sentry/node";import h from"ps-list";import{deflateSync as g}from"node:zlib";import{randomUUID as _}from"node:crypto";import{URL as v}from"url";import y from"node:http";import b from"node:process";var x=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]:``}},S;(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})(S||={});var C;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(C||={});const w=S.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),T=e=>{switch(typeof e){case`undefined`:return w.undefined;case`string`:return w.string;case`number`:return Number.isNaN(e)?w.nan:w.number;case`boolean`:return w.boolean;case`function`:return w.function;case`bigint`:return w.bigint;case`symbol`:return w.symbol;case`object`:return Array.isArray(e)?w.array:e===null?w.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?w.promise:typeof Map<`u`&&e instanceof Map?w.map:typeof Set<`u`&&e instanceof Set?w.set:typeof Date<`u`&&e instanceof Date?w.date:w.object;default:return w.unknown}},E=S.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 D=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,S.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()}};D.create=e=>new D(e);var O=(e,t)=>{let n;switch(e.code){case E.invalid_type:n=e.received===w.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,S.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${S.joinValues(e.keys,`, `)}`;break;case E.invalid_union:n=`Invalid input`;break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${S.joinValues(e.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${S.joinValues(e.options)}, received '${e.received}'`;break;case E.invalid_arguments:n=`Invalid function arguments`;break;case E.invalid_return_type:n=`Invalid function return type`;break;case E.invalid_date:n=`Invalid date`;break;case E.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}"`:S.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case E.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 E.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 E.custom:n=`Invalid input`;break;case E.invalid_intersection_types:n=`Intersection results could not be merged`;break;case E.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case E.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,S.assertNever(e)}return{message:n}};let k=O;function A(){return k}const j=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 M(e,t){let n=A(),r=j({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===O?void 0:O].filter(e=>!!e)});e.common.issues.push(r)}var N=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 P;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 P;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 P=Object.freeze({status:`aborted`}),F=e=>({status:`dirty`,value:e}),I=e=>({status:`valid`,value:e}),ee=e=>e.status===`aborted`,L=e=>e.status===`dirty`,R=e=>e.status===`valid`,z=e=>typeof Promise<`u`&&e instanceof Promise;var B;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(B||={});var V=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 te=(e,t)=>{if(R(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 D(e.common.issues),this._error}}};function H(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 U=class{get description(){return this._def.description}_getType(e){return T(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:T(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new N,ctx:{common:e.parent.common,data:e.data,parsedType:T(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(z(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:T(e)},r=this._parseSync({data:e,path:n.path,parent:n});return te(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:T(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return R(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=>R(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:T(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(z(r)?r:Promise.resolve(r));return te(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:E.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 nt({schema:this,typeName:G.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 rt.create(this,this._def)}nullable(){return it.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Le.create(this)}promise(){return tt.create(this,this._def)}or(e){return Be.create([this,e],this._def)}and(e){return We.create(this,e,this._def)}transform(e){return new nt({...H(this._def),schema:this,typeName:G.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new at({...H(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new ct({typeName:G.ZodBranded,type:this,...H(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ot({...H(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return lt.create(this,e)}readonly(){return ut.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const ne=/^c[^\s-]{8,}$/i,re=/^[0-9a-z]+$/,W=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ie=/^[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,ae=/^[a-z0-9_-]{21}$/i,oe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,se=/^[-+]?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)?)??$/,ce=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let le;const ue=/^(?:(?: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])$/,de=/^(?:(?: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])$/,fe=/^(([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]))$/,pe=/^(([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])$/,me=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,he=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ge=`((\\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])))`,_e=RegExp(`^${ge}$`);function ve(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 ye(e){return RegExp(`^${ve(e)}$`)}function be(e){let t=`${ge}T${ve(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function xe(e,t){return!!((t===`v4`||!t)&&ue.test(e)||(t===`v6`||!t)&&fe.test(e))}function Se(e,t){if(!oe.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 Ce(e,t){return!!((t===`v4`||!t)&&de.test(e)||(t===`v6`||!t)&&pe.test(e))}var we=class e extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==w.string){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.string,received:t.parsedType}),P}let t=new N,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),M(n,{code:E.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),M(n,{code:E.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?M(n,{code:E.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&M(n,{code:E.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)ce.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`email`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)le||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),le.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`emoji`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ie.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`uuid`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)ae.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`nanoid`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)ne.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`cuid`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)re.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`cuid2`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)W.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`ulid`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),M(n,{validation:`url`,code:E.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),M(n,{validation:`regex`,code:E.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),M(n,{code:E.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),M(n,{code:E.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),M(n,{code:E.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?be(r).test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{code:E.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?_e.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{code:E.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?ye(r).test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{code:E.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?se.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`duration`,code:E.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?xe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`ip`,code:E.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Se(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`jwt`,code:E.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Ce(e.data,r.version)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`cidr`,code:E.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?me.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`base64`,code:E.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?he.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`base64url`,code:E.invalid_string,message:r.message}),t.dirty()):S.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:E.invalid_string,...B.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...B.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...B.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...B.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...B.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...B.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...B.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...B.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...B.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...B.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...B.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...B.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,...B.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,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...B.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...B.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...B.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...B.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...B.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...B.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...B.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...B.errToObj(t)})}nonempty(e){return this.min(1,B.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}};we.create=e=>new we({checks:[],typeName:G.ZodString,coerce:e?.coerce??!1,...H(e)});function Te(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 Ee=class e extends U{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)!==w.number){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.number,received:t.parsedType}),P}let t,n=new N;for(let r of this._def.checks)r.kind===`int`?S.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),M(t,{code:E.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),M(t,{code:E.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),M(t,{code:E.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Te(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),M(t,{code:E.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),M(t,{code:E.not_finite,message:r.message}),n.dirty()):S.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,B.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,B.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,B.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,B.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:B.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:B.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:B.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:B.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:B.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:B.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`&&S.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)}};Ee.create=e=>new Ee({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...H(e)});var De=class e extends U{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)!==w.bigint)return this._getInvalidInput(e);let t,n=new N;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),M(t,{code:E.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),M(t,{code:E.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),M(t,{code:E.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):S.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.bigint,received:t.parsedType}),P}gte(e,t){return this.setLimit(`min`,e,!0,B.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,B.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,B.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,B.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:B.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:B.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:B.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}};De.create=e=>new De({checks:[],typeName:G.ZodBigInt,coerce:e?.coerce??!1,...H(e)});var Oe=class extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==w.boolean){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.boolean,received:t.parsedType}),P}return I(e.data)}};Oe.create=e=>new Oe({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...H(e)});var ke=class e extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==w.date){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.date,received:t.parsedType}),P}if(Number.isNaN(e.data.getTime())){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_date}),P}let t=new N,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),M(n,{code:E.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),M(n,{code:E.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):S.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:B.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:B.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)}};ke.create=e=>new ke({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...H(e)});var Ae=class extends U{_parse(e){if(this._getType(e)!==w.symbol){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.symbol,received:t.parsedType}),P}return I(e.data)}};Ae.create=e=>new Ae({typeName:G.ZodSymbol,...H(e)});var je=class extends U{_parse(e){if(this._getType(e)!==w.undefined){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.undefined,received:t.parsedType}),P}return I(e.data)}};je.create=e=>new je({typeName:G.ZodUndefined,...H(e)});var Me=class extends U{_parse(e){if(this._getType(e)!==w.null){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.null,received:t.parsedType}),P}return I(e.data)}};Me.create=e=>new Me({typeName:G.ZodNull,...H(e)});var Ne=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return I(e.data)}};Ne.create=e=>new Ne({typeName:G.ZodAny,...H(e)});var Pe=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return I(e.data)}};Pe.create=e=>new Pe({typeName:G.ZodUnknown,...H(e)});var Fe=class extends U{_parse(e){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.never,received:t.parsedType}),P}};Fe.create=e=>new Fe({typeName:G.ZodNever,...H(e)});var Ie=class extends U{_parse(e){if(this._getType(e)!==w.undefined){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.void,received:t.parsedType}),P}return I(e.data)}};Ie.create=e=>new Ie({typeName:G.ZodVoid,...H(e)});var Le=class e extends U{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==w.array)return M(t,{code:E.invalid_type,expected:w.array,received:t.parsedType}),P;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(M(t,{code:e?E.too_big:E.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&&(M(t,{code:E.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&&(M(t,{code:E.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 V(t,e,t.path,n)))).then(e=>N.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new V(t,e,t.path,n)));return N.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:B.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:B.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:B.toString(n)}})}nonempty(e){return this.min(1,e)}};Le.create=(e,t)=>new Le({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...H(t)});function Re(e){if(e instanceof ze){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=rt.create(Re(r))}return new ze({...e._def,shape:()=>t})}else if(e instanceof Le)return new Le({...e._def,type:Re(e.element)});else if(e instanceof rt)return rt.create(Re(e.unwrap()));else if(e instanceof it)return it.create(Re(e.unwrap()));else if(e instanceof Ge)return Ge.create(e.items.map(e=>Re(e)));else return e}var ze=class e extends U{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=S.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==w.object){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.object,received:t.parsedType}),P}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Fe&&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 V(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Fe){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&&(M(n,{code:E.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 V(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=>N.mergeObjectSync(t,e)):N.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return B.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:B.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:G.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 S.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 S.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Re(this)}partial(t){let n={};for(let e of S.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 S.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof rt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Qe(S.objectKeys(this.shape))}};ze.create=(e,t)=>new ze({shape:()=>e,unknownKeys:`strip`,catchall:Fe.create(),typeName:G.ZodObject,...H(t)}),ze.strictCreate=(e,t)=>new ze({shape:()=>e,unknownKeys:`strict`,catchall:Fe.create(),typeName:G.ZodObject,...H(t)}),ze.lazycreate=(e,t)=>new ze({shape:e,unknownKeys:`strip`,catchall:Fe.create(),typeName:G.ZodObject,...H(t)});var Be=class extends U{_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 D(e.ctx.common.issues));return M(t,{code:E.invalid_union,unionErrors:n}),P}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 D(e));return M(t,{code:E.invalid_union,unionErrors:i}),P}}get options(){return this._def.options}};Be.create=(e,t)=>new Be({options:e,typeName:G.ZodUnion,...H(t)});const Ve=e=>e instanceof Xe?Ve(e.schema):e instanceof nt?Ve(e.innerType()):e instanceof Ze?[e.value]:e instanceof $e?e.options:e instanceof et?S.objectValues(e.enum):e instanceof at?Ve(e._def.innerType):e instanceof je?[void 0]:e instanceof Me?[null]:e instanceof rt?[void 0,...Ve(e.unwrap())]:e instanceof it?[null,...Ve(e.unwrap())]:e instanceof ct||e instanceof ut?Ve(e.unwrap()):e instanceof ot?Ve(e._def.innerType):[];var He=class e extends U{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.object)return M(t,{code:E.invalid_type,expected:w.object,received:t.parsedType}),P;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}):(M(t,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),P)}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=Ve(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:G.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...H(r)})}};function Ue(e,t){let n=T(e),r=T(t);if(e===t)return{valid:!0,data:e};if(n===w.object&&r===w.object){let n=S.objectKeys(t),r=S.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Ue(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===w.array&&r===w.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=Ue(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===w.date&&r===w.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var We=class extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ee(e)||ee(r))return P;let i=Ue(e.value,r.value);return i.valid?((L(e)||L(r))&&t.dirty(),{status:t.value,value:i.data}):(M(n,{code:E.invalid_intersection_types}),P)};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}))}};We.create=(e,t,n)=>new We({left:e,right:t,typeName:G.ZodIntersection,...H(n)});var Ge=class e extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.array)return M(n,{code:E.invalid_type,expected:w.array,received:n.parsedType}),P;if(n.data.length<this._def.items.length)return M(n,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),P;!this._def.rest&&n.data.length>this._def.items.length&&(M(n,{code:E.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 V(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>N.mergeArray(t,e)):N.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ge.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Ge({items:e,typeName:G.ZodTuple,rest:null,...H(t)})};var Ke=class e extends U{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!==w.object)return M(n,{code:E.invalid_type,expected:w.object,received:n.parsedType}),P;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new V(n,e,n.path,e)),value:a._parse(new V(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?N.mergeObjectAsync(t,r):N.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof U?new e({keyType:t,valueType:n,typeName:G.ZodRecord,...H(r)}):new e({keyType:we.create(),valueType:t,typeName:G.ZodRecord,...H(n)})}},qe=class extends U{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!==w.map)return M(n,{code:E.invalid_type,expected:w.map,received:n.parsedType}),P;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new V(n,e,n.path,[a,`key`])),value:i._parse(new V(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 P;(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 P;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};qe.create=(e,t,n)=>new qe({valueType:t,keyType:e,typeName:G.ZodMap,...H(n)});var Je=class e extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.set)return M(n,{code:E.invalid_type,expected:w.set,received:n.parsedType}),P;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(M(n,{code:E.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&&(M(n,{code:E.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 P;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 V(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:B.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:B.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Je.create=(e,t)=>new Je({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...H(t)});var Ye=class e extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.function)return M(t,{code:E.invalid_type,expected:w.function,received:t.parsedType}),P;function n(e,n){return j({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,A(),O].filter(e=>!!e),issueData:{code:E.invalid_arguments,argumentsError:n}})}function r(e,n){return j({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,A(),O].filter(e=>!!e),issueData:{code:E.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof tt){let e=this;return I(async function(...t){let o=new D([]),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 I(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new D([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new D([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:Ge.create(t).rest(Pe.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||Ge.create([]).rest(Pe.create()),returns:n||Pe.create(),typeName:G.ZodFunction,...H(r)})}},Xe=class extends U{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})}};Xe.create=(e,t)=>new Xe({getter:e,typeName:G.ZodLazy,...H(t)});var Ze=class extends U{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return M(t,{received:t.data,code:E.invalid_literal,expected:this._def.value}),P}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Ze.create=(e,t)=>new Ze({value:e,typeName:G.ZodLiteral,...H(t)});function Qe(e,t){return new $e({values:e,typeName:G.ZodEnum,...H(t)})}var $e=class e extends U{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return M(t,{expected:S.joinValues(n),received:t.parsedType,code:E.invalid_type}),P}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return M(t,{received:t.data,code:E.invalid_enum_value,options:n}),P}return I(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})}};$e.create=Qe;var et=class extends U{_parse(e){let t=S.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==w.string&&n.parsedType!==w.number){let e=S.objectValues(t);return M(n,{expected:S.joinValues(e),received:n.parsedType,code:E.invalid_type}),P}if(this._cache||=new Set(S.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=S.objectValues(t);return M(n,{received:n.data,code:E.invalid_enum_value,options:e}),P}return I(e.data)}get enum(){return this._def.values}};et.create=(e,t)=>new et({values:e,typeName:G.ZodNativeEnum,...H(t)});var tt=class extends U{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.promise&&t.common.async===!1)return M(t,{code:E.invalid_type,expected:w.promise,received:t.parsedType}),P;let n=t.parsedType===w.promise?t.data:Promise.resolve(t.data);return I(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};tt.create=(e,t)=>new tt({type:e,typeName:G.ZodPromise,...H(t)});var nt=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.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=>{M(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 P;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?P:r.status===`dirty`||t.value===`dirty`?F(r.value):r});{if(t.value===`aborted`)return P;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?P:r.status===`dirty`||t.value===`dirty`?F(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`?P:(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`?P:(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(!R(e))return P;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=>R(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):P);S.assertNever(r)}};nt.create=(e,t,n)=>new nt({schema:e,typeName:G.ZodEffects,effect:t,...H(n)}),nt.createWithPreprocess=(e,t,n)=>new nt({schema:t,effect:{type:`preprocess`,transform:e},typeName:G.ZodEffects,...H(n)});var rt=class extends U{_parse(e){return this._getType(e)===w.undefined?I(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rt.create=(e,t)=>new rt({innerType:e,typeName:G.ZodOptional,...H(t)});var it=class extends U{_parse(e){return this._getType(e)===w.null?I(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(e,t)=>new it({innerType:e,typeName:G.ZodNullable,...H(t)});var at=class extends U{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===w.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};at.create=(e,t)=>new at({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...H(t)});var ot=class extends U{_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 z(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new D(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new D(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ot.create=(e,t)=>new ot({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...H(t)});var st=class extends U{_parse(e){if(this._getType(e)!==w.nan){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.nan,received:t.parsedType}),P}return{status:`valid`,value:e.data}}};st.create=e=>new st({typeName:G.ZodNaN,...H(e)});var ct=class extends U{_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}},lt=class e extends U{_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`?P:e.status===`dirty`?(t.dirty(),F(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`?P: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:G.ZodPipeline})}},ut=class extends U{_parse(e){let t=this._def.innerType._parse(e),n=e=>(R(e)&&(e.value=Object.freeze(e.value)),e);return z(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};ut.create=(e,t)=>new ut({innerType:e,typeName:G.ZodReadonly,...H(t)}),ze.lazycreate;var G;(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`})(G||={});const K=we.create,dt=Ee.create;st.create,De.create;const ft=Oe.create;ke.create,Ae.create,je.create,Me.create;const pt=Ne.create,mt=Pe.create;Fe.create,Ie.create;const q=Le.create,J=ze.create;ze.strictCreate;const ht=Be.create,gt=He.create;We.create,Ge.create;const _t=Ke.create;qe.create,Je.create,Ye.create,Xe.create;const Y=Ze.create,vt=$e.create;et.create,tt.create,nt.create;const X=rt.create;it.create,nt.createWithPreprocess,lt.create;const yt=P,bt=`2025-06-18`,xt=[bt,`2025-03-26`,`2024-11-05`,`2024-10-07`],St=ht([K(),dt().int()]),Ct=K(),wt=J({progressToken:X(St)}).passthrough(),Tt=J({_meta:X(wt)}).passthrough(),Et=J({method:K(),params:X(Tt)}),Dt=J({_meta:X(J({}).passthrough())}).passthrough(),Ot=J({method:K(),params:X(Dt)}),kt=J({_meta:X(J({}).passthrough())}).passthrough(),At=ht([K(),dt().int()]),jt=J({jsonrpc:Y(`2.0`),id:At}).merge(Et).strict(),Mt=e=>jt.safeParse(e).success,Nt=J({jsonrpc:Y(`2.0`)}).merge(Ot).strict(),Pt=e=>Nt.safeParse(e).success,Ft=J({jsonrpc:Y(`2.0`),id:At,result:kt}).strict(),It=e=>Ft.safeParse(e).success;var Lt;(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`})(Lt||={});const Rt=J({jsonrpc:Y(`2.0`),id:At,error:J({code:dt().int(),message:K(),data:X(mt())})}).strict(),zt=e=>Rt.safeParse(e).success,Bt=ht([jt,Nt,Ft,Rt]),Vt=kt.strict(),Ht=Ot.extend({method:Y(`notifications/cancelled`),params:Dt.extend({requestId:At,reason:K().optional()})}),Ut=J({src:K(),mimeType:X(K()),sizes:X(K())}).passthrough(),Wt=J({name:K(),title:X(K())}).passthrough(),Gt=Wt.extend({version:K(),websiteUrl:X(K()),icons:X(q(Ut))}),Kt=J({experimental:X(J({}).passthrough()),sampling:X(J({}).passthrough()),elicitation:X(J({}).passthrough()),roots:X(J({listChanged:X(ft())}).passthrough())}).passthrough(),qt=Et.extend({method:Y(`initialize`),params:Tt.extend({protocolVersion:K(),capabilities:Kt,clientInfo:Gt})}),Jt=e=>qt.safeParse(e).success,Yt=J({experimental:X(J({}).passthrough()),logging:X(J({}).passthrough()),completions:X(J({}).passthrough()),prompts:X(J({listChanged:X(ft())}).passthrough()),resources:X(J({subscribe:X(ft()),listChanged:X(ft())}).passthrough()),tools:X(J({listChanged:X(ft())}).passthrough())}).passthrough(),Xt=kt.extend({protocolVersion:K(),capabilities:Yt,serverInfo:Gt,instructions:X(K())}),Zt=Ot.extend({method:Y(`notifications/initialized`)}),Qt=e=>Zt.safeParse(e).success,$t=Et.extend({method:Y(`ping`)}),en=J({progress:dt(),total:X(dt()),message:X(K())}).passthrough(),tn=Ot.extend({method:Y(`notifications/progress`),params:Dt.merge(en).extend({progressToken:St})}),nn=Et.extend({params:Tt.extend({cursor:X(Ct)}).optional()}),rn=kt.extend({nextCursor:X(Ct)}),an=J({uri:K(),mimeType:X(K()),_meta:X(J({}).passthrough())}).passthrough(),on=an.extend({text:K()}),sn=K().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),cn=an.extend({blob:sn}),ln=Wt.extend({uri:K(),description:X(K()),mimeType:X(K()),icons:X(q(Ut)),_meta:X(J({}).passthrough())}),un=Wt.extend({uriTemplate:K(),description:X(K()),mimeType:X(K()),_meta:X(J({}).passthrough())}),dn=nn.extend({method:Y(`resources/list`)}),fn=rn.extend({resources:q(ln)}),pn=nn.extend({method:Y(`resources/templates/list`)}),mn=rn.extend({resourceTemplates:q(un)}),hn=Et.extend({method:Y(`resources/read`),params:Tt.extend({uri:K()})}),gn=kt.extend({contents:q(ht([on,cn]))}),_n=Ot.extend({method:Y(`notifications/resources/list_changed`)}),vn=Et.extend({method:Y(`resources/subscribe`),params:Tt.extend({uri:K()})}),yn=Et.extend({method:Y(`resources/unsubscribe`),params:Tt.extend({uri:K()})}),bn=Ot.extend({method:Y(`notifications/resources/updated`),params:Dt.extend({uri:K()})}),xn=J({name:K(),description:X(K()),required:X(ft())}).passthrough(),Sn=Wt.extend({description:X(K()),arguments:X(q(xn)),icons:X(q(Ut)),_meta:X(J({}).passthrough())}),Cn=nn.extend({method:Y(`prompts/list`)}),wn=rn.extend({prompts:q(Sn)}),Tn=Et.extend({method:Y(`prompts/get`),params:Tt.extend({name:K(),arguments:X(_t(K()))})}),En=J({type:Y(`text`),text:K(),_meta:X(J({}).passthrough())}).passthrough(),Dn=J({type:Y(`image`),data:sn,mimeType:K(),_meta:X(J({}).passthrough())}).passthrough(),On=J({type:Y(`audio`),data:sn,mimeType:K(),_meta:X(J({}).passthrough())}).passthrough(),kn=J({type:Y(`resource`),resource:ht([on,cn]),_meta:X(J({}).passthrough())}).passthrough(),An=ln.extend({type:Y(`resource_link`)}),jn=ht([En,Dn,On,An,kn]),Mn=J({role:vt([`user`,`assistant`]),content:jn}).passthrough(),Nn=kt.extend({description:X(K()),messages:q(Mn)}),Pn=Ot.extend({method:Y(`notifications/prompts/list_changed`)}),Fn=J({title:X(K()),readOnlyHint:X(ft()),destructiveHint:X(ft()),idempotentHint:X(ft()),openWorldHint:X(ft())}).passthrough(),In=Wt.extend({description:X(K()),inputSchema:J({type:Y(`object`),properties:X(J({}).passthrough()),required:X(q(K()))}).passthrough(),outputSchema:X(J({type:Y(`object`),properties:X(J({}).passthrough()),required:X(q(K()))}).passthrough()),annotations:X(Fn),icons:X(q(Ut)),_meta:X(J({}).passthrough())}),Ln=nn.extend({method:Y(`tools/list`)}),Rn=rn.extend({tools:q(In)}),zn=kt.extend({content:q(jn).default([]),structuredContent:J({}).passthrough().optional(),isError:X(ft())});zn.or(kt.extend({toolResult:mt()}));const Bn=Et.extend({method:Y(`tools/call`),params:Tt.extend({name:K(),arguments:X(_t(mt()))})}),Vn=Ot.extend({method:Y(`notifications/tools/list_changed`)}),Hn=vt([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Un=Et.extend({method:Y(`logging/setLevel`),params:Tt.extend({level:Hn})}),Wn=Ot.extend({method:Y(`notifications/message`),params:Dt.extend({level:Hn,logger:X(K()),data:mt()})}),Gn=J({name:K().optional()}).passthrough(),Kn=J({hints:X(q(Gn)),costPriority:X(dt().min(0).max(1)),speedPriority:X(dt().min(0).max(1)),intelligencePriority:X(dt().min(0).max(1))}).passthrough(),qn=J({role:vt([`user`,`assistant`]),content:ht([En,Dn,On])}).passthrough(),Jn=Et.extend({method:Y(`sampling/createMessage`),params:Tt.extend({messages:q(qn),systemPrompt:X(K()),includeContext:X(vt([`none`,`thisServer`,`allServers`])),temperature:X(dt()),maxTokens:dt().int(),stopSequences:X(q(K())),metadata:X(J({}).passthrough()),modelPreferences:X(Kn)})}),Yn=kt.extend({model:K(),stopReason:X(vt([`endTurn`,`stopSequence`,`maxTokens`]).or(K())),role:vt([`user`,`assistant`]),content:gt(`type`,[En,Dn,On])}),Xn=J({type:Y(`boolean`),title:X(K()),description:X(K()),default:X(ft())}).passthrough(),Zn=J({type:Y(`string`),title:X(K()),description:X(K()),minLength:X(dt()),maxLength:X(dt()),format:X(vt([`email`,`uri`,`date`,`date-time`]))}).passthrough(),Qn=J({type:vt([`number`,`integer`]),title:X(K()),description:X(K()),minimum:X(dt()),maximum:X(dt())}).passthrough(),$n=J({type:Y(`string`),title:X(K()),description:X(K()),enum:q(K()),enumNames:X(q(K()))}).passthrough(),er=ht([Xn,Zn,Qn,$n]),tr=Et.extend({method:Y(`elicitation/create`),params:Tt.extend({message:K(),requestedSchema:J({type:Y(`object`),properties:_t(K(),er),required:X(q(K()))}).passthrough()})}),nr=kt.extend({action:vt([`accept`,`decline`,`cancel`]),content:X(_t(K(),mt()))}),rr=J({type:Y(`ref/resource`),uri:K()}).passthrough(),ir=J({type:Y(`ref/prompt`),name:K()}).passthrough(),ar=Et.extend({method:Y(`completion/complete`),params:Tt.extend({ref:ht([ir,rr]),argument:J({name:K(),value:K()}).passthrough(),context:X(J({arguments:X(_t(K(),K()))}))})}),or=kt.extend({completion:J({values:q(K()).max(100),total:X(dt().int()),hasMore:X(ft())}).passthrough()}),sr=J({uri:K().startsWith(`file://`),name:X(K()),_meta:X(J({}).passthrough())}).passthrough(),cr=Et.extend({method:Y(`roots/list`)}),lr=kt.extend({roots:q(sr)}),ur=Ot.extend({method:Y(`notifications/roots/list_changed`)});ht([$t,qt,ar,Un,Tn,Cn,dn,pn,hn,vn,yn,Bn,Ln]),ht([Ht,tn,Zt,ur]),ht([Vt,Yn,nr,lr]),ht([$t,Jn,tr,cr]),ht([Ht,tn,Wn,bn,_n,Vn,Pn]),ht([Vt,Xt,or,Nn,wn,fn,mn,gn,zn,Rn]);var dr=class extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}},fr=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},pr=class extends fr{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},mr=class extends fr{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},hr=class extends fr{constructor(e,t,n,r={}){super(`HTTPServerError`,e,{feature:`http`,module:`server`,operation:`request`},{endpoint:t,statusCode:n,...r})}},gr=class extends fr{constructor(e,t,n,r={}){super(`ProcessSpawnError`,e,{feature:`stdio`,module:`transport`,operation:`spawn`},{argCount:n?.length,command:t,...r})}},_r=class extends fr{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})}},vr=class extends fr{constructor(e,t,n=`unknown`,r={}){super(`ProxyServerError`,e,{feature:`server`,module:`proxy`,operation:n},{handler:t,...r})}},yr=class extends fr{constructor(e,t=`unknown`,n=`unknown`,r={}){super(`TransportError`,e,{feature:t,module:`transport`,operation:n},r)}};const br={APP_VERSION:`1.0.48`,NODE_ENV:`development`,OAUTH_PROVIDERS:[{authorizationEndpoint:`https://github.com/login/oauth/authorize`,clientId:`Ov23liDj6mzRyvM5n0yG`,id:`github`,name:`GitHub`,tokenEndpoint:`https://github.com/login/oauth/access_token`,urlPatterns:[`github.com`,`api.github.com`,`githubcopilot.com`,`api.githubcopilot.com`],clientSecret:`d467125f345a6edd5de0254a5a9b6bdde26fdd86`,scopes:[`read:user`,`repo`,`gist`,`notifications`,`project`,`public_repo`,`read:gpg_key`,`read:org`,`repo:status`,`repo_deployment`,`user`,`user:email`,`user:follow`],usePkce:!0,tokenEndpointAuthMethod:`client_secret_post`}],SENTRY_DSN:null,SENTRY_ENABLED:!1},xr=u.get,Sr=br.APP_VERSION,Cr=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},wr=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}},Tr=r(),Er=xr(`NODE_ENV`).default(br.NODE_ENV||`development`).asEnum([`development`,`production`,`staging`,`test`]),Dr=xr(`MCP_GATEWAY_SENTRY_DSN`).default(br.SENTRY_DSN||``).asString()||null,Or=xr(`MCP_GATEWAY_SENTRY_ENABLED`).default(String(br.SENTRY_ENABLED??!1)).asBool(),kr=xr(`DEBUG`).default(`false`).asBool()||xr(`MCP_GATEWAY_DEBUG`).default(`false`).asBool(),Ar=xr(`MCP_GATEWAY_SCANNER_URL`).default(``).asString()||null,jr=xr(`MCP_GATEWAY_SCANNER_API_KEY`).default(``).asString()||void 0,Mr=(()=>{let e=xr(`MCP_GATEWAY_SCANNER_HEADERS`).required(!1).asString();return e?Cr(e):{}})(),Nr=xr(`MCP_GATEWAY_SCANNER_TIMEOUT_MS`).default(`20000`).asIntPositive(),Pr=xr(`MCP_GATEWAY_SCANNER_FAIL_OPEN`).default(`true`).asBool(),Fr=xr(`MCP_GATEWAY_COMMAND`).default(`mcp-gateway`).asString(),Ir=xr(`CLIENT_APP_NAME`).default(``).asString(),Lr=xr(`MCP_GATEWAY_LOG_DIR`).default(s(d(),`.onyx`,`mcp-gateway`,`logs`)).asString(),Rr=xr(`MCP_GATEWAY_OAUTH_DIR`).default(s(d(),`.onyx`,`mcp-gateway`,`oauth`)).asString(),zr=(()=>xr(`MCP_GATEWAY_ACCESS_CONTROL_URL`).default(``).asString()||(Ar?wr(Ar):null))(),Br=(()=>{let e=xr(`MCP_GATEWAY_ACCESS_CONTROL_HEADERS`).required(!1).asString();return e?Cr(e):{}})(),Vr=xr(`MCP_GATEWAY_ACCESS_CONTROL_TIMEOUT_MS`).default(`3000`).asIntPositive(),Hr={accessControl:{enabled:!!(zr&&jr),headers:Br,timeoutMs:Vr,url:zr},appVersion:Sr,clientAppName:Ir,debug:kr,environment:Er,logDir:Lr,oauthDir:Rr,proxyCommand:Fr,scanner:{apiKey:jr,enabled:!!Ar,failOpen:Pr,headers:Mr,timeoutMs:Nr,url:Ar},sentry:{debug:kr&&Er===`development`,dsn:Dr||void 0,enabled:Or,environment:Er,release:`mcp-gateway@${Sr}`,tracesSampleRate:Er===`production`?1:0}},Ur=Hr.logDir,Wr=Hr.debug?`debug`:`info`;let Gr=!1;try{i(Ur)||a(Ur,{recursive:!0}),Gr=!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: ${Ur}`),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 Kr=c.format.combine(c.format.timestamp(),c.format.errors({stack:!0}),c.format.json());let qr=null;const Jr=[];if(Gr){let e=new l({datePattern:`YYYY-MM-DD`,filename:s(Ur,`mcp-gateway-%DATE%.log`),format:Kr,handleExceptions:!1,handleRejections:!1,level:Wr,maxFiles:10,maxSize:`10m`});Jr.push(e)}const Yr=c.createLogger({defaultMeta:{service:`mcp-gateway`,version:Hr.appVersion},format:c.format.combine(c.format.errors({stack:!0}),c.format.metadata()),level:Wr,transports:Jr}),Xr=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}},Z={debug:(...e)=>{let{message:t,meta:n,sessionData:r}=Xr(e);Yr.debug(t,{sessionData:r,...n})},error:(...e)=>{let{message:t,meta:n,sessionData:r}=Xr(e);Yr.error(t,{sessionData:r,...n})},getSessionData:()=>qr,info:(...e)=>{let{message:t,meta:n,sessionData:r}=Xr(e);Yr.info(t,{sessionData:r,...n})},setSessionData:e=>{qr=e,Z.debug(`Session data set for logger`,e)},warn:(...e)=>{let{message:t,meta:n,sessionData:r}=Xr(e);Yr.warn(t,{sessionData:r,...n})}};Z.info(`MCP Gateway logger initialized`,{debug:Hr.debug,fileLoggingEnabled:Gr,logDir:Ur,logLevel:Wr});let Zr={"proxy.version":Hr.appVersion};function Qr(e,t=`default`,n=`info`,r){try{if(!Hr.sentry.enabled){Z.debug(`Breadcrumb: [${t}] ${e}`,r);return}m.addBreadcrumb({category:t,data:r?ni(r):void 0,level:n,message:e,timestamp:Date.now()/1e3})}catch(e){Z.warn(`Failed to add breadcrumb to Sentry`,{error:e})}}function $r(e){Zr={...Zr,...e}}function ei(e,t,n){try{let r=e instanceof fr?{...e.tags,...n}:n,i=e instanceof fr?{...e.extra,...t}:t;if(!Hr.sentry.enabled){let t=e instanceof Error?e.message:String(e);Z.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);Z.error(`Sending exception to Sentry: ${a}`,{error:e instanceof Error?e.stack||e.message:e,extra:i,tags:r}),m.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(ni(i)).forEach(([e,n])=>{t.setExtra(e,n)}),t.setLevel(`error`),m.captureException(e)})}catch(e){Z.warn(`Failed to capture exception to Sentry`,{sentryError:e instanceof Error?e.message:e})}}function ti(){try{if(!Hr.sentry.enabled){Z.debug(`Sentry disabled (no DSN provided or in development mode)`);return}m.init({beforeSend(e){return e.tags={...e.tags,...Zr},e.extra&&=ni(e.extra),e.contexts?.runtime?.name&&(e.contexts.runtime.name=`node`),e},beforeSendTransaction(e){return e.tags={...e.tags,...Zr},e},debug:Hr.sentry.debug,dsn:Hr.sentry.dsn,environment:Hr.sentry.environment,release:Hr.sentry.release,tracesSampleRate:Hr.sentry.tracesSampleRate}),Z.debug(`Sentry initialized`,{dsn:Hr.sentry.dsn?`***configured***`:`not configured`,environment:Hr.sentry.environment,release:Hr.sentry.release})}catch(e){Z.warn(`Failed to initialize Sentry, continuing without error tracking`,{error:e})}}function ni(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}let ri=null;const ii=async()=>(ri||=await import(`systeminformation`),ri);function ai(){return s(d(),`.claude.json`)}function oi(){try{return f()}catch{return`unknown-device`}}async function si(e){try{return(await h()).find(t=>t.pid===e)?.name||`unknown`}catch{return`unknown`}}async function ci(){try{let e=(await(await ii()).system()).serial;return e&&e!==``&&e!==`0`&&!e.toLowerCase().includes(`to be filled`)?e:void 0}catch{return}}function li(){try{let e=di();return e?e.oauthAccount.emailAddress:void 0}catch{return}}function ui(){try{let e=p();if(e.username)return e.username;throw Error(`userInfo() returned empty username`)}catch{return process.env.USER||process.env.USERNAME||process.env.LOGNAME}}function di(){try{let e=ai();if(!i(e))return null;let t=o(e,`utf-8`);return JSON.parse(t)}catch{return null}}const fi=async()=>{let e=process.pid,t=process.ppid;try{let n=oi(),[r,i]=await Promise.all([ci(),si(t)]),a=li(),o=ui();return{clientAppName:Ir||`unknown`,deviceName:n,email:a,parentProcessId:t,parentProcessName:i,processId:e,systemSerialNumber:r,username:o}}catch{return{clientAppName:Ir||`unknown`,deviceName:`unknown-device`,email:void 0,parentProcessId:t,parentProcessName:`unknown`,processId:e,systemSerialNumber:void 0,username:void 0}}};function pi(e){let t=g(JSON.stringify(e));return Buffer.from(t).toString(`base64url`)}var mi=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}),Z.info(`Scan result`,{action:t.action,id:e.id,method:e.method,originalRequestId:e.originalRequestId}),t.action===`block`)return Z.warn(`Request blocked by security policy`),t}catch(t){if(Z.error(`Scanning failed`,{error:t}),ei(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 Z.warn(`Scanning service unavailable, blocking traffic (fail-closed)`),{action:`block`};Z.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};Z.info(`Scanning traffic`,{id:e.id,method:e.method,originalRequestId:e.originalRequestId,type:e.type});let n=await this.sendScanRequest(t);return Z.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 pi(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:Tr,...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 hi=null;const gi=async e=>{let t=await fi(),n=e.cliArgs.proxyType,r={...t,proxyType:n,remoteCliArgs:n===`remote`?e.cliArgs:void 0,stdioCliArgs:n===`stdio`?e.cliArgs:void 0};return Z.setSessionData(r),hi=new mi(e,r),hi},_i=()=>hi,vi=e=>e.length>1&&e[1]&&typeof e[1]==`object`&&`requestId`in e[1]?e[1].requestId:void 0,yi=(e,t,n,i)=>async(...a)=>{let o=_i(),s=e,c=a[0],l=r(),u=vi(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(Z.error(`${e} evaluation failed, applying fail-safe`,{error:t}),o?.isScanEnabled()&&!o.scannerConfig?.failOpen)throw Error(`Security scanning service unavailable`);return}if(Z.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`?Z.warn(n):Z.info(n),r.modified_data}if(n){let a=`${e} ${t} by security policy`;i===`warn`?Z.warn(a):Z.info(a),n(r.modified_data);return}return r.modified_data}Z.warn(`${r.action} action without modified_data, allowing original ${e}`)}return}catch(t){if(Z.error(`Unexpected error during ${e} processing`,{error:t}),ei(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(n){if(n instanceof Error&&n.message===`Security scanning service unavailable`){let r=new vr(`Security scanning unavailable (fail-closed)`,e,t,{errorMessage:n.message});throw ei(r),n}Z.error(`Unexpected error during request processing, continuing`,{error:n}),ei(n)}if(f!==void 0)return f;if(i&&!await i.isAllowed()){let n=i.getBlockReason();throw Z.warn(`MCP server blocked by access control`,{handlerName:e,operation:t,reason:n}),new pr(n,`policy_block`)}try{let e=await n(...a);try{if(e){let t=await d(`response`,e);if(t!==void 0)return t}}catch(e){Z.error(`Error during response processing, returning original result`,{error:e}),ei(e)}return e}catch(n){if(n instanceof pr)throw Z.info(`Request blocked by access control`,{error:n.message,handlerName:e,operation:t,reason:n.reason}),n;try{await d(`error`,{error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})}catch(e){Z.warn(`Failed to evaluate error`,{evalError:e})}let r=new vr(`Handler error: ${n}`,e,t,{argsCount:a.length,errorMessage:n instanceof Error?n.message:String(n)});throw ei(r),n}},bi=async({authorizer:e,client:t,server:n,serverCapabilities:r})=>{r?.logging&&(n.setNotificationHandler(Wn,yi(`notifications/message`,`server-to-client`,async e=>t.notification(e),e)),t.setNotificationHandler(Wn,yi(`notifications/message`,`client-to-server`,async e=>n.notification(e),e))),r?.prompts&&(n.setRequestHandler(Tn,yi(`prompts/get`,`get`,async e=>t.getPrompt(e.params),e)),n.setRequestHandler(Cn,yi(`prompts/list`,`list`,async e=>t.listPrompts(e.params),e))),r?.resources&&(n.setRequestHandler(dn,yi(`resources/list`,`list`,async e=>t.listResources(e.params),e)),n.setRequestHandler(pn,yi(`resources/templates/list`,`list`,async e=>t.listResourceTemplates(e.params),e)),n.setRequestHandler(hn,yi(`resources/read`,`read`,async e=>t.readResource(e.params),e)),r?.resources.subscribe&&(n.setNotificationHandler(bn,yi(`notifications/resources/updated`,`notify`,async e=>t.notification(e),e)),n.setRequestHandler(vn,yi(`resources/subscribe`,`subscribe`,async e=>t.subscribeResource(e.params),e)),n.setRequestHandler(yn,yi(`resources/unsubscribe`,`unsubscribe`,async e=>t.unsubscribeResource(e.params),e)))),r?.tools&&(n.setRequestHandler(Bn,yi(`tools/call`,`call`,async e=>t.callTool(e.params),e)),n.setRequestHandler(Ln,yi(`tools/list`,`list`,async e=>t.listTools(e.params),e))),n.setRequestHandler(ar,yi(`completion/complete`,`complete`,async e=>t.complete(e.params),e))};var xi=e(((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)}})),Si=e(((exports,n)=>{
|
|
1
|
+
import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-CrDKVgUD.js";import{randomUUID as r}from"crypto";import{existsSync as i,mkdirSync as a,readFileSync as o}from"node:fs";import{join as s}from"node:path";import c from"winston";import l from"winston-daily-rotate-file";import u from"env-var";import{homedir as d,hostname as f,userInfo as p}from"node:os";import"dotenv/config";import*as m from"@sentry/node";import h from"ps-list";import{deflateSync as g}from"node:zlib";import{randomUUID as _}from"node:crypto";import{URL as v}from"url";import y from"node:http";import b from"node:process";var x=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]:``}},S;(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})(S||={});var C;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(C||={});const w=S.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),T=e=>{switch(typeof e){case`undefined`:return w.undefined;case`string`:return w.string;case`number`:return Number.isNaN(e)?w.nan:w.number;case`boolean`:return w.boolean;case`function`:return w.function;case`bigint`:return w.bigint;case`symbol`:return w.symbol;case`object`:return Array.isArray(e)?w.array:e===null?w.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?w.promise:typeof Map<`u`&&e instanceof Map?w.map:typeof Set<`u`&&e instanceof Set?w.set:typeof Date<`u`&&e instanceof Date?w.date:w.object;default:return w.unknown}},E=S.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 D=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,S.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()}};D.create=e=>new D(e);var O=(e,t)=>{let n;switch(e.code){case E.invalid_type:n=e.received===w.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,S.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${S.joinValues(e.keys,`, `)}`;break;case E.invalid_union:n=`Invalid input`;break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${S.joinValues(e.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${S.joinValues(e.options)}, received '${e.received}'`;break;case E.invalid_arguments:n=`Invalid function arguments`;break;case E.invalid_return_type:n=`Invalid function return type`;break;case E.invalid_date:n=`Invalid date`;break;case E.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}"`:S.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case E.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 E.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 E.custom:n=`Invalid input`;break;case E.invalid_intersection_types:n=`Intersection results could not be merged`;break;case E.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case E.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,S.assertNever(e)}return{message:n}};let k=O;function A(){return k}const j=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 M(e,t){let n=A(),r=j({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===O?void 0:O].filter(e=>!!e)});e.common.issues.push(r)}var N=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 P;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 P;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 P=Object.freeze({status:`aborted`}),F=e=>({status:`dirty`,value:e}),I=e=>({status:`valid`,value:e}),ee=e=>e.status===`aborted`,L=e=>e.status===`dirty`,R=e=>e.status===`valid`,z=e=>typeof Promise<`u`&&e instanceof Promise;var B;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(B||={});var V=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 te=(e,t)=>{if(R(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 D(e.common.issues),this._error}}};function H(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 U=class{get description(){return this._def.description}_getType(e){return T(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:T(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new N,ctx:{common:e.parent.common,data:e.data,parsedType:T(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(z(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:T(e)},r=this._parseSync({data:e,path:n.path,parent:n});return te(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:T(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return R(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=>R(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:T(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(z(r)?r:Promise.resolve(r));return te(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:E.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 nt({schema:this,typeName:G.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 rt.create(this,this._def)}nullable(){return it.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Le.create(this)}promise(){return tt.create(this,this._def)}or(e){return Be.create([this,e],this._def)}and(e){return We.create(this,e,this._def)}transform(e){return new nt({...H(this._def),schema:this,typeName:G.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new at({...H(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new ct({typeName:G.ZodBranded,type:this,...H(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ot({...H(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return lt.create(this,e)}readonly(){return ut.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const ne=/^c[^\s-]{8,}$/i,re=/^[0-9a-z]+$/,W=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ie=/^[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,ae=/^[a-z0-9_-]{21}$/i,oe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,se=/^[-+]?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)?)??$/,ce=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let le;const ue=/^(?:(?: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])$/,de=/^(?:(?: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])$/,fe=/^(([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]))$/,pe=/^(([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])$/,me=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,he=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ge=`((\\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])))`,_e=RegExp(`^${ge}$`);function ve(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 ye(e){return RegExp(`^${ve(e)}$`)}function be(e){let t=`${ge}T${ve(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function xe(e,t){return!!((t===`v4`||!t)&&ue.test(e)||(t===`v6`||!t)&&fe.test(e))}function Se(e,t){if(!oe.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 Ce(e,t){return!!((t===`v4`||!t)&&de.test(e)||(t===`v6`||!t)&&pe.test(e))}var we=class e extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==w.string){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.string,received:t.parsedType}),P}let t=new N,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),M(n,{code:E.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),M(n,{code:E.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?M(n,{code:E.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&M(n,{code:E.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)ce.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`email`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)le||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),le.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`emoji`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ie.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`uuid`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)ae.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`nanoid`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)ne.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`cuid`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)re.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`cuid2`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)W.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`ulid`,code:E.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),M(n,{validation:`url`,code:E.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),M(n,{validation:`regex`,code:E.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),M(n,{code:E.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),M(n,{code:E.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),M(n,{code:E.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?be(r).test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{code:E.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?_e.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{code:E.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?ye(r).test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{code:E.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?se.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`duration`,code:E.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?xe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`ip`,code:E.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Se(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`jwt`,code:E.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Ce(e.data,r.version)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`cidr`,code:E.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?me.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`base64`,code:E.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?he.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`base64url`,code:E.invalid_string,message:r.message}),t.dirty()):S.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:E.invalid_string,...B.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...B.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...B.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...B.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...B.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...B.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...B.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...B.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...B.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...B.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...B.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...B.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,...B.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,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...B.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...B.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...B.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...B.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...B.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...B.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...B.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...B.errToObj(t)})}nonempty(e){return this.min(1,B.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}};we.create=e=>new we({checks:[],typeName:G.ZodString,coerce:e?.coerce??!1,...H(e)});function Te(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 Ee=class e extends U{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)!==w.number){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.number,received:t.parsedType}),P}let t,n=new N;for(let r of this._def.checks)r.kind===`int`?S.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),M(t,{code:E.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),M(t,{code:E.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),M(t,{code:E.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Te(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),M(t,{code:E.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),M(t,{code:E.not_finite,message:r.message}),n.dirty()):S.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,B.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,B.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,B.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,B.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:B.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:B.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:B.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:B.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:B.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:B.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`&&S.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)}};Ee.create=e=>new Ee({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...H(e)});var De=class e extends U{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)!==w.bigint)return this._getInvalidInput(e);let t,n=new N;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),M(t,{code:E.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),M(t,{code:E.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),M(t,{code:E.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):S.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.bigint,received:t.parsedType}),P}gte(e,t){return this.setLimit(`min`,e,!0,B.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,B.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,B.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,B.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:B.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:B.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:B.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}};De.create=e=>new De({checks:[],typeName:G.ZodBigInt,coerce:e?.coerce??!1,...H(e)});var Oe=class extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==w.boolean){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.boolean,received:t.parsedType}),P}return I(e.data)}};Oe.create=e=>new Oe({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...H(e)});var ke=class e extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==w.date){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.date,received:t.parsedType}),P}if(Number.isNaN(e.data.getTime())){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_date}),P}let t=new N,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),M(n,{code:E.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),M(n,{code:E.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):S.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:B.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:B.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)}};ke.create=e=>new ke({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...H(e)});var Ae=class extends U{_parse(e){if(this._getType(e)!==w.symbol){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.symbol,received:t.parsedType}),P}return I(e.data)}};Ae.create=e=>new Ae({typeName:G.ZodSymbol,...H(e)});var je=class extends U{_parse(e){if(this._getType(e)!==w.undefined){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.undefined,received:t.parsedType}),P}return I(e.data)}};je.create=e=>new je({typeName:G.ZodUndefined,...H(e)});var Me=class extends U{_parse(e){if(this._getType(e)!==w.null){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.null,received:t.parsedType}),P}return I(e.data)}};Me.create=e=>new Me({typeName:G.ZodNull,...H(e)});var Ne=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return I(e.data)}};Ne.create=e=>new Ne({typeName:G.ZodAny,...H(e)});var Pe=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return I(e.data)}};Pe.create=e=>new Pe({typeName:G.ZodUnknown,...H(e)});var Fe=class extends U{_parse(e){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.never,received:t.parsedType}),P}};Fe.create=e=>new Fe({typeName:G.ZodNever,...H(e)});var Ie=class extends U{_parse(e){if(this._getType(e)!==w.undefined){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.void,received:t.parsedType}),P}return I(e.data)}};Ie.create=e=>new Ie({typeName:G.ZodVoid,...H(e)});var Le=class e extends U{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==w.array)return M(t,{code:E.invalid_type,expected:w.array,received:t.parsedType}),P;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(M(t,{code:e?E.too_big:E.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&&(M(t,{code:E.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&&(M(t,{code:E.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 V(t,e,t.path,n)))).then(e=>N.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new V(t,e,t.path,n)));return N.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:B.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:B.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:B.toString(n)}})}nonempty(e){return this.min(1,e)}};Le.create=(e,t)=>new Le({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...H(t)});function Re(e){if(e instanceof ze){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=rt.create(Re(r))}return new ze({...e._def,shape:()=>t})}else if(e instanceof Le)return new Le({...e._def,type:Re(e.element)});else if(e instanceof rt)return rt.create(Re(e.unwrap()));else if(e instanceof it)return it.create(Re(e.unwrap()));else if(e instanceof Ge)return Ge.create(e.items.map(e=>Re(e)));else return e}var ze=class e extends U{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=S.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==w.object){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.object,received:t.parsedType}),P}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Fe&&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 V(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Fe){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&&(M(n,{code:E.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 V(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=>N.mergeObjectSync(t,e)):N.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return B.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:B.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:G.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 S.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 S.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Re(this)}partial(t){let n={};for(let e of S.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 S.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof rt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Qe(S.objectKeys(this.shape))}};ze.create=(e,t)=>new ze({shape:()=>e,unknownKeys:`strip`,catchall:Fe.create(),typeName:G.ZodObject,...H(t)}),ze.strictCreate=(e,t)=>new ze({shape:()=>e,unknownKeys:`strict`,catchall:Fe.create(),typeName:G.ZodObject,...H(t)}),ze.lazycreate=(e,t)=>new ze({shape:e,unknownKeys:`strip`,catchall:Fe.create(),typeName:G.ZodObject,...H(t)});var Be=class extends U{_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 D(e.ctx.common.issues));return M(t,{code:E.invalid_union,unionErrors:n}),P}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 D(e));return M(t,{code:E.invalid_union,unionErrors:i}),P}}get options(){return this._def.options}};Be.create=(e,t)=>new Be({options:e,typeName:G.ZodUnion,...H(t)});const Ve=e=>e instanceof Xe?Ve(e.schema):e instanceof nt?Ve(e.innerType()):e instanceof Ze?[e.value]:e instanceof $e?e.options:e instanceof et?S.objectValues(e.enum):e instanceof at?Ve(e._def.innerType):e instanceof je?[void 0]:e instanceof Me?[null]:e instanceof rt?[void 0,...Ve(e.unwrap())]:e instanceof it?[null,...Ve(e.unwrap())]:e instanceof ct||e instanceof ut?Ve(e.unwrap()):e instanceof ot?Ve(e._def.innerType):[];var He=class e extends U{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.object)return M(t,{code:E.invalid_type,expected:w.object,received:t.parsedType}),P;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}):(M(t,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),P)}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=Ve(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:G.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...H(r)})}};function Ue(e,t){let n=T(e),r=T(t);if(e===t)return{valid:!0,data:e};if(n===w.object&&r===w.object){let n=S.objectKeys(t),r=S.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Ue(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===w.array&&r===w.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=Ue(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===w.date&&r===w.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var We=class extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ee(e)||ee(r))return P;let i=Ue(e.value,r.value);return i.valid?((L(e)||L(r))&&t.dirty(),{status:t.value,value:i.data}):(M(n,{code:E.invalid_intersection_types}),P)};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}))}};We.create=(e,t,n)=>new We({left:e,right:t,typeName:G.ZodIntersection,...H(n)});var Ge=class e extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.array)return M(n,{code:E.invalid_type,expected:w.array,received:n.parsedType}),P;if(n.data.length<this._def.items.length)return M(n,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),P;!this._def.rest&&n.data.length>this._def.items.length&&(M(n,{code:E.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 V(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>N.mergeArray(t,e)):N.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ge.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Ge({items:e,typeName:G.ZodTuple,rest:null,...H(t)})};var Ke=class e extends U{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!==w.object)return M(n,{code:E.invalid_type,expected:w.object,received:n.parsedType}),P;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new V(n,e,n.path,e)),value:a._parse(new V(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?N.mergeObjectAsync(t,r):N.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof U?new e({keyType:t,valueType:n,typeName:G.ZodRecord,...H(r)}):new e({keyType:we.create(),valueType:t,typeName:G.ZodRecord,...H(n)})}},qe=class extends U{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!==w.map)return M(n,{code:E.invalid_type,expected:w.map,received:n.parsedType}),P;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new V(n,e,n.path,[a,`key`])),value:i._parse(new V(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 P;(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 P;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};qe.create=(e,t,n)=>new qe({valueType:t,keyType:e,typeName:G.ZodMap,...H(n)});var Je=class e extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.set)return M(n,{code:E.invalid_type,expected:w.set,received:n.parsedType}),P;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(M(n,{code:E.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&&(M(n,{code:E.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 P;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 V(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:B.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:B.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Je.create=(e,t)=>new Je({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...H(t)});var Ye=class e extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.function)return M(t,{code:E.invalid_type,expected:w.function,received:t.parsedType}),P;function n(e,n){return j({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,A(),O].filter(e=>!!e),issueData:{code:E.invalid_arguments,argumentsError:n}})}function r(e,n){return j({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,A(),O].filter(e=>!!e),issueData:{code:E.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof tt){let e=this;return I(async function(...t){let o=new D([]),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 I(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new D([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new D([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:Ge.create(t).rest(Pe.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||Ge.create([]).rest(Pe.create()),returns:n||Pe.create(),typeName:G.ZodFunction,...H(r)})}},Xe=class extends U{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})}};Xe.create=(e,t)=>new Xe({getter:e,typeName:G.ZodLazy,...H(t)});var Ze=class extends U{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return M(t,{received:t.data,code:E.invalid_literal,expected:this._def.value}),P}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Ze.create=(e,t)=>new Ze({value:e,typeName:G.ZodLiteral,...H(t)});function Qe(e,t){return new $e({values:e,typeName:G.ZodEnum,...H(t)})}var $e=class e extends U{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return M(t,{expected:S.joinValues(n),received:t.parsedType,code:E.invalid_type}),P}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return M(t,{received:t.data,code:E.invalid_enum_value,options:n}),P}return I(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})}};$e.create=Qe;var et=class extends U{_parse(e){let t=S.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==w.string&&n.parsedType!==w.number){let e=S.objectValues(t);return M(n,{expected:S.joinValues(e),received:n.parsedType,code:E.invalid_type}),P}if(this._cache||=new Set(S.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=S.objectValues(t);return M(n,{received:n.data,code:E.invalid_enum_value,options:e}),P}return I(e.data)}get enum(){return this._def.values}};et.create=(e,t)=>new et({values:e,typeName:G.ZodNativeEnum,...H(t)});var tt=class extends U{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.promise&&t.common.async===!1)return M(t,{code:E.invalid_type,expected:w.promise,received:t.parsedType}),P;let n=t.parsedType===w.promise?t.data:Promise.resolve(t.data);return I(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};tt.create=(e,t)=>new tt({type:e,typeName:G.ZodPromise,...H(t)});var nt=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.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=>{M(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 P;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?P:r.status===`dirty`||t.value===`dirty`?F(r.value):r});{if(t.value===`aborted`)return P;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?P:r.status===`dirty`||t.value===`dirty`?F(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`?P:(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`?P:(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(!R(e))return P;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=>R(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):P);S.assertNever(r)}};nt.create=(e,t,n)=>new nt({schema:e,typeName:G.ZodEffects,effect:t,...H(n)}),nt.createWithPreprocess=(e,t,n)=>new nt({schema:t,effect:{type:`preprocess`,transform:e},typeName:G.ZodEffects,...H(n)});var rt=class extends U{_parse(e){return this._getType(e)===w.undefined?I(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rt.create=(e,t)=>new rt({innerType:e,typeName:G.ZodOptional,...H(t)});var it=class extends U{_parse(e){return this._getType(e)===w.null?I(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(e,t)=>new it({innerType:e,typeName:G.ZodNullable,...H(t)});var at=class extends U{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===w.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};at.create=(e,t)=>new at({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...H(t)});var ot=class extends U{_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 z(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new D(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new D(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ot.create=(e,t)=>new ot({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...H(t)});var st=class extends U{_parse(e){if(this._getType(e)!==w.nan){let t=this._getOrReturnCtx(e);return M(t,{code:E.invalid_type,expected:w.nan,received:t.parsedType}),P}return{status:`valid`,value:e.data}}};st.create=e=>new st({typeName:G.ZodNaN,...H(e)});var ct=class extends U{_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}},lt=class e extends U{_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`?P:e.status===`dirty`?(t.dirty(),F(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`?P: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:G.ZodPipeline})}},ut=class extends U{_parse(e){let t=this._def.innerType._parse(e),n=e=>(R(e)&&(e.value=Object.freeze(e.value)),e);return z(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};ut.create=(e,t)=>new ut({innerType:e,typeName:G.ZodReadonly,...H(t)}),ze.lazycreate;var G;(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`})(G||={});const K=we.create,dt=Ee.create;st.create,De.create;const ft=Oe.create;ke.create,Ae.create,je.create,Me.create;const pt=Ne.create,mt=Pe.create;Fe.create,Ie.create;const q=Le.create,J=ze.create;ze.strictCreate;const ht=Be.create,gt=He.create;We.create,Ge.create;const _t=Ke.create;qe.create,Je.create,Ye.create,Xe.create;const Y=Ze.create,vt=$e.create;et.create,tt.create,nt.create;const X=rt.create;it.create,nt.createWithPreprocess,lt.create;const yt=P,bt=`2025-06-18`,xt=[bt,`2025-03-26`,`2024-11-05`,`2024-10-07`],St=ht([K(),dt().int()]),Ct=K(),wt=J({progressToken:X(St)}).passthrough(),Tt=J({_meta:X(wt)}).passthrough(),Et=J({method:K(),params:X(Tt)}),Dt=J({_meta:X(J({}).passthrough())}).passthrough(),Ot=J({method:K(),params:X(Dt)}),kt=J({_meta:X(J({}).passthrough())}).passthrough(),At=ht([K(),dt().int()]),jt=J({jsonrpc:Y(`2.0`),id:At}).merge(Et).strict(),Mt=e=>jt.safeParse(e).success,Nt=J({jsonrpc:Y(`2.0`)}).merge(Ot).strict(),Pt=e=>Nt.safeParse(e).success,Ft=J({jsonrpc:Y(`2.0`),id:At,result:kt}).strict(),It=e=>Ft.safeParse(e).success;var Lt;(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`})(Lt||={});const Rt=J({jsonrpc:Y(`2.0`),id:At,error:J({code:dt().int(),message:K(),data:X(mt())})}).strict(),zt=e=>Rt.safeParse(e).success,Bt=ht([jt,Nt,Ft,Rt]),Vt=kt.strict(),Ht=Ot.extend({method:Y(`notifications/cancelled`),params:Dt.extend({requestId:At,reason:K().optional()})}),Ut=J({src:K(),mimeType:X(K()),sizes:X(K())}).passthrough(),Wt=J({name:K(),title:X(K())}).passthrough(),Gt=Wt.extend({version:K(),websiteUrl:X(K()),icons:X(q(Ut))}),Kt=J({experimental:X(J({}).passthrough()),sampling:X(J({}).passthrough()),elicitation:X(J({}).passthrough()),roots:X(J({listChanged:X(ft())}).passthrough())}).passthrough(),qt=Et.extend({method:Y(`initialize`),params:Tt.extend({protocolVersion:K(),capabilities:Kt,clientInfo:Gt})}),Jt=e=>qt.safeParse(e).success,Yt=J({experimental:X(J({}).passthrough()),logging:X(J({}).passthrough()),completions:X(J({}).passthrough()),prompts:X(J({listChanged:X(ft())}).passthrough()),resources:X(J({subscribe:X(ft()),listChanged:X(ft())}).passthrough()),tools:X(J({listChanged:X(ft())}).passthrough())}).passthrough(),Xt=kt.extend({protocolVersion:K(),capabilities:Yt,serverInfo:Gt,instructions:X(K())}),Zt=Ot.extend({method:Y(`notifications/initialized`)}),Qt=e=>Zt.safeParse(e).success,$t=Et.extend({method:Y(`ping`)}),en=J({progress:dt(),total:X(dt()),message:X(K())}).passthrough(),tn=Ot.extend({method:Y(`notifications/progress`),params:Dt.merge(en).extend({progressToken:St})}),nn=Et.extend({params:Tt.extend({cursor:X(Ct)}).optional()}),rn=kt.extend({nextCursor:X(Ct)}),an=J({uri:K(),mimeType:X(K()),_meta:X(J({}).passthrough())}).passthrough(),on=an.extend({text:K()}),sn=K().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),cn=an.extend({blob:sn}),ln=Wt.extend({uri:K(),description:X(K()),mimeType:X(K()),icons:X(q(Ut)),_meta:X(J({}).passthrough())}),un=Wt.extend({uriTemplate:K(),description:X(K()),mimeType:X(K()),_meta:X(J({}).passthrough())}),dn=nn.extend({method:Y(`resources/list`)}),fn=rn.extend({resources:q(ln)}),pn=nn.extend({method:Y(`resources/templates/list`)}),mn=rn.extend({resourceTemplates:q(un)}),hn=Et.extend({method:Y(`resources/read`),params:Tt.extend({uri:K()})}),gn=kt.extend({contents:q(ht([on,cn]))}),_n=Ot.extend({method:Y(`notifications/resources/list_changed`)}),vn=Et.extend({method:Y(`resources/subscribe`),params:Tt.extend({uri:K()})}),yn=Et.extend({method:Y(`resources/unsubscribe`),params:Tt.extend({uri:K()})}),bn=Ot.extend({method:Y(`notifications/resources/updated`),params:Dt.extend({uri:K()})}),xn=J({name:K(),description:X(K()),required:X(ft())}).passthrough(),Sn=Wt.extend({description:X(K()),arguments:X(q(xn)),icons:X(q(Ut)),_meta:X(J({}).passthrough())}),Cn=nn.extend({method:Y(`prompts/list`)}),wn=rn.extend({prompts:q(Sn)}),Tn=Et.extend({method:Y(`prompts/get`),params:Tt.extend({name:K(),arguments:X(_t(K()))})}),En=J({type:Y(`text`),text:K(),_meta:X(J({}).passthrough())}).passthrough(),Dn=J({type:Y(`image`),data:sn,mimeType:K(),_meta:X(J({}).passthrough())}).passthrough(),On=J({type:Y(`audio`),data:sn,mimeType:K(),_meta:X(J({}).passthrough())}).passthrough(),kn=J({type:Y(`resource`),resource:ht([on,cn]),_meta:X(J({}).passthrough())}).passthrough(),An=ln.extend({type:Y(`resource_link`)}),jn=ht([En,Dn,On,An,kn]),Mn=J({role:vt([`user`,`assistant`]),content:jn}).passthrough(),Nn=kt.extend({description:X(K()),messages:q(Mn)}),Pn=Ot.extend({method:Y(`notifications/prompts/list_changed`)}),Fn=J({title:X(K()),readOnlyHint:X(ft()),destructiveHint:X(ft()),idempotentHint:X(ft()),openWorldHint:X(ft())}).passthrough(),In=Wt.extend({description:X(K()),inputSchema:J({type:Y(`object`),properties:X(J({}).passthrough()),required:X(q(K()))}).passthrough(),outputSchema:X(J({type:Y(`object`),properties:X(J({}).passthrough()),required:X(q(K()))}).passthrough()),annotations:X(Fn),icons:X(q(Ut)),_meta:X(J({}).passthrough())}),Ln=nn.extend({method:Y(`tools/list`)}),Rn=rn.extend({tools:q(In)}),zn=kt.extend({content:q(jn).default([]),structuredContent:J({}).passthrough().optional(),isError:X(ft())});zn.or(kt.extend({toolResult:mt()}));const Bn=Et.extend({method:Y(`tools/call`),params:Tt.extend({name:K(),arguments:X(_t(mt()))})}),Vn=Ot.extend({method:Y(`notifications/tools/list_changed`)}),Hn=vt([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Un=Et.extend({method:Y(`logging/setLevel`),params:Tt.extend({level:Hn})}),Wn=Ot.extend({method:Y(`notifications/message`),params:Dt.extend({level:Hn,logger:X(K()),data:mt()})}),Gn=J({name:K().optional()}).passthrough(),Kn=J({hints:X(q(Gn)),costPriority:X(dt().min(0).max(1)),speedPriority:X(dt().min(0).max(1)),intelligencePriority:X(dt().min(0).max(1))}).passthrough(),qn=J({role:vt([`user`,`assistant`]),content:ht([En,Dn,On])}).passthrough(),Jn=Et.extend({method:Y(`sampling/createMessage`),params:Tt.extend({messages:q(qn),systemPrompt:X(K()),includeContext:X(vt([`none`,`thisServer`,`allServers`])),temperature:X(dt()),maxTokens:dt().int(),stopSequences:X(q(K())),metadata:X(J({}).passthrough()),modelPreferences:X(Kn)})}),Yn=kt.extend({model:K(),stopReason:X(vt([`endTurn`,`stopSequence`,`maxTokens`]).or(K())),role:vt([`user`,`assistant`]),content:gt(`type`,[En,Dn,On])}),Xn=J({type:Y(`boolean`),title:X(K()),description:X(K()),default:X(ft())}).passthrough(),Zn=J({type:Y(`string`),title:X(K()),description:X(K()),minLength:X(dt()),maxLength:X(dt()),format:X(vt([`email`,`uri`,`date`,`date-time`]))}).passthrough(),Qn=J({type:vt([`number`,`integer`]),title:X(K()),description:X(K()),minimum:X(dt()),maximum:X(dt())}).passthrough(),$n=J({type:Y(`string`),title:X(K()),description:X(K()),enum:q(K()),enumNames:X(q(K()))}).passthrough(),er=ht([Xn,Zn,Qn,$n]),tr=Et.extend({method:Y(`elicitation/create`),params:Tt.extend({message:K(),requestedSchema:J({type:Y(`object`),properties:_t(K(),er),required:X(q(K()))}).passthrough()})}),nr=kt.extend({action:vt([`accept`,`decline`,`cancel`]),content:X(_t(K(),mt()))}),rr=J({type:Y(`ref/resource`),uri:K()}).passthrough(),ir=J({type:Y(`ref/prompt`),name:K()}).passthrough(),ar=Et.extend({method:Y(`completion/complete`),params:Tt.extend({ref:ht([ir,rr]),argument:J({name:K(),value:K()}).passthrough(),context:X(J({arguments:X(_t(K(),K()))}))})}),or=kt.extend({completion:J({values:q(K()).max(100),total:X(dt().int()),hasMore:X(ft())}).passthrough()}),sr=J({uri:K().startsWith(`file://`),name:X(K()),_meta:X(J({}).passthrough())}).passthrough(),cr=Et.extend({method:Y(`roots/list`)}),lr=kt.extend({roots:q(sr)}),ur=Ot.extend({method:Y(`notifications/roots/list_changed`)});ht([$t,qt,ar,Un,Tn,Cn,dn,pn,hn,vn,yn,Bn,Ln]),ht([Ht,tn,Zt,ur]),ht([Vt,Yn,nr,lr]),ht([$t,Jn,tr,cr]),ht([Ht,tn,Wn,bn,_n,Vn,Pn]),ht([Vt,Xt,or,Nn,wn,fn,mn,gn,zn,Rn]);var dr=class extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}},fr=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},pr=class extends fr{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},mr=class extends fr{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},hr=class extends fr{constructor(e,t,n,r={}){super(`HTTPServerError`,e,{feature:`http`,module:`server`,operation:`request`},{endpoint:t,statusCode:n,...r})}},gr=class extends fr{constructor(e,t,n,r={}){super(`ProcessSpawnError`,e,{feature:`stdio`,module:`transport`,operation:`spawn`},{argCount:n?.length,command:t,...r})}},_r=class extends fr{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})}},vr=class extends fr{constructor(e,t,n=`unknown`,r={}){super(`ProxyServerError`,e,{feature:`server`,module:`proxy`,operation:n},{handler:t,...r})}},yr=class extends fr{constructor(e,t=`unknown`,n=`unknown`,r={}){super(`TransportError`,e,{feature:t,module:`transport`,operation:n},r)}};const br={APP_VERSION:`1.0.49`,NODE_ENV:`development`,OAUTH_PROVIDERS:[{authorizationEndpoint:`https://github.com/login/oauth/authorize`,clientId:`Ov23liDj6mzRyvM5n0yG`,id:`github`,name:`GitHub`,tokenEndpoint:`https://github.com/login/oauth/access_token`,urlPatterns:[`github.com`,`api.github.com`,`githubcopilot.com`,`api.githubcopilot.com`],clientSecret:`d467125f345a6edd5de0254a5a9b6bdde26fdd86`,scopes:[`read:user`,`repo`,`gist`,`notifications`,`project`,`public_repo`,`read:gpg_key`,`read:org`,`repo:status`,`repo_deployment`,`user`,`user:email`,`user:follow`],usePkce:!0,tokenEndpointAuthMethod:`client_secret_post`}],SENTRY_DSN:null,SENTRY_ENABLED:!1},xr=u.get,Sr=br.APP_VERSION,Cr=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},wr=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}},Tr=r(),Er=xr(`NODE_ENV`).default(br.NODE_ENV||`development`).asEnum([`development`,`production`,`staging`,`test`]),Dr=xr(`MCP_GATEWAY_SENTRY_DSN`).default(br.SENTRY_DSN||``).asString()||null,Or=xr(`MCP_GATEWAY_SENTRY_ENABLED`).default(String(br.SENTRY_ENABLED??!1)).asBool(),kr=xr(`DEBUG`).default(`false`).asBool()||xr(`MCP_GATEWAY_DEBUG`).default(`false`).asBool(),Ar=xr(`MCP_GATEWAY_SCANNER_URL`).default(``).asString()||null,jr=xr(`MCP_GATEWAY_SCANNER_API_KEY`).default(``).asString()||void 0,Mr=(()=>{let e=xr(`MCP_GATEWAY_SCANNER_HEADERS`).required(!1).asString();return e?Cr(e):{}})(),Nr=xr(`MCP_GATEWAY_SCANNER_TIMEOUT_MS`).default(`20000`).asIntPositive(),Pr=xr(`MCP_GATEWAY_SCANNER_FAIL_OPEN`).default(`true`).asBool(),Fr=xr(`MCP_GATEWAY_COMMAND`).default(`mcp-gateway`).asString(),Ir=xr(`CLIENT_APP_NAME`).default(``).asString(),Lr=xr(`MCP_GATEWAY_LOG_DIR`).default(s(d(),`.onyx`,`mcp-gateway`,`logs`)).asString(),Rr=xr(`MCP_GATEWAY_OAUTH_DIR`).default(s(d(),`.onyx`,`mcp-gateway`,`oauth`)).asString(),zr=(()=>xr(`MCP_GATEWAY_ACCESS_CONTROL_URL`).default(``).asString()||(Ar?wr(Ar):null))(),Br=(()=>{let e=xr(`MCP_GATEWAY_ACCESS_CONTROL_HEADERS`).required(!1).asString();return e?Cr(e):{}})(),Vr=xr(`MCP_GATEWAY_ACCESS_CONTROL_TIMEOUT_MS`).default(`3000`).asIntPositive(),Hr={accessControl:{enabled:!!(zr&&jr),headers:Br,timeoutMs:Vr,url:zr},appVersion:Sr,clientAppName:Ir,debug:kr,environment:Er,logDir:Lr,oauthDir:Rr,proxyCommand:Fr,scanner:{apiKey:jr,enabled:!!Ar,failOpen:Pr,headers:Mr,timeoutMs:Nr,url:Ar},sentry:{debug:kr&&Er===`development`,dsn:Dr||void 0,enabled:Or,environment:Er,release:`mcp-gateway@${Sr}`,tracesSampleRate:Er===`production`?1:0}},Ur=Hr.logDir,Wr=Hr.debug?`debug`:`info`;let Gr=!1;try{i(Ur)||a(Ur,{recursive:!0}),Gr=!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: ${Ur}`),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 Kr=c.format.combine(c.format.timestamp(),c.format.errors({stack:!0}),c.format.json());let qr=null;const Jr=[];if(Gr){let e=new l({datePattern:`YYYY-MM-DD`,filename:s(Ur,`mcp-gateway-%DATE%.log`),format:Kr,handleExceptions:!1,handleRejections:!1,level:Wr,maxFiles:10,maxSize:`10m`});Jr.push(e)}const Yr=c.createLogger({defaultMeta:{service:`mcp-gateway`,version:Hr.appVersion},format:c.format.combine(c.format.errors({stack:!0}),c.format.metadata()),level:Wr,transports:Jr}),Xr=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}},Z={debug:(...e)=>{let{message:t,meta:n,sessionData:r}=Xr(e);Yr.debug(t,{sessionData:r,...n})},error:(...e)=>{let{message:t,meta:n,sessionData:r}=Xr(e);Yr.error(t,{sessionData:r,...n})},getSessionData:()=>qr,info:(...e)=>{let{message:t,meta:n,sessionData:r}=Xr(e);Yr.info(t,{sessionData:r,...n})},setSessionData:e=>{qr=e,Z.debug(`Session data set for logger`,e)},warn:(...e)=>{let{message:t,meta:n,sessionData:r}=Xr(e);Yr.warn(t,{sessionData:r,...n})}};Z.info(`MCP Gateway logger initialized`,{debug:Hr.debug,fileLoggingEnabled:Gr,logDir:Ur,logLevel:Wr});let Zr={"proxy.version":Hr.appVersion};function Qr(e,t=`default`,n=`info`,r){try{if(!Hr.sentry.enabled){Z.debug(`Breadcrumb: [${t}] ${e}`,r);return}m.addBreadcrumb({category:t,data:r?ni(r):void 0,level:n,message:e,timestamp:Date.now()/1e3})}catch(e){Z.warn(`Failed to add breadcrumb to Sentry`,{error:e})}}function $r(e){Zr={...Zr,...e}}function ei(e,t,n){try{let r=e instanceof fr?{...e.tags,...n}:n,i=e instanceof fr?{...e.extra,...t}:t;if(!Hr.sentry.enabled){let t=e instanceof Error?e.message:String(e);Z.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);Z.error(`Sending exception to Sentry: ${a}`,{error:e instanceof Error?e.stack||e.message:e,extra:i,tags:r}),m.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(ni(i)).forEach(([e,n])=>{t.setExtra(e,n)}),t.setLevel(`error`),m.captureException(e)})}catch(e){Z.warn(`Failed to capture exception to Sentry`,{sentryError:e instanceof Error?e.message:e})}}function ti(){try{if(!Hr.sentry.enabled){Z.debug(`Sentry disabled (no DSN provided or in development mode)`);return}m.init({beforeSend(e){return e.tags={...e.tags,...Zr},e.extra&&=ni(e.extra),e.contexts?.runtime?.name&&(e.contexts.runtime.name=`node`),e},beforeSendTransaction(e){return e.tags={...e.tags,...Zr},e},debug:Hr.sentry.debug,dsn:Hr.sentry.dsn,environment:Hr.sentry.environment,release:Hr.sentry.release,tracesSampleRate:Hr.sentry.tracesSampleRate}),Z.debug(`Sentry initialized`,{dsn:Hr.sentry.dsn?`***configured***`:`not configured`,environment:Hr.sentry.environment,release:Hr.sentry.release})}catch(e){Z.warn(`Failed to initialize Sentry, continuing without error tracking`,{error:e})}}function ni(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}let ri=null;const ii=async()=>(ri||=await import(`systeminformation`),ri);function ai(){return s(d(),`.claude.json`)}function oi(){try{return f()}catch{return`unknown-device`}}async function si(e){try{return(await h()).find(t=>t.pid===e)?.name||`unknown`}catch{return`unknown`}}async function ci(){try{let e=(await(await ii()).system()).serial;return e&&e!==``&&e!==`0`&&!e.toLowerCase().includes(`to be filled`)?e:void 0}catch{return}}function li(){try{let e=di();return e?e.oauthAccount.emailAddress:void 0}catch{return}}function ui(){try{let e=p();if(e.username)return e.username;throw Error(`userInfo() returned empty username`)}catch{return process.env.USER||process.env.USERNAME||process.env.LOGNAME}}function di(){try{let e=ai();if(!i(e))return null;let t=o(e,`utf-8`);return JSON.parse(t)}catch{return null}}const fi=async()=>{let e=process.pid,t=process.ppid;try{let n=oi(),[r,i]=await Promise.all([ci(),si(t)]),a=li(),o=ui();return{clientAppName:Ir||`unknown`,deviceName:n,email:a,parentProcessId:t,parentProcessName:i,processId:e,systemSerialNumber:r,username:o}}catch{return{clientAppName:Ir||`unknown`,deviceName:`unknown-device`,email:void 0,parentProcessId:t,parentProcessName:`unknown`,processId:e,systemSerialNumber:void 0,username:void 0}}};function pi(e){let t=g(JSON.stringify(e));return Buffer.from(t).toString(`base64url`)}var mi=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}),Z.info(`Scan result`,{action:t.action,id:e.id,method:e.method,originalRequestId:e.originalRequestId}),t.action===`block`)return Z.warn(`Request blocked by security policy`),t}catch(t){if(Z.error(`Scanning failed`,{error:t}),ei(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 Z.warn(`Scanning service unavailable, blocking traffic (fail-closed)`),{action:`block`};Z.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};Z.info(`Scanning traffic`,{id:e.id,method:e.method,originalRequestId:e.originalRequestId,type:e.type});let n=await this.sendScanRequest(t);return Z.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 pi(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:Tr,...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 hi=null;const gi=async e=>{let t=await fi(),n=e.cliArgs.proxyType,r={...t,proxyType:n,remoteCliArgs:n===`remote`?e.cliArgs:void 0,stdioCliArgs:n===`stdio`?e.cliArgs:void 0};return Z.setSessionData(r),hi=new mi(e,r),hi},_i=()=>hi,vi=e=>e.length>1&&e[1]&&typeof e[1]==`object`&&`requestId`in e[1]?e[1].requestId:void 0,yi=(e,t,n,i)=>async(...a)=>{let o=_i(),s=e,c=a[0],l=r(),u=vi(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(Z.error(`${e} evaluation failed, applying fail-safe`,{error:t}),o?.isScanEnabled()&&!o.scannerConfig?.failOpen)throw Error(`Security scanning service unavailable`);return}if(Z.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`?Z.warn(n):Z.info(n),r.modified_data}if(n){let a=`${e} ${t} by security policy`;i===`warn`?Z.warn(a):Z.info(a),n(r.modified_data);return}return r.modified_data}Z.warn(`${r.action} action without modified_data, allowing original ${e}`)}return}catch(t){if(Z.error(`Unexpected error during ${e} processing`,{error:t}),ei(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(n){if(n instanceof Error&&n.message===`Security scanning service unavailable`){let r=new vr(`Security scanning unavailable (fail-closed)`,e,t,{errorMessage:n.message});throw ei(r),n}Z.error(`Unexpected error during request processing, continuing`,{error:n}),ei(n)}if(f!==void 0)return f;if(i&&!await i.isAllowed()){let n=i.getBlockReason();throw Z.warn(`MCP server blocked by access control`,{handlerName:e,operation:t,reason:n}),new pr(n,`policy_block`)}try{let e=await n(...a);try{if(e){let t=await d(`response`,e);if(t!==void 0)return t}}catch(e){Z.error(`Error during response processing, returning original result`,{error:e}),ei(e)}return e}catch(n){if(n instanceof pr)throw Z.info(`Request blocked by access control`,{error:n.message,handlerName:e,operation:t,reason:n.reason}),n;try{await d(`error`,{error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})}catch(e){Z.warn(`Failed to evaluate error`,{evalError:e})}let r=new vr(`Handler error: ${n}`,e,t,{argsCount:a.length,errorMessage:n instanceof Error?n.message:String(n)});throw ei(r),n}},bi=async({authorizer:e,client:t,server:n,serverCapabilities:r})=>{r?.logging&&(n.setNotificationHandler(Wn,yi(`notifications/message`,`server-to-client`,async e=>t.notification(e),e)),t.setNotificationHandler(Wn,yi(`notifications/message`,`client-to-server`,async e=>n.notification(e),e))),r?.prompts&&(n.setRequestHandler(Tn,yi(`prompts/get`,`get`,async e=>t.getPrompt(e.params),e)),n.setRequestHandler(Cn,yi(`prompts/list`,`list`,async e=>t.listPrompts(e.params),e))),r?.resources&&(n.setRequestHandler(dn,yi(`resources/list`,`list`,async e=>t.listResources(e.params),e)),n.setRequestHandler(pn,yi(`resources/templates/list`,`list`,async e=>t.listResourceTemplates(e.params),e)),n.setRequestHandler(hn,yi(`resources/read`,`read`,async e=>t.readResource(e.params),e)),r?.resources.subscribe&&(n.setNotificationHandler(bn,yi(`notifications/resources/updated`,`notify`,async e=>t.notification(e),e)),n.setRequestHandler(vn,yi(`resources/subscribe`,`subscribe`,async e=>t.subscribeResource(e.params),e)),n.setRequestHandler(yn,yi(`resources/unsubscribe`,`unsubscribe`,async e=>t.unsubscribeResource(e.params),e)))),r?.tools&&(n.setRequestHandler(Bn,yi(`tools/call`,`call`,async e=>t.callTool(e.params),e)),n.setRequestHandler(Ln,yi(`tools/list`,`list`,async e=>t.listTools(e.params),e))),n.setRequestHandler(ar,yi(`completion/complete`,`complete`,async e=>t.complete(e.params),e))};var xi=e(((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)}})),Si=e(((exports,n)=>{
|
|
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 go=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(yo(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(yo(this),t)}};function _o(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function vo(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(vo).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${vo(e.cause)}`:e.message:`${e}`}function yo(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var bo=e=>{throw TypeError(e)},xo=(e,t,n)=>t.has(e)||bo(`Cannot `+n),Q=(e,t,n)=>(xo(e,t,`read from private field`),n?n.call(e):t.get(e)),So=(e,t,n)=>t.has(e)?bo(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),$=(e,t,n,r)=>(xo(e,t,`write to private field`),t.set(e,n),n),Co=(e,t,n)=>(xo(e,t,`access private method`),n),wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po,Fo,Io,Lo,Ro,zo,Bo,Vo,Ho,Uo,Wo,Go,Ko,qo=class extends EventTarget{constructor(e,t){super(),So(this,Lo),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,So(this,wo),So(this,To),So(this,Eo),So(this,Do),So(this,Oo),So(this,ko),So(this,Ao),So(this,jo,null),So(this,Mo),So(this,No),So(this,Po,null),So(this,Fo,null),So(this,Io,null),So(this,zo,async e=>{var t;Q(this,No).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){Co(this,Lo,Wo).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?$(this,Eo,new URL(e.url)):$(this,Eo,void 0),i!==200){Co(this,Lo,Wo).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){Co(this,Lo,Wo).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if(Q(this,wo)===this.CLOSED)return;$(this,wo,this.OPEN);let o=new Event(`open`);if((t=Q(this,Io))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){Co(this,Lo,Wo).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&&Q(this,No).feed(s.decode(t,{stream:!e})),e&&(l=!1,Q(this,No).reset(),Co(this,Lo,Go).call(this))}while(l)}),So(this,Bo,e=>{$(this,Mo,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&Co(this,Lo,Go).call(this,vo(e))}),So(this,Ho,e=>{typeof e.id==`string`&&$(this,jo,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:Q(this,Eo)?Q(this,Eo).origin:Q(this,To).origin,lastEventId:e.id||``});Q(this,Fo)&&(!e.event||e.event===`message`)&&Q(this,Fo).call(this,t),this.dispatchEvent(t)}),So(this,Uo,e=>{$(this,ko,e)}),So(this,Ko,()=>{$(this,Ao,void 0),Q(this,wo)===this.CONNECTING&&Co(this,Lo,Ro).call(this)});try{if(e instanceof URL)$(this,To,e);else if(typeof e==`string`)$(this,To,new URL(e,Jo()));else throw Error(`Invalid URL`)}catch{throw _o(`An invalid or illegal string was specified`)}$(this,No,mo({onEvent:Q(this,Ho),onRetry:Q(this,Uo)})),$(this,wo,this.CONNECTING),$(this,ko,3e3),$(this,Oo,t?.fetch??globalThis.fetch),$(this,Do,t?.withCredentials??!1),Co(this,Lo,Ro).call(this)}get readyState(){return Q(this,wo)}get url(){return Q(this,To).href}get withCredentials(){return Q(this,Do)}get onerror(){return Q(this,Po)}set onerror(e){$(this,Po,e)}get onmessage(){return Q(this,Fo)}set onmessage(e){$(this,Fo,e)}get onopen(){return Q(this,Io)}set onopen(e){$(this,Io,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(){Q(this,Ao)&&clearTimeout(Q(this,Ao)),Q(this,wo)!==this.CLOSED&&(Q(this,Mo)&&Q(this,Mo).abort(),$(this,wo,this.CLOSED),$(this,Mo,void 0))}};wo=new WeakMap,To=new WeakMap,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 WeakSet,Ro=function(){$(this,wo,this.CONNECTING),$(this,Mo,new AbortController),Q(this,Oo)(Q(this,To),Co(this,Lo,Vo).call(this)).then(Q(this,zo)).catch(Q(this,Bo))},zo=new WeakMap,Bo=new WeakMap,Vo=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...Q(this,jo)?{"Last-Event-ID":Q(this,jo)}:void 0},cache:`no-store`,signal:Q(this,Mo)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},Ho=new WeakMap,Uo=new WeakMap,Wo=function(e,t){var n;Q(this,wo)!==this.CLOSED&&$(this,wo,this.CLOSED);let r=new go(`error`,{code:t,message:e});(n=Q(this,Po))==null||n.call(this,r),this.dispatchEvent(r)},Go=function(e,t){var n;if(Q(this,wo)===this.CLOSED)return;$(this,wo,this.CONNECTING);let r=new go(`error`,{code:t,message:e});(n=Q(this,Po))==null||n.call(this,r),this.dispatchEvent(r),$(this,Ao,setTimeout(Q(this,Ko),Q(this,ko)))},Ko=new WeakMap,qo.CONNECTING=0,qo.OPEN=1,qo.CLOSED=2;function Jo(){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 Yo;Yo=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function Xo(e){return(await Yo).getRandomValues(new Uint8Array(e))}async function Zo(e){let t=``,n=await Xo(e);for(let r=0;r<e;r++){let e=n[r]%66;t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e]}return t}async function Qo(e){return await Zo(e)}async function $o(e){let t=await(await Yo).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function es(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Qo(e),n=await $o(t);return{code_verifier:t,code_challenge:n}}const ts=K().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:E.custom,message:`URL must be parseable`,fatal:!0}),yt}).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`}),ns=J({resource:K().url(),authorization_servers:q(ts).optional(),jwks_uri:K().url().optional(),scopes_supported:q(K()).optional(),bearer_methods_supported:q(K()).optional(),resource_signing_alg_values_supported:q(K()).optional(),resource_name:K().optional(),resource_documentation:K().optional(),resource_policy_uri:K().url().optional(),resource_tos_uri:K().url().optional(),tls_client_certificate_bound_access_tokens:ft().optional(),authorization_details_types_supported:q(K()).optional(),dpop_signing_alg_values_supported:q(K()).optional(),dpop_bound_access_tokens_required:ft().optional()}).passthrough(),rs=J({issuer:K(),authorization_endpoint:ts,token_endpoint:ts,registration_endpoint:ts.optional(),scopes_supported:q(K()).optional(),response_types_supported:q(K()),response_modes_supported:q(K()).optional(),grant_types_supported:q(K()).optional(),token_endpoint_auth_methods_supported:q(K()).optional(),token_endpoint_auth_signing_alg_values_supported:q(K()).optional(),service_documentation:ts.optional(),revocation_endpoint:ts.optional(),revocation_endpoint_auth_methods_supported:q(K()).optional(),revocation_endpoint_auth_signing_alg_values_supported:q(K()).optional(),introspection_endpoint:K().optional(),introspection_endpoint_auth_methods_supported:q(K()).optional(),introspection_endpoint_auth_signing_alg_values_supported:q(K()).optional(),code_challenge_methods_supported:q(K()).optional()}).passthrough(),os=J({issuer:K(),authorization_endpoint:ts,token_endpoint:ts,userinfo_endpoint:ts.optional(),jwks_uri:ts,registration_endpoint:ts.optional(),scopes_supported:q(K()).optional(),response_types_supported:q(K()),response_modes_supported:q(K()).optional(),grant_types_supported:q(K()).optional(),acr_values_supported:q(K()).optional(),subject_types_supported:q(K()),id_token_signing_alg_values_supported:q(K()),id_token_encryption_alg_values_supported:q(K()).optional(),id_token_encryption_enc_values_supported:q(K()).optional(),userinfo_signing_alg_values_supported:q(K()).optional(),userinfo_encryption_alg_values_supported:q(K()).optional(),userinfo_encryption_enc_values_supported:q(K()).optional(),request_object_signing_alg_values_supported:q(K()).optional(),request_object_encryption_alg_values_supported:q(K()).optional(),request_object_encryption_enc_values_supported:q(K()).optional(),token_endpoint_auth_methods_supported:q(K()).optional(),token_endpoint_auth_signing_alg_values_supported:q(K()).optional(),display_values_supported:q(K()).optional(),claim_types_supported:q(K()).optional(),claims_supported:q(K()).optional(),service_documentation:K().optional(),claims_locales_supported:q(K()).optional(),ui_locales_supported:q(K()).optional(),claims_parameter_supported:ft().optional(),request_parameter_supported:ft().optional(),request_uri_parameter_supported:ft().optional(),require_request_uri_registration:ft().optional(),op_policy_uri:ts.optional(),op_tos_uri:ts.optional()}).passthrough().merge(rs.pick({code_challenge_methods_supported:!0})),ss=J({access_token:K(),id_token:K().optional(),token_type:K(),expires_in:dt().optional(),scope:K().optional(),refresh_token:K().optional()}).strip(),cs=J({error:K(),error_description:K().optional(),error_uri:K().optional()}),ls=J({redirect_uris:q(ts),token_endpoint_auth_method:K().optional(),grant_types:q(K()).optional(),response_types:q(K()).optional(),client_name:K().optional(),client_uri:ts.optional(),logo_uri:ts.optional(),scope:K().optional(),contacts:q(K()).optional(),tos_uri:ts.optional(),policy_uri:K().optional(),jwks_uri:ts.optional(),jwks:pt().optional(),software_id:K().optional(),software_version:K().optional(),software_statement:K().optional()}).strip(),us=J({client_id:K(),client_secret:K().optional(),client_id_issued_at:dt().optional(),client_secret_expires_at:dt().optional()}).strip(),ds=ls.merge(us);J({error:K(),error_description:K().optional()}).strip(),J({token:K(),token_type_hint:K().optional()}).strip();function fs(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function ps({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 ms=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}},hs=class extends ms{};hs.errorCode=`invalid_request`;var gs=class extends ms{};gs.errorCode=`invalid_client`;var _s=class extends ms{};_s.errorCode=`invalid_grant`;var vs=class extends ms{};vs.errorCode=`unauthorized_client`;var ys=class extends ms{};ys.errorCode=`unsupported_grant_type`;var bs=class extends ms{};bs.errorCode=`invalid_scope`;var xs=class extends ms{};xs.errorCode=`access_denied`;var Ss=class extends ms{};Ss.errorCode=`server_error`;var Cs=class extends ms{};Cs.errorCode=`temporarily_unavailable`;var ws=class extends ms{};ws.errorCode=`unsupported_response_type`;var Ts=class extends ms{};Ts.errorCode=`unsupported_token_type`;var Es=class extends ms{};Es.errorCode=`invalid_token`;var Ds=class extends ms{};Ds.errorCode=`method_not_allowed`;var Os=class extends ms{};Os.errorCode=`too_many_requests`;var ks=class extends ms{};ks.errorCode=`invalid_client_metadata`;var As=class extends ms{};As.errorCode=`insufficient_scope`;const js={[hs.errorCode]:hs,[gs.errorCode]:gs,[_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};var Ms=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Ns(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 Ps(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Fs(i,a,n);return;case`client_secret_post`:Is(i,a,r);return;case`none`:Ls(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Fs(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 Is(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Ls(e,t){t.set(`client_id`,e)}async function Rs(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}=cs.parse(JSON.parse(n));return new(js[e]||Ss)(t||``,r)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new Ss(r)}}async function zs(e,t){try{return await Bs(e,t)}catch(n){if(n instanceof gs||n instanceof vs)return await e.invalidateCredentials?.call(e,`all`),await Bs(e,t);if(n instanceof _s)return await e.invalidateCredentials?.call(e,`tokens`),await Bs(e,t);throw n}}async function Bs(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o,s;try{o=await Us(t,{resourceMetadataUrl:i},a),o.authorization_servers&&o.authorization_servers.length>0&&(s=o.authorization_servers[0])}catch{}s||=t;let c=await Vs(t,e,o),l=await Xs(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 ec(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 Qs(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 $s(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 ms)||e instanceof Ss))throw e}let f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:m}=await Zs(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 Vs(e,t,n){let r=fs(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ps({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function Hs(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 Us(e,t,n=fetch){let r=await Js(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 ns.parse(await r.json())}async function Ws(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Ws(e,void 0,n):void 0;throw r}}function Gs(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ks(e,t,n=fetch){return await Ws(e,{"MCP-Protocol-Version":t},n)}function qs(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Js(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??bt,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Gs(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await Ks(o,a,n);if(!r?.metadataUrl&&qs(s,i.pathname)){let e=new URL(`/.well-known/${t}`,i);s=await Ks(e,a,n)}return s}function Ys(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 Xs(e,{fetchFn:t=fetch,protocolVersion:n=bt}={}){let r={"MCP-Protocol-Version":n},i=Ys(e);for(let{url:e,type:n}of i){let i=await Ws(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 rs.parse(await i.json());{let t=os.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 Zs(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 es(),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 Qs(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=Ns(n,e);Ps(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 Rs(p);return ss.parse(await p.json())}async function $s(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=Ns(n,e);Ps(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 Rs(d);return ss.parse({refresh_token:r,...await d.json()})}async function ec(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 Rs(a);return ds.parse(await a.json())}var tc=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},nc=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 Ms(`No auth provider`);let t;try{t=await zs(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 Ms;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 qo(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=Hs(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 tc(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=Bt.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 Ms(`No auth provider`);if(await zs(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ms(`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=Hs(r),await zs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ms;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}},rc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=mo({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 ic={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var ac=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},oc=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??ic}async _authThenStart(){var e;if(!this._authProvider)throw new Ms(`No auth provider`);let t;try{t=await zs(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 Ms;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 ac(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 rc).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=Bt.parse(JSON.parse(e.data));i!==void 0&&It(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 Ms(`No auth provider`);if(await zs(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ms(`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:Mt(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=Hs(s),await zs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ms;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){Qt(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=>Bt.parse(e)):[Bt.parse(e)];for(let e of t)(n=this.onmessage)==null||n.call(this,e)}else throw new ac(-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 ac(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}},sc=n(co(),1),cc=class extends ha{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Hn.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(qt,e=>this._oninitialize(e)),this.setNotificationHandler(Zt,()=>this.oninitialized?.call(this)),this._capabilities.logging&&this.setRequestHandler(Un,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Hn.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=ga(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:xt.includes(t)?t:bt,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`},Vt)}async createMessage(e,t){return this.request({method:`sampling/createMessage`,params:e},Yn,t)}async elicitInput(e,t){let n=await this.request({method:`elicitation/create`,params:e},nr,t);if(n.action===`accept`&&n.content)try{let t=new sc.default,r=t.compile(e.requestedSchema);if(!r(n.content))throw new dr(Lt.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(r.errors)}`)}catch(e){throw e instanceof dr?e:new dr(Lt.InternalError,`Error validating elicitation response: ${e}`)}return n}async listRoots(e,t){return this.request({method:`roots/list`,params:e},lr,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`})}},lc=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),uc(t)}clear(){this._buffer=void 0}};function uc(e){return Bt.parse(JSON.parse(e))}function dc(e){return JSON.stringify(e)+`
|
|
28
28
|
`}var fc=class{constructor(e=b.stdin,t=b.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new lc,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=dc(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function pc(e){let t=typeof e==`string`?new URL(e):new URL(e.toString());return t.pathname.length>1&&t.pathname.endsWith(`/`)&&(t.pathname=t.pathname.slice(0,-1)),t.toString()}export{pr as AccessControlBlockError,br as BUILD_TIME_CONFIG,uo as Client,mr as ConfigurationError,x as InMemoryEventStore,gr as ProcessSpawnError,_r as ProxyConnectionError,lc as ReadBuffer,nc as SSEClientTransport,cc as Server,fc as StdioServerTransport,oc as StreamableHTTPClientTransport,yr as TransportError,Ms as UnauthorizedError,Qr as addBreadcrumbSafe,$r as addGlobalTags,ei as captureExceptionSafe,pi as compressClientInfo,Hr as config,mo as createParser,Xs as discoverAuthorizationServerMetadata,Us as discoverOAuthProtectedResourceMetadata,Qs as exchangeAuthorization,fi as getSessionData,ti as initSentrySafe,gi as initializeTrafficMirror,Z as logger,pc as normalizeUrl,bi as proxyServer,$s as refreshAuthorization,ec as registerClient,dc as serializeMessage,Zs as startAuthorization,ma as startHTTPServer};
|
|
29
|
-
//# sourceMappingURL=normalizeUrl-
|
|
29
|
+
//# sourceMappingURL=normalizeUrl-DwqzAC5_.js.map
|