@onyxsecurity/mcp-gateway 1.0.54 → 1.0.55

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.
@@ -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{AsyncLocalStorage as i}from"node:async_hooks";import{randomUUID as a}from"node:crypto";import{existsSync as o,mkdirSync as s,readFileSync as c}from"node:fs";import{join as l}from"node:path";import u from"winston";import d from"winston-daily-rotate-file";import f from"env-var";import{arch as p,homedir as m,hostname as h,platform as g,userInfo as _}from"node:os";import"dotenv/config";import v from"ps-list";import{deflateSync as y}from"node:zlib";import{URL as b}from"url";import x from"node:http";import S from"node:process";var C=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]:``}},w;(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})(w||={});var T;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(T||={});const E=w.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),D=e=>{switch(typeof e){case`undefined`:return E.undefined;case`string`:return E.string;case`number`:return Number.isNaN(e)?E.nan:E.number;case`boolean`:return E.boolean;case`function`:return E.function;case`bigint`:return E.bigint;case`symbol`:return E.symbol;case`object`:return Array.isArray(e)?E.array:e===null?E.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?E.promise:typeof Map<`u`&&e instanceof Map?E.map:typeof Set<`u`&&e instanceof Set?E.set:typeof Date<`u`&&e instanceof Date?E.date:E.object;default:return E.unknown}},O=w.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 k=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,w.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()}};k.create=e=>new k(e);var A=(e,t)=>{let n;switch(e.code){case O.invalid_type:n=e.received===E.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case O.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,w.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:n=`Unrecognized key(s) in object: ${w.joinValues(e.keys,`, `)}`;break;case O.invalid_union:n=`Invalid input`;break;case O.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${w.joinValues(e.options)}`;break;case O.invalid_enum_value:n=`Invalid enum value. Expected ${w.joinValues(e.options)}, received '${e.received}'`;break;case O.invalid_arguments:n=`Invalid function arguments`;break;case O.invalid_return_type:n=`Invalid function return type`;break;case O.invalid_date:n=`Invalid date`;break;case O.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}"`:w.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case O.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 O.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 O.custom:n=`Invalid input`;break;case O.invalid_intersection_types:n=`Intersection results could not be merged`;break;case O.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case O.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,w.assertNever(e)}return{message:n}};let ee=A;function j(){return ee}const M=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 N(e,t){let n=j(),r=M({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===A?void 0:A].filter(e=>!!e)});e.common.issues.push(r)}var P=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 F;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 F;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 F=Object.freeze({status:`aborted`}),te=e=>({status:`dirty`,value:e}),I=e=>({status:`valid`,value:e}),L=e=>e.status===`aborted`,ne=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 H=(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 k(e.common.issues),this._error}}};function U(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 W=class{get description(){return this._def.description}_getType(e){return D(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new P,ctx:{common:e.parent.common,data:e.data,parsedType:D(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:D(e)},r=this._parseSync({data:e,path:n.path,parent:n});return H(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(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:D(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(z(r)?r:Promise.resolve(r));return H(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:O.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 rt({schema:this,typeName:K.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return it.create(this,this._def)}nullable(){return at.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Re.create(this)}promise(){return nt.create(this,this._def)}or(e){return Ve.create([this,e],this._def)}and(e){return Ge.create(this,e,this._def)}transform(e){return new rt({...U(this._def),schema:this,typeName:K.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ot({...U(this._def),innerType:this,defaultValue:t,typeName:K.ZodDefault})}brand(){return new lt({typeName:K.ZodBranded,type:this,...U(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new st({...U(this._def),innerType:this,catchValue:t,typeName:K.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ut.create(this,e)}readonly(){return dt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const G=/^c[^\s-]{8,}$/i,re=/^[0-9a-z]+$/,ie=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ae=/^[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,oe=/^[a-z0-9_-]{21}$/i,se=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ce=/^[-+]?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)?)??$/,le=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let ue;const 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])$/,fe=/^(?:(?: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])$/,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]))$/,me=/^(([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])$/,he=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ge=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_e=`((\\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])))`,ve=RegExp(`^${_e}$`);function ye(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 be(e){return RegExp(`^${ye(e)}$`)}function xe(e){let t=`${_e}T${ye(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Se(e,t){return!!((t===`v4`||!t)&&de.test(e)||(t===`v6`||!t)&&pe.test(e))}function Ce(e,t){if(!se.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 we(e,t){return!!((t===`v4`||!t)&&fe.test(e)||(t===`v6`||!t)&&me.test(e))}var Te=class e extends W{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==E.string){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.string,received:t.parsedType}),F}let t=new P,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.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),N(n,{code:O.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?N(n,{code:O.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&N(n,{code:O.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)le.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`email`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)ue||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),ue.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`emoji`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ae.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`uuid`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)oe.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`nanoid`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)G.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`cuid`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)re.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`cuid2`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)ie.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`ulid`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),N(n,{validation:`url`,code:O.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),N(n,{validation:`regex`,code:O.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),N(n,{code:O.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),N(n,{code:O.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?xe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ve.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?be(r).test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?ce.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`duration`,code:O.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Se(e.data,r.version)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`ip`,code:O.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Ce(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`jwt`,code:O.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?we(e.data,r.version)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`cidr`,code:O.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?he.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`base64`,code:O.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?ge.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`base64url`,code:O.invalid_string,message:r.message}),t.dirty()):w.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:O.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}};Te.create=e=>new Te({checks:[],typeName:K.ZodString,coerce:e?.coerce??!1,...U(e)});function Ee(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 De=class e extends W{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)!==E.number){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.number,received:t.parsedType}),F}let t,n=new P;for(let r of this._def.checks)r.kind===`int`?w.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),N(t,{code:O.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),N(t,{code:O.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),N(t,{code:O.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ee(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),N(t,{code:O.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),N(t,{code:O.not_finite,message:r.message}),n.dirty()):w.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`&&w.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)}};De.create=e=>new De({checks:[],typeName:K.ZodNumber,coerce:e?.coerce||!1,...U(e)});var Oe=class e extends W{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)!==E.bigint)return this._getInvalidInput(e);let t,n=new P;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),N(t,{code:O.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),N(t,{code:O.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),N(t,{code:O.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):w.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.bigint,received:t.parsedType}),F}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}};Oe.create=e=>new Oe({checks:[],typeName:K.ZodBigInt,coerce:e?.coerce??!1,...U(e)});var ke=class extends W{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==E.boolean){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.boolean,received:t.parsedType}),F}return I(e.data)}};ke.create=e=>new ke({typeName:K.ZodBoolean,coerce:e?.coerce||!1,...U(e)});var Ae=class e extends W{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==E.date){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.date,received:t.parsedType}),F}if(Number.isNaN(e.data.getTime())){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_date}),F}let t=new P,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.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),N(n,{code:O.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):w.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)}};Ae.create=e=>new Ae({checks:[],coerce:e?.coerce||!1,typeName:K.ZodDate,...U(e)});var je=class extends W{_parse(e){if(this._getType(e)!==E.symbol){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.symbol,received:t.parsedType}),F}return I(e.data)}};je.create=e=>new je({typeName:K.ZodSymbol,...U(e)});var Me=class extends W{_parse(e){if(this._getType(e)!==E.undefined){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.undefined,received:t.parsedType}),F}return I(e.data)}};Me.create=e=>new Me({typeName:K.ZodUndefined,...U(e)});var Ne=class extends W{_parse(e){if(this._getType(e)!==E.null){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.null,received:t.parsedType}),F}return I(e.data)}};Ne.create=e=>new Ne({typeName:K.ZodNull,...U(e)});var Pe=class extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return I(e.data)}};Pe.create=e=>new Pe({typeName:K.ZodAny,...U(e)});var Fe=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return I(e.data)}};Fe.create=e=>new Fe({typeName:K.ZodUnknown,...U(e)});var Ie=class extends W{_parse(e){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.never,received:t.parsedType}),F}};Ie.create=e=>new Ie({typeName:K.ZodNever,...U(e)});var Le=class extends W{_parse(e){if(this._getType(e)!==E.undefined){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.void,received:t.parsedType}),F}return I(e.data)}};Le.create=e=>new Le({typeName:K.ZodVoid,...U(e)});var Re=class e extends W{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==E.array)return N(t,{code:O.invalid_type,expected:E.array,received:t.parsedType}),F;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(N(t,{code:e?O.too_big:O.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&&(N(t,{code:O.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&&(N(t,{code:O.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=>P.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new V(t,e,t.path,n)));return P.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)}};Re.create=(e,t)=>new Re({type:e,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...U(t)});function ze(e){if(e instanceof Be){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=it.create(ze(r))}return new Be({...e._def,shape:()=>t})}else if(e instanceof Re)return new Re({...e._def,type:ze(e.element)});else if(e instanceof it)return it.create(ze(e.unwrap()));else if(e instanceof at)return at.create(ze(e.unwrap()));else if(e instanceof Ke)return Ke.create(e.items.map(e=>ze(e)));else return e}var Be=class e extends W{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=w.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==E.object){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.object,received:t.parsedType}),F}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ie&&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 Ie){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&&(N(n,{code:O.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=>P.mergeObjectSync(t,e)):P.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:K.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of w.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 w.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return ze(this)}partial(t){let n={};for(let e of w.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 w.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof it;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return $e(w.objectKeys(this.shape))}};Be.create=(e,t)=>new Be({shape:()=>e,unknownKeys:`strip`,catchall:Ie.create(),typeName:K.ZodObject,...U(t)}),Be.strictCreate=(e,t)=>new Be({shape:()=>e,unknownKeys:`strict`,catchall:Ie.create(),typeName:K.ZodObject,...U(t)}),Be.lazycreate=(e,t)=>new Be({shape:e,unknownKeys:`strip`,catchall:Ie.create(),typeName:K.ZodObject,...U(t)});var Ve=class extends W{_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 k(e.ctx.common.issues));return N(t,{code:O.invalid_union,unionErrors:n}),F}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 k(e));return N(t,{code:O.invalid_union,unionErrors:i}),F}}get options(){return this._def.options}};Ve.create=(e,t)=>new Ve({options:e,typeName:K.ZodUnion,...U(t)});const He=e=>e instanceof Ze?He(e.schema):e instanceof rt?He(e.innerType()):e instanceof Qe?[e.value]:e instanceof et?e.options:e instanceof tt?w.objectValues(e.enum):e instanceof ot?He(e._def.innerType):e instanceof Me?[void 0]:e instanceof Ne?[null]:e instanceof it?[void 0,...He(e.unwrap())]:e instanceof at?[null,...He(e.unwrap())]:e instanceof lt||e instanceof dt?He(e.unwrap()):e instanceof st?He(e._def.innerType):[];var Ue=class e extends W{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.object)return N(t,{code:O.invalid_type,expected:E.object,received:t.parsedType}),F;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}):(N(t,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}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=He(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:K.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...U(r)})}};function We(e,t){let n=D(e),r=D(t);if(e===t)return{valid:!0,data:e};if(n===E.object&&r===E.object){let n=w.objectKeys(t),r=w.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=We(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===E.array&&r===E.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=We(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===E.date&&r===E.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Ge=class extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(L(e)||L(r))return F;let i=We(e.value,r.value);return i.valid?((ne(e)||ne(r))&&t.dirty(),{status:t.value,value:i.data}):(N(n,{code:O.invalid_intersection_types}),F)};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}))}};Ge.create=(e,t,n)=>new Ge({left:e,right:t,typeName:K.ZodIntersection,...U(n)});var Ke=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.array)return N(n,{code:O.invalid_type,expected:E.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return N(n,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),F;!this._def.rest&&n.data.length>this._def.items.length&&(N(n,{code:O.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=>P.mergeArray(t,e)):P.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ke.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Ke({items:e,typeName:K.ZodTuple,rest:null,...U(t)})};var qe=class e extends W{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!==E.object)return N(n,{code:O.invalid_type,expected:E.object,received:n.parsedType}),F;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?P.mergeObjectAsync(t,r):P.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof W?new e({keyType:t,valueType:n,typeName:K.ZodRecord,...U(r)}):new e({keyType:Te.create(),valueType:t,typeName:K.ZodRecord,...U(n)})}},Je=class extends W{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!==E.map)return N(n,{code:O.invalid_type,expected:E.map,received:n.parsedType}),F;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 F;(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 F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Je.create=(e,t,n)=>new Je({valueType:t,keyType:e,typeName:K.ZodMap,...U(n)});var Ye=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.set)return N(n,{code:O.invalid_type,expected:E.set,received:n.parsedType}),F;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(N(n,{code:O.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&&(N(n,{code:O.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 F;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)}};Ye.create=(e,t)=>new Ye({valueType:e,minSize:null,maxSize:null,typeName:K.ZodSet,...U(t)});var Xe=class e extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.function)return N(t,{code:O.invalid_type,expected:E.function,received:t.parsedType}),F;function n(e,n){return M({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,j(),A].filter(e=>!!e),issueData:{code:O.invalid_arguments,argumentsError:n}})}function r(e,n){return M({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,j(),A].filter(e=>!!e),issueData:{code:O.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof nt){let e=this;return I(async function(...t){let o=new k([]),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 k([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new k([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:Ke.create(t).rest(Fe.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||Ke.create([]).rest(Fe.create()),returns:n||Fe.create(),typeName:K.ZodFunction,...U(r)})}},Ze=class extends W{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})}};Ze.create=(e,t)=>new Ze({getter:e,typeName:K.ZodLazy,...U(t)});var Qe=class extends W{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return N(t,{received:t.data,code:O.invalid_literal,expected:this._def.value}),F}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Qe.create=(e,t)=>new Qe({value:e,typeName:K.ZodLiteral,...U(t)});function $e(e,t){return new et({values:e,typeName:K.ZodEnum,...U(t)})}var et=class e extends W{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return N(t,{expected:w.joinValues(n),received:t.parsedType,code:O.invalid_type}),F}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return N(t,{received:t.data,code:O.invalid_enum_value,options:n}),F}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})}};et.create=$e;var tt=class extends W{_parse(e){let t=w.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==E.string&&n.parsedType!==E.number){let e=w.objectValues(t);return N(n,{expected:w.joinValues(e),received:n.parsedType,code:O.invalid_type}),F}if(this._cache||=new Set(w.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=w.objectValues(t);return N(n,{received:n.data,code:O.invalid_enum_value,options:e}),F}return I(e.data)}get enum(){return this._def.values}};tt.create=(e,t)=>new tt({values:e,typeName:K.ZodNativeEnum,...U(t)});var nt=class extends W{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.promise&&t.common.async===!1)return N(t,{code:O.invalid_type,expected:E.promise,received:t.parsedType}),F;let n=t.parsedType===E.promise?t.data:Promise.resolve(t.data);return I(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};nt.create=(e,t)=>new nt({type:e,typeName:K.ZodPromise,...U(t)});var rt=class extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{N(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 F;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?te(r.value):r});{if(t.value===`aborted`)return F;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?te(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`?F:(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`?F:(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 F;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})):F);w.assertNever(r)}};rt.create=(e,t,n)=>new rt({schema:e,typeName:K.ZodEffects,effect:t,...U(n)}),rt.createWithPreprocess=(e,t,n)=>new rt({schema:t,effect:{type:`preprocess`,transform:e},typeName:K.ZodEffects,...U(n)});var it=class extends W{_parse(e){return this._getType(e)===E.undefined?I(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(e,t)=>new it({innerType:e,typeName:K.ZodOptional,...U(t)});var at=class extends W{_parse(e){return this._getType(e)===E.null?I(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};at.create=(e,t)=>new at({innerType:e,typeName:K.ZodNullable,...U(t)});var ot=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===E.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ot.create=(e,t)=>new ot({innerType:e,typeName:K.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...U(t)});var st=class extends W{_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 k(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new k(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};st.create=(e,t)=>new st({innerType:e,typeName:K.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...U(t)});var ct=class extends W{_parse(e){if(this._getType(e)!==E.nan){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.nan,received:t.parsedType}),F}return{status:`valid`,value:e.data}}};ct.create=e=>new ct({typeName:K.ZodNaN,...U(e)});var lt=class extends W{_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}},ut=class e extends W{_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`?F:e.status===`dirty`?(t.dirty(),te(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`?F:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:K.ZodPipeline})}},dt=class extends W{_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}};dt.create=(e,t)=>new dt({innerType:e,typeName:K.ZodReadonly,...U(t)}),Be.lazycreate;var K;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(K||={});const q=Te.create,ft=De.create;ct.create,Oe.create;const pt=ke.create;Ae.create,je.create,Me.create,Ne.create;const mt=Pe.create,ht=Fe.create;Ie.create,Le.create;const J=Re.create,Y=Be.create;Be.strictCreate;const gt=Ve.create,_t=Ue.create;Ge.create,Ke.create;const vt=qe.create;Je.create,Ye.create,Xe.create,Ze.create;const X=Qe.create,yt=et.create;tt.create,nt.create,rt.create;const Z=it.create;at.create,rt.createWithPreprocess,ut.create;const bt=F,xt=`2025-06-18`,St=[xt,`2025-03-26`,`2024-11-05`,`2024-10-07`],Ct=gt([q(),ft().int()]),wt=q(),Tt=Y({progressToken:Z(Ct)}).passthrough(),Et=Y({_meta:Z(Tt)}).passthrough(),Dt=Y({method:q(),params:Z(Et)}),Ot=Y({_meta:Z(Y({}).passthrough())}).passthrough(),kt=Y({method:q(),params:Z(Ot)}),At=Y({_meta:Z(Y({}).passthrough())}).passthrough(),jt=gt([q(),ft().int()]),Mt=Y({jsonrpc:X(`2.0`),id:jt}).merge(Dt).strict(),Nt=e=>Mt.safeParse(e).success,Pt=Y({jsonrpc:X(`2.0`)}).merge(kt).strict(),Ft=e=>Pt.safeParse(e).success,It=Y({jsonrpc:X(`2.0`),id:jt,result:At}).strict(),Lt=e=>It.safeParse(e).success;var Rt;(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`})(Rt||={});const zt=Y({jsonrpc:X(`2.0`),id:jt,error:Y({code:ft().int(),message:q(),data:Z(ht())})}).strict(),Bt=e=>zt.safeParse(e).success,Vt=gt([Mt,Pt,It,zt]),Ht=At.strict(),Ut=kt.extend({method:X(`notifications/cancelled`),params:Ot.extend({requestId:jt,reason:q().optional()})}),Wt=Y({src:q(),mimeType:Z(q()),sizes:Z(q())}).passthrough(),Gt=Y({name:q(),title:Z(q())}).passthrough(),Kt=Gt.extend({version:q(),websiteUrl:Z(q()),icons:Z(J(Wt))}),qt=Y({experimental:Z(Y({}).passthrough()),sampling:Z(Y({}).passthrough()),elicitation:Z(Y({}).passthrough()),roots:Z(Y({listChanged:Z(pt())}).passthrough())}).passthrough(),Jt=Dt.extend({method:X(`initialize`),params:Et.extend({protocolVersion:q(),capabilities:qt,clientInfo:Kt})}),Yt=e=>Jt.safeParse(e).success,Xt=Y({experimental:Z(Y({}).passthrough()),logging:Z(Y({}).passthrough()),completions:Z(Y({}).passthrough()),prompts:Z(Y({listChanged:Z(pt())}).passthrough()),resources:Z(Y({subscribe:Z(pt()),listChanged:Z(pt())}).passthrough()),tools:Z(Y({listChanged:Z(pt())}).passthrough())}).passthrough(),Zt=At.extend({protocolVersion:q(),capabilities:Xt,serverInfo:Kt,instructions:Z(q())}),Qt=kt.extend({method:X(`notifications/initialized`)}),$t=e=>Qt.safeParse(e).success,en=Dt.extend({method:X(`ping`)}),tn=Y({progress:ft(),total:Z(ft()),message:Z(q())}).passthrough(),nn=kt.extend({method:X(`notifications/progress`),params:Ot.merge(tn).extend({progressToken:Ct})}),rn=Dt.extend({params:Et.extend({cursor:Z(wt)}).optional()}),an=At.extend({nextCursor:Z(wt)}),on=Y({uri:q(),mimeType:Z(q()),_meta:Z(Y({}).passthrough())}).passthrough(),sn=on.extend({text:q()}),cn=q().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),ln=on.extend({blob:cn}),un=Gt.extend({uri:q(),description:Z(q()),mimeType:Z(q()),icons:Z(J(Wt)),_meta:Z(Y({}).passthrough())}),dn=Gt.extend({uriTemplate:q(),description:Z(q()),mimeType:Z(q()),_meta:Z(Y({}).passthrough())}),fn=rn.extend({method:X(`resources/list`)}),pn=an.extend({resources:J(un)}),mn=rn.extend({method:X(`resources/templates/list`)}),hn=an.extend({resourceTemplates:J(dn)}),gn=Dt.extend({method:X(`resources/read`),params:Et.extend({uri:q()})}),_n=At.extend({contents:J(gt([sn,ln]))}),vn=kt.extend({method:X(`notifications/resources/list_changed`)}),yn=Dt.extend({method:X(`resources/subscribe`),params:Et.extend({uri:q()})}),bn=Dt.extend({method:X(`resources/unsubscribe`),params:Et.extend({uri:q()})}),xn=kt.extend({method:X(`notifications/resources/updated`),params:Ot.extend({uri:q()})}),Sn=Y({name:q(),description:Z(q()),required:Z(pt())}).passthrough(),Cn=Gt.extend({description:Z(q()),arguments:Z(J(Sn)),icons:Z(J(Wt)),_meta:Z(Y({}).passthrough())}),wn=rn.extend({method:X(`prompts/list`)}),Tn=an.extend({prompts:J(Cn)}),En=Dt.extend({method:X(`prompts/get`),params:Et.extend({name:q(),arguments:Z(vt(q()))})}),Dn=Y({type:X(`text`),text:q(),_meta:Z(Y({}).passthrough())}).passthrough(),On=Y({type:X(`image`),data:cn,mimeType:q(),_meta:Z(Y({}).passthrough())}).passthrough(),kn=Y({type:X(`audio`),data:cn,mimeType:q(),_meta:Z(Y({}).passthrough())}).passthrough(),An=Y({type:X(`resource`),resource:gt([sn,ln]),_meta:Z(Y({}).passthrough())}).passthrough(),jn=un.extend({type:X(`resource_link`)}),Mn=gt([Dn,On,kn,jn,An]),Nn=Y({role:yt([`user`,`assistant`]),content:Mn}).passthrough(),Pn=At.extend({description:Z(q()),messages:J(Nn)}),Fn=kt.extend({method:X(`notifications/prompts/list_changed`)}),In=Y({title:Z(q()),readOnlyHint:Z(pt()),destructiveHint:Z(pt()),idempotentHint:Z(pt()),openWorldHint:Z(pt())}).passthrough(),Ln=Gt.extend({description:Z(q()),inputSchema:Y({type:X(`object`),properties:Z(Y({}).passthrough()),required:Z(J(q()))}).passthrough(),outputSchema:Z(Y({type:X(`object`),properties:Z(Y({}).passthrough()),required:Z(J(q()))}).passthrough()),annotations:Z(In),icons:Z(J(Wt)),_meta:Z(Y({}).passthrough())}),Rn=rn.extend({method:X(`tools/list`)}),zn=an.extend({tools:J(Ln)}),Bn=At.extend({content:J(Mn).default([]),structuredContent:Y({}).passthrough().optional(),isError:Z(pt())});Bn.or(At.extend({toolResult:ht()}));const Vn=Dt.extend({method:X(`tools/call`),params:Et.extend({name:q(),arguments:Z(vt(ht()))})}),Hn=kt.extend({method:X(`notifications/tools/list_changed`)}),Un=yt([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Wn=Dt.extend({method:X(`logging/setLevel`),params:Et.extend({level:Un})}),Gn=kt.extend({method:X(`notifications/message`),params:Ot.extend({level:Un,logger:Z(q()),data:ht()})}),Kn=Y({name:q().optional()}).passthrough(),qn=Y({hints:Z(J(Kn)),costPriority:Z(ft().min(0).max(1)),speedPriority:Z(ft().min(0).max(1)),intelligencePriority:Z(ft().min(0).max(1))}).passthrough(),Jn=Y({role:yt([`user`,`assistant`]),content:gt([Dn,On,kn])}).passthrough(),Yn=Dt.extend({method:X(`sampling/createMessage`),params:Et.extend({messages:J(Jn),systemPrompt:Z(q()),includeContext:Z(yt([`none`,`thisServer`,`allServers`])),temperature:Z(ft()),maxTokens:ft().int(),stopSequences:Z(J(q())),metadata:Z(Y({}).passthrough()),modelPreferences:Z(qn)})}),Xn=At.extend({model:q(),stopReason:Z(yt([`endTurn`,`stopSequence`,`maxTokens`]).or(q())),role:yt([`user`,`assistant`]),content:_t(`type`,[Dn,On,kn])}),Zn=Y({type:X(`boolean`),title:Z(q()),description:Z(q()),default:Z(pt())}).passthrough(),Qn=Y({type:X(`string`),title:Z(q()),description:Z(q()),minLength:Z(ft()),maxLength:Z(ft()),format:Z(yt([`email`,`uri`,`date`,`date-time`]))}).passthrough(),$n=Y({type:yt([`number`,`integer`]),title:Z(q()),description:Z(q()),minimum:Z(ft()),maximum:Z(ft())}).passthrough(),er=Y({type:X(`string`),title:Z(q()),description:Z(q()),enum:J(q()),enumNames:Z(J(q()))}).passthrough(),tr=gt([Zn,Qn,$n,er]),nr=Dt.extend({method:X(`elicitation/create`),params:Et.extend({message:q(),requestedSchema:Y({type:X(`object`),properties:vt(q(),tr),required:Z(J(q()))}).passthrough()})}),rr=At.extend({action:yt([`accept`,`decline`,`cancel`]),content:Z(vt(q(),ht()))}),ir=Y({type:X(`ref/resource`),uri:q()}).passthrough(),ar=Y({type:X(`ref/prompt`),name:q()}).passthrough(),or=Dt.extend({method:X(`completion/complete`),params:Et.extend({ref:gt([ar,ir]),argument:Y({name:q(),value:q()}).passthrough(),context:Z(Y({arguments:Z(vt(q(),q()))}))})}),sr=At.extend({completion:Y({values:J(q()).max(100),total:Z(ft().int()),hasMore:Z(pt())}).passthrough()}),cr=Y({uri:q().startsWith(`file://`),name:Z(q()),_meta:Z(Y({}).passthrough())}).passthrough(),lr=Dt.extend({method:X(`roots/list`)}),ur=At.extend({roots:J(cr)}),dr=kt.extend({method:X(`notifications/roots/list_changed`)});gt([en,Jt,or,Wn,En,wn,fn,mn,gn,yn,bn,Vn,Rn]),gt([Ut,nn,Qt,dr]),gt([Ht,Xn,rr,ur]),gt([en,Yn,nr,lr]),gt([Ut,nn,Gn,xn,vn,Hn,Fn]),gt([Ht,Zt,sr,Pn,Tn,pn,hn,_n,Bn,zn]);var fr=class extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}},pr=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},mr=class extends pr{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},hr=class extends pr{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},gr=class extends pr{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})}};const _r={APP_VERSION:`1.0.54`,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`}]},vr=f.get,yr=_r.APP_VERSION,br=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},xr=e=>{try{let t=new URL(e),n=t.pathname.split(`/`).filter(Boolean)[0]===`ingest`?`/ingest`:``;return`${t.protocol}//${t.host}${n}/endpoint-logs`}catch{return null}},Sr=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}},Cr=r(),wr=vr(`NODE_ENV`).default(_r.NODE_ENV||`development`).asEnum([`development`,`production`,`staging`,`test`]),Tr=vr(`DEBUG`).default(`false`).asBool()||vr(`MCP_GATEWAY_DEBUG`).default(`false`).asBool(),Er=vr(`MCP_GATEWAY_SCANNER_URL`).default(``).asString()||null,Dr=vr(`MCP_GATEWAY_SCANNER_API_KEY`).default(``).asString()||void 0,Or=vr(`MCP_GATEWAY_MIRROR_URL`).default(``).asString()||null,kr=(()=>{let e=vr(`MCP_GATEWAY_SCANNER_HEADERS`).required(!1).asString();return e?br(e):{}})(),Ar=vr(`MCP_GATEWAY_SCANNER_TIMEOUT_MS`).default(`20000`).asIntPositive(),jr=vr(`MCP_GATEWAY_SCANNER_FAIL_OPEN`).default(`true`).asBool(),Mr=vr(`MCP_GATEWAY_COMMAND`).default(`mcp-gateway`).asString(),Nr=vr(`CLIENT_APP_NAME`).default(``).asString(),Pr=vr(`MCP_GATEWAY_LOG_DIR`).default(l(m(),`.onyx`,`mcp-gateway`,`logs`)).asString(),Fr=vr(`MCP_GATEWAY_OAUTH_DIR`).default(l(m(),`.onyx`,`mcp-gateway`,`oauth`)).asString(),Ir=(()=>vr(`MCP_GATEWAY_ACCESS_CONTROL_URL`).default(``).asString()||(Er?Sr(Er):null))(),Lr=(()=>{let e=vr(`MCP_GATEWAY_ACCESS_CONTROL_HEADERS`).required(!1).asString();return e?br(e):{}})(),Rr=vr(`MCP_GATEWAY_ACCESS_CONTROL_TIMEOUT_MS`).default(`3000`).asIntPositive(),zr=vr(`MCP_GATEWAY_LOG_INGEST_ENABLED`).default(`true`).asBool(),Br=vr(`MCP_GATEWAY_LOG_INGEST_TIMEOUT_MS`).default(`5000`).asIntPositive(),Vr=(()=>vr(`MCP_GATEWAY_LOG_INGEST_URL`).default(``).asString()||(Or?xr(Or):Er?xr(Er):null))(),Hr={accessControl:{enabled:!!(Ir&&Dr),headers:Lr,timeoutMs:Rr,url:Ir},appVersion:yr,clientAppName:Nr,debug:Tr,environment:wr,logDir:Pr,logIngest:{apiKey:Dr,enabled:zr&&!!(Vr&&Dr),timeoutMs:Br,url:Vr},oauthDir:Fr,proxyCommand:Mr,scanner:{apiKey:Dr,enabled:!!Er,failOpen:jr,headers:kr,timeoutMs:Ar,url:Er}};var Ur=e(((exports,n)=>{n.exports=t(`util`).deprecate})),Wr=e(((exports,n)=>{n.exports=t(`stream`)})),Gr=e(((exports,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),Kr=e(((exports,t)=>{let n={};function r(e,t,r){r||=Error;function i(e,n,r){return typeof t==`string`?t:t(e,n,r)}class a extends r{constructor(e,t,n){super(i(e,t,n))}}a.prototype.name=r.name,a.prototype.code=e,n[e]=a}function i(e,t){if(Array.isArray(e)){let n=e.length;return e=e.map(e=>String(e)),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return`of ${t} ${String(e)}`}function a(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function o(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function s(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}r(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),r(`ERR_INVALID_ARG_TYPE`,function(e,t,n){let r;typeof t==`string`&&a(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;let c;if(o(e,` argument`))c=`The ${e} ${r} ${i(t,`type`)}`;else{let n=s(e,`.`)?`property`:`argument`;c=`The "${e}" ${n} ${r} ${i(t,`type`)}`}return c+=`. Received type ${typeof n}`,c},TypeError),r(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),r(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),r(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),r(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),r(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),r(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),r(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),r(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),r(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),r(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=n})),qr=e(((exports,t)=>{var n=Kr().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16*1024}t.exports={getHighWaterMark:i}})),Jr=e(((exports,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Yr=e(((exports,n)=>{try{var r=t(`util`);if(typeof r.inherits!=`function`)throw``;n.exports=r.inherits}catch{n.exports=Jr()}})),Xr=e(((exports,n)=>{function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r(Object(n),!0).forEach(function(t){a(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function a(e,t,n){return t=l(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function s(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,l(r.key),r)}}function c(e,t,n){return t&&s(e.prototype,t),n&&s(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function l(e){var t=u(e,`string`);return typeof t==`symbol`?t:String(t)}function u(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var d=t(`buffer`),f=d.Buffer,p=t(`util`),m=p.inspect,h=m&&m.custom||`inspect`;function g(e,t,n){f.prototype.copy.call(e,t,n)}n.exports=function(){function e(){o(this,e),this.head=null,this.tail=null,this.length=0}return c(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return f.alloc(0);for(var t=f.allocUnsafe(e>>>0),n=this.head,r=0;n;)g(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=f.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:h,value:function(e,t){return m(this,i(i({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),Zr=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{AsyncLocalStorage as i}from"node:async_hooks";import{randomUUID as a}from"node:crypto";import{existsSync as o,mkdirSync as s,readFileSync as c}from"node:fs";import{join as l}from"node:path";import u from"winston";import d from"winston-daily-rotate-file";import f from"env-var";import{arch as p,homedir as m,hostname as h,platform as g,userInfo as _}from"node:os";import"dotenv/config";import v from"ps-list";import{deflateSync as y}from"node:zlib";import{URL as b}from"url";import x from"node:http";import S from"node:process";var C=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]:``}},w;(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})(w||={});var T;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(T||={});const E=w.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),D=e=>{switch(typeof e){case`undefined`:return E.undefined;case`string`:return E.string;case`number`:return Number.isNaN(e)?E.nan:E.number;case`boolean`:return E.boolean;case`function`:return E.function;case`bigint`:return E.bigint;case`symbol`:return E.symbol;case`object`:return Array.isArray(e)?E.array:e===null?E.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?E.promise:typeof Map<`u`&&e instanceof Map?E.map:typeof Set<`u`&&e instanceof Set?E.set:typeof Date<`u`&&e instanceof Date?E.date:E.object;default:return E.unknown}},O=w.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 k=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,w.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()}};k.create=e=>new k(e);var A=(e,t)=>{let n;switch(e.code){case O.invalid_type:n=e.received===E.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case O.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,w.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:n=`Unrecognized key(s) in object: ${w.joinValues(e.keys,`, `)}`;break;case O.invalid_union:n=`Invalid input`;break;case O.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${w.joinValues(e.options)}`;break;case O.invalid_enum_value:n=`Invalid enum value. Expected ${w.joinValues(e.options)}, received '${e.received}'`;break;case O.invalid_arguments:n=`Invalid function arguments`;break;case O.invalid_return_type:n=`Invalid function return type`;break;case O.invalid_date:n=`Invalid date`;break;case O.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}"`:w.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case O.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 O.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 O.custom:n=`Invalid input`;break;case O.invalid_intersection_types:n=`Intersection results could not be merged`;break;case O.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case O.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,w.assertNever(e)}return{message:n}};let ee=A;function j(){return ee}const M=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 N(e,t){let n=j(),r=M({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===A?void 0:A].filter(e=>!!e)});e.common.issues.push(r)}var P=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 F;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 F;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 F=Object.freeze({status:`aborted`}),te=e=>({status:`dirty`,value:e}),I=e=>({status:`valid`,value:e}),L=e=>e.status===`aborted`,ne=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 H=(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 k(e.common.issues),this._error}}};function U(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 W=class{get description(){return this._def.description}_getType(e){return D(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new P,ctx:{common:e.parent.common,data:e.data,parsedType:D(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:D(e)},r=this._parseSync({data:e,path:n.path,parent:n});return H(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(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:D(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(z(r)?r:Promise.resolve(r));return H(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:O.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 rt({schema:this,typeName:K.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return it.create(this,this._def)}nullable(){return at.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Re.create(this)}promise(){return nt.create(this,this._def)}or(e){return Ve.create([this,e],this._def)}and(e){return Ge.create(this,e,this._def)}transform(e){return new rt({...U(this._def),schema:this,typeName:K.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ot({...U(this._def),innerType:this,defaultValue:t,typeName:K.ZodDefault})}brand(){return new lt({typeName:K.ZodBranded,type:this,...U(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new st({...U(this._def),innerType:this,catchValue:t,typeName:K.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ut.create(this,e)}readonly(){return dt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const G=/^c[^\s-]{8,}$/i,re=/^[0-9a-z]+$/,ie=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ae=/^[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,oe=/^[a-z0-9_-]{21}$/i,se=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ce=/^[-+]?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)?)??$/,le=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let ue;const 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])$/,fe=/^(?:(?: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])$/,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]))$/,me=/^(([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])$/,he=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ge=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_e=`((\\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])))`,ve=RegExp(`^${_e}$`);function ye(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 be(e){return RegExp(`^${ye(e)}$`)}function xe(e){let t=`${_e}T${ye(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Se(e,t){return!!((t===`v4`||!t)&&de.test(e)||(t===`v6`||!t)&&pe.test(e))}function Ce(e,t){if(!se.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 we(e,t){return!!((t===`v4`||!t)&&fe.test(e)||(t===`v6`||!t)&&me.test(e))}var Te=class e extends W{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==E.string){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.string,received:t.parsedType}),F}let t=new P,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.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),N(n,{code:O.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?N(n,{code:O.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&N(n,{code:O.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)le.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`email`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)ue||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),ue.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`emoji`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ae.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`uuid`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)oe.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`nanoid`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)G.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`cuid`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)re.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`cuid2`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)ie.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`ulid`,code:O.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),N(n,{validation:`url`,code:O.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),N(n,{validation:`regex`,code:O.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),N(n,{code:O.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),N(n,{code:O.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?xe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ve.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?be(r).test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?ce.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`duration`,code:O.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Se(e.data,r.version)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`ip`,code:O.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Ce(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`jwt`,code:O.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?we(e.data,r.version)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`cidr`,code:O.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?he.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`base64`,code:O.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?ge.test(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{validation:`base64url`,code:O.invalid_string,message:r.message}),t.dirty()):w.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:O.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}};Te.create=e=>new Te({checks:[],typeName:K.ZodString,coerce:e?.coerce??!1,...U(e)});function Ee(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 De=class e extends W{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)!==E.number){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.number,received:t.parsedType}),F}let t,n=new P;for(let r of this._def.checks)r.kind===`int`?w.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),N(t,{code:O.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),N(t,{code:O.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),N(t,{code:O.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ee(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),N(t,{code:O.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),N(t,{code:O.not_finite,message:r.message}),n.dirty()):w.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`&&w.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)}};De.create=e=>new De({checks:[],typeName:K.ZodNumber,coerce:e?.coerce||!1,...U(e)});var Oe=class e extends W{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)!==E.bigint)return this._getInvalidInput(e);let t,n=new P;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),N(t,{code:O.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),N(t,{code:O.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),N(t,{code:O.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):w.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.bigint,received:t.parsedType}),F}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}};Oe.create=e=>new Oe({checks:[],typeName:K.ZodBigInt,coerce:e?.coerce??!1,...U(e)});var ke=class extends W{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==E.boolean){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.boolean,received:t.parsedType}),F}return I(e.data)}};ke.create=e=>new ke({typeName:K.ZodBoolean,coerce:e?.coerce||!1,...U(e)});var Ae=class e extends W{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==E.date){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.date,received:t.parsedType}),F}if(Number.isNaN(e.data.getTime())){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_date}),F}let t=new P,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.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),N(n,{code:O.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):w.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)}};Ae.create=e=>new Ae({checks:[],coerce:e?.coerce||!1,typeName:K.ZodDate,...U(e)});var je=class extends W{_parse(e){if(this._getType(e)!==E.symbol){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.symbol,received:t.parsedType}),F}return I(e.data)}};je.create=e=>new je({typeName:K.ZodSymbol,...U(e)});var Me=class extends W{_parse(e){if(this._getType(e)!==E.undefined){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.undefined,received:t.parsedType}),F}return I(e.data)}};Me.create=e=>new Me({typeName:K.ZodUndefined,...U(e)});var Ne=class extends W{_parse(e){if(this._getType(e)!==E.null){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.null,received:t.parsedType}),F}return I(e.data)}};Ne.create=e=>new Ne({typeName:K.ZodNull,...U(e)});var Pe=class extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return I(e.data)}};Pe.create=e=>new Pe({typeName:K.ZodAny,...U(e)});var Fe=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return I(e.data)}};Fe.create=e=>new Fe({typeName:K.ZodUnknown,...U(e)});var Ie=class extends W{_parse(e){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.never,received:t.parsedType}),F}};Ie.create=e=>new Ie({typeName:K.ZodNever,...U(e)});var Le=class extends W{_parse(e){if(this._getType(e)!==E.undefined){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.void,received:t.parsedType}),F}return I(e.data)}};Le.create=e=>new Le({typeName:K.ZodVoid,...U(e)});var Re=class e extends W{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==E.array)return N(t,{code:O.invalid_type,expected:E.array,received:t.parsedType}),F;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(N(t,{code:e?O.too_big:O.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&&(N(t,{code:O.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&&(N(t,{code:O.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=>P.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new V(t,e,t.path,n)));return P.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)}};Re.create=(e,t)=>new Re({type:e,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...U(t)});function ze(e){if(e instanceof Be){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=it.create(ze(r))}return new Be({...e._def,shape:()=>t})}else if(e instanceof Re)return new Re({...e._def,type:ze(e.element)});else if(e instanceof it)return it.create(ze(e.unwrap()));else if(e instanceof at)return at.create(ze(e.unwrap()));else if(e instanceof Ke)return Ke.create(e.items.map(e=>ze(e)));else return e}var Be=class e extends W{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=w.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==E.object){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.object,received:t.parsedType}),F}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ie&&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 Ie){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&&(N(n,{code:O.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=>P.mergeObjectSync(t,e)):P.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:K.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of w.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 w.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return ze(this)}partial(t){let n={};for(let e of w.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 w.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof it;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return $e(w.objectKeys(this.shape))}};Be.create=(e,t)=>new Be({shape:()=>e,unknownKeys:`strip`,catchall:Ie.create(),typeName:K.ZodObject,...U(t)}),Be.strictCreate=(e,t)=>new Be({shape:()=>e,unknownKeys:`strict`,catchall:Ie.create(),typeName:K.ZodObject,...U(t)}),Be.lazycreate=(e,t)=>new Be({shape:e,unknownKeys:`strip`,catchall:Ie.create(),typeName:K.ZodObject,...U(t)});var Ve=class extends W{_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 k(e.ctx.common.issues));return N(t,{code:O.invalid_union,unionErrors:n}),F}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 k(e));return N(t,{code:O.invalid_union,unionErrors:i}),F}}get options(){return this._def.options}};Ve.create=(e,t)=>new Ve({options:e,typeName:K.ZodUnion,...U(t)});const He=e=>e instanceof Ze?He(e.schema):e instanceof rt?He(e.innerType()):e instanceof Qe?[e.value]:e instanceof et?e.options:e instanceof tt?w.objectValues(e.enum):e instanceof ot?He(e._def.innerType):e instanceof Me?[void 0]:e instanceof Ne?[null]:e instanceof it?[void 0,...He(e.unwrap())]:e instanceof at?[null,...He(e.unwrap())]:e instanceof lt||e instanceof dt?He(e.unwrap()):e instanceof st?He(e._def.innerType):[];var Ue=class e extends W{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.object)return N(t,{code:O.invalid_type,expected:E.object,received:t.parsedType}),F;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}):(N(t,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}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=He(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:K.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...U(r)})}};function We(e,t){let n=D(e),r=D(t);if(e===t)return{valid:!0,data:e};if(n===E.object&&r===E.object){let n=w.objectKeys(t),r=w.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=We(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===E.array&&r===E.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=We(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===E.date&&r===E.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Ge=class extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(L(e)||L(r))return F;let i=We(e.value,r.value);return i.valid?((ne(e)||ne(r))&&t.dirty(),{status:t.value,value:i.data}):(N(n,{code:O.invalid_intersection_types}),F)};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}))}};Ge.create=(e,t,n)=>new Ge({left:e,right:t,typeName:K.ZodIntersection,...U(n)});var Ke=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.array)return N(n,{code:O.invalid_type,expected:E.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return N(n,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),F;!this._def.rest&&n.data.length>this._def.items.length&&(N(n,{code:O.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=>P.mergeArray(t,e)):P.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ke.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Ke({items:e,typeName:K.ZodTuple,rest:null,...U(t)})};var qe=class e extends W{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!==E.object)return N(n,{code:O.invalid_type,expected:E.object,received:n.parsedType}),F;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?P.mergeObjectAsync(t,r):P.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof W?new e({keyType:t,valueType:n,typeName:K.ZodRecord,...U(r)}):new e({keyType:Te.create(),valueType:t,typeName:K.ZodRecord,...U(n)})}},Je=class extends W{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!==E.map)return N(n,{code:O.invalid_type,expected:E.map,received:n.parsedType}),F;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 F;(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 F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Je.create=(e,t,n)=>new Je({valueType:t,keyType:e,typeName:K.ZodMap,...U(n)});var Ye=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.set)return N(n,{code:O.invalid_type,expected:E.set,received:n.parsedType}),F;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(N(n,{code:O.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&&(N(n,{code:O.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 F;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)}};Ye.create=(e,t)=>new Ye({valueType:e,minSize:null,maxSize:null,typeName:K.ZodSet,...U(t)});var Xe=class e extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.function)return N(t,{code:O.invalid_type,expected:E.function,received:t.parsedType}),F;function n(e,n){return M({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,j(),A].filter(e=>!!e),issueData:{code:O.invalid_arguments,argumentsError:n}})}function r(e,n){return M({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,j(),A].filter(e=>!!e),issueData:{code:O.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof nt){let e=this;return I(async function(...t){let o=new k([]),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 k([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new k([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:Ke.create(t).rest(Fe.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||Ke.create([]).rest(Fe.create()),returns:n||Fe.create(),typeName:K.ZodFunction,...U(r)})}},Ze=class extends W{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})}};Ze.create=(e,t)=>new Ze({getter:e,typeName:K.ZodLazy,...U(t)});var Qe=class extends W{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return N(t,{received:t.data,code:O.invalid_literal,expected:this._def.value}),F}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Qe.create=(e,t)=>new Qe({value:e,typeName:K.ZodLiteral,...U(t)});function $e(e,t){return new et({values:e,typeName:K.ZodEnum,...U(t)})}var et=class e extends W{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return N(t,{expected:w.joinValues(n),received:t.parsedType,code:O.invalid_type}),F}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return N(t,{received:t.data,code:O.invalid_enum_value,options:n}),F}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})}};et.create=$e;var tt=class extends W{_parse(e){let t=w.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==E.string&&n.parsedType!==E.number){let e=w.objectValues(t);return N(n,{expected:w.joinValues(e),received:n.parsedType,code:O.invalid_type}),F}if(this._cache||=new Set(w.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=w.objectValues(t);return N(n,{received:n.data,code:O.invalid_enum_value,options:e}),F}return I(e.data)}get enum(){return this._def.values}};tt.create=(e,t)=>new tt({values:e,typeName:K.ZodNativeEnum,...U(t)});var nt=class extends W{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.promise&&t.common.async===!1)return N(t,{code:O.invalid_type,expected:E.promise,received:t.parsedType}),F;let n=t.parsedType===E.promise?t.data:Promise.resolve(t.data);return I(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};nt.create=(e,t)=>new nt({type:e,typeName:K.ZodPromise,...U(t)});var rt=class extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{N(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 F;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?te(r.value):r});{if(t.value===`aborted`)return F;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?te(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`?F:(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`?F:(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 F;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})):F);w.assertNever(r)}};rt.create=(e,t,n)=>new rt({schema:e,typeName:K.ZodEffects,effect:t,...U(n)}),rt.createWithPreprocess=(e,t,n)=>new rt({schema:t,effect:{type:`preprocess`,transform:e},typeName:K.ZodEffects,...U(n)});var it=class extends W{_parse(e){return this._getType(e)===E.undefined?I(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(e,t)=>new it({innerType:e,typeName:K.ZodOptional,...U(t)});var at=class extends W{_parse(e){return this._getType(e)===E.null?I(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};at.create=(e,t)=>new at({innerType:e,typeName:K.ZodNullable,...U(t)});var ot=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===E.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ot.create=(e,t)=>new ot({innerType:e,typeName:K.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...U(t)});var st=class extends W{_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 k(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new k(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};st.create=(e,t)=>new st({innerType:e,typeName:K.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...U(t)});var ct=class extends W{_parse(e){if(this._getType(e)!==E.nan){let t=this._getOrReturnCtx(e);return N(t,{code:O.invalid_type,expected:E.nan,received:t.parsedType}),F}return{status:`valid`,value:e.data}}};ct.create=e=>new ct({typeName:K.ZodNaN,...U(e)});var lt=class extends W{_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}},ut=class e extends W{_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`?F:e.status===`dirty`?(t.dirty(),te(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`?F:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:K.ZodPipeline})}},dt=class extends W{_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}};dt.create=(e,t)=>new dt({innerType:e,typeName:K.ZodReadonly,...U(t)}),Be.lazycreate;var K;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(K||={});const q=Te.create,ft=De.create;ct.create,Oe.create;const pt=ke.create;Ae.create,je.create,Me.create,Ne.create;const mt=Pe.create,ht=Fe.create;Ie.create,Le.create;const J=Re.create,Y=Be.create;Be.strictCreate;const gt=Ve.create,_t=Ue.create;Ge.create,Ke.create;const vt=qe.create;Je.create,Ye.create,Xe.create,Ze.create;const X=Qe.create,yt=et.create;tt.create,nt.create,rt.create;const Z=it.create;at.create,rt.createWithPreprocess,ut.create;const bt=F,xt=`2025-06-18`,St=[xt,`2025-03-26`,`2024-11-05`,`2024-10-07`],Ct=gt([q(),ft().int()]),wt=q(),Tt=Y({progressToken:Z(Ct)}).passthrough(),Et=Y({_meta:Z(Tt)}).passthrough(),Dt=Y({method:q(),params:Z(Et)}),Ot=Y({_meta:Z(Y({}).passthrough())}).passthrough(),kt=Y({method:q(),params:Z(Ot)}),At=Y({_meta:Z(Y({}).passthrough())}).passthrough(),jt=gt([q(),ft().int()]),Mt=Y({jsonrpc:X(`2.0`),id:jt}).merge(Dt).strict(),Nt=e=>Mt.safeParse(e).success,Pt=Y({jsonrpc:X(`2.0`)}).merge(kt).strict(),Ft=e=>Pt.safeParse(e).success,It=Y({jsonrpc:X(`2.0`),id:jt,result:At}).strict(),Lt=e=>It.safeParse(e).success;var Rt;(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`})(Rt||={});const zt=Y({jsonrpc:X(`2.0`),id:jt,error:Y({code:ft().int(),message:q(),data:Z(ht())})}).strict(),Bt=e=>zt.safeParse(e).success,Vt=gt([Mt,Pt,It,zt]),Ht=At.strict(),Ut=kt.extend({method:X(`notifications/cancelled`),params:Ot.extend({requestId:jt,reason:q().optional()})}),Wt=Y({src:q(),mimeType:Z(q()),sizes:Z(q())}).passthrough(),Gt=Y({name:q(),title:Z(q())}).passthrough(),Kt=Gt.extend({version:q(),websiteUrl:Z(q()),icons:Z(J(Wt))}),qt=Y({experimental:Z(Y({}).passthrough()),sampling:Z(Y({}).passthrough()),elicitation:Z(Y({}).passthrough()),roots:Z(Y({listChanged:Z(pt())}).passthrough())}).passthrough(),Jt=Dt.extend({method:X(`initialize`),params:Et.extend({protocolVersion:q(),capabilities:qt,clientInfo:Kt})}),Yt=e=>Jt.safeParse(e).success,Xt=Y({experimental:Z(Y({}).passthrough()),logging:Z(Y({}).passthrough()),completions:Z(Y({}).passthrough()),prompts:Z(Y({listChanged:Z(pt())}).passthrough()),resources:Z(Y({subscribe:Z(pt()),listChanged:Z(pt())}).passthrough()),tools:Z(Y({listChanged:Z(pt())}).passthrough())}).passthrough(),Zt=At.extend({protocolVersion:q(),capabilities:Xt,serverInfo:Kt,instructions:Z(q())}),Qt=kt.extend({method:X(`notifications/initialized`)}),$t=e=>Qt.safeParse(e).success,en=Dt.extend({method:X(`ping`)}),tn=Y({progress:ft(),total:Z(ft()),message:Z(q())}).passthrough(),nn=kt.extend({method:X(`notifications/progress`),params:Ot.merge(tn).extend({progressToken:Ct})}),rn=Dt.extend({params:Et.extend({cursor:Z(wt)}).optional()}),an=At.extend({nextCursor:Z(wt)}),on=Y({uri:q(),mimeType:Z(q()),_meta:Z(Y({}).passthrough())}).passthrough(),sn=on.extend({text:q()}),cn=q().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),ln=on.extend({blob:cn}),un=Gt.extend({uri:q(),description:Z(q()),mimeType:Z(q()),icons:Z(J(Wt)),_meta:Z(Y({}).passthrough())}),dn=Gt.extend({uriTemplate:q(),description:Z(q()),mimeType:Z(q()),_meta:Z(Y({}).passthrough())}),fn=rn.extend({method:X(`resources/list`)}),pn=an.extend({resources:J(un)}),mn=rn.extend({method:X(`resources/templates/list`)}),hn=an.extend({resourceTemplates:J(dn)}),gn=Dt.extend({method:X(`resources/read`),params:Et.extend({uri:q()})}),_n=At.extend({contents:J(gt([sn,ln]))}),vn=kt.extend({method:X(`notifications/resources/list_changed`)}),yn=Dt.extend({method:X(`resources/subscribe`),params:Et.extend({uri:q()})}),bn=Dt.extend({method:X(`resources/unsubscribe`),params:Et.extend({uri:q()})}),xn=kt.extend({method:X(`notifications/resources/updated`),params:Ot.extend({uri:q()})}),Sn=Y({name:q(),description:Z(q()),required:Z(pt())}).passthrough(),Cn=Gt.extend({description:Z(q()),arguments:Z(J(Sn)),icons:Z(J(Wt)),_meta:Z(Y({}).passthrough())}),wn=rn.extend({method:X(`prompts/list`)}),Tn=an.extend({prompts:J(Cn)}),En=Dt.extend({method:X(`prompts/get`),params:Et.extend({name:q(),arguments:Z(vt(q()))})}),Dn=Y({type:X(`text`),text:q(),_meta:Z(Y({}).passthrough())}).passthrough(),On=Y({type:X(`image`),data:cn,mimeType:q(),_meta:Z(Y({}).passthrough())}).passthrough(),kn=Y({type:X(`audio`),data:cn,mimeType:q(),_meta:Z(Y({}).passthrough())}).passthrough(),An=Y({type:X(`resource`),resource:gt([sn,ln]),_meta:Z(Y({}).passthrough())}).passthrough(),jn=un.extend({type:X(`resource_link`)}),Mn=gt([Dn,On,kn,jn,An]),Nn=Y({role:yt([`user`,`assistant`]),content:Mn}).passthrough(),Pn=At.extend({description:Z(q()),messages:J(Nn)}),Fn=kt.extend({method:X(`notifications/prompts/list_changed`)}),In=Y({title:Z(q()),readOnlyHint:Z(pt()),destructiveHint:Z(pt()),idempotentHint:Z(pt()),openWorldHint:Z(pt())}).passthrough(),Ln=Gt.extend({description:Z(q()),inputSchema:Y({type:X(`object`),properties:Z(Y({}).passthrough()),required:Z(J(q()))}).passthrough(),outputSchema:Z(Y({type:X(`object`),properties:Z(Y({}).passthrough()),required:Z(J(q()))}).passthrough()),annotations:Z(In),icons:Z(J(Wt)),_meta:Z(Y({}).passthrough())}),Rn=rn.extend({method:X(`tools/list`)}),zn=an.extend({tools:J(Ln)}),Bn=At.extend({content:J(Mn).default([]),structuredContent:Y({}).passthrough().optional(),isError:Z(pt())});Bn.or(At.extend({toolResult:ht()}));const Vn=Dt.extend({method:X(`tools/call`),params:Et.extend({name:q(),arguments:Z(vt(ht()))})}),Hn=kt.extend({method:X(`notifications/tools/list_changed`)}),Un=yt([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Wn=Dt.extend({method:X(`logging/setLevel`),params:Et.extend({level:Un})}),Gn=kt.extend({method:X(`notifications/message`),params:Ot.extend({level:Un,logger:Z(q()),data:ht()})}),Kn=Y({name:q().optional()}).passthrough(),qn=Y({hints:Z(J(Kn)),costPriority:Z(ft().min(0).max(1)),speedPriority:Z(ft().min(0).max(1)),intelligencePriority:Z(ft().min(0).max(1))}).passthrough(),Jn=Y({role:yt([`user`,`assistant`]),content:gt([Dn,On,kn])}).passthrough(),Yn=Dt.extend({method:X(`sampling/createMessage`),params:Et.extend({messages:J(Jn),systemPrompt:Z(q()),includeContext:Z(yt([`none`,`thisServer`,`allServers`])),temperature:Z(ft()),maxTokens:ft().int(),stopSequences:Z(J(q())),metadata:Z(Y({}).passthrough()),modelPreferences:Z(qn)})}),Xn=At.extend({model:q(),stopReason:Z(yt([`endTurn`,`stopSequence`,`maxTokens`]).or(q())),role:yt([`user`,`assistant`]),content:_t(`type`,[Dn,On,kn])}),Zn=Y({type:X(`boolean`),title:Z(q()),description:Z(q()),default:Z(pt())}).passthrough(),Qn=Y({type:X(`string`),title:Z(q()),description:Z(q()),minLength:Z(ft()),maxLength:Z(ft()),format:Z(yt([`email`,`uri`,`date`,`date-time`]))}).passthrough(),$n=Y({type:yt([`number`,`integer`]),title:Z(q()),description:Z(q()),minimum:Z(ft()),maximum:Z(ft())}).passthrough(),er=Y({type:X(`string`),title:Z(q()),description:Z(q()),enum:J(q()),enumNames:Z(J(q()))}).passthrough(),tr=gt([Zn,Qn,$n,er]),nr=Dt.extend({method:X(`elicitation/create`),params:Et.extend({message:q(),requestedSchema:Y({type:X(`object`),properties:vt(q(),tr),required:Z(J(q()))}).passthrough()})}),rr=At.extend({action:yt([`accept`,`decline`,`cancel`]),content:Z(vt(q(),ht()))}),ir=Y({type:X(`ref/resource`),uri:q()}).passthrough(),ar=Y({type:X(`ref/prompt`),name:q()}).passthrough(),or=Dt.extend({method:X(`completion/complete`),params:Et.extend({ref:gt([ar,ir]),argument:Y({name:q(),value:q()}).passthrough(),context:Z(Y({arguments:Z(vt(q(),q()))}))})}),sr=At.extend({completion:Y({values:J(q()).max(100),total:Z(ft().int()),hasMore:Z(pt())}).passthrough()}),cr=Y({uri:q().startsWith(`file://`),name:Z(q()),_meta:Z(Y({}).passthrough())}).passthrough(),lr=Dt.extend({method:X(`roots/list`)}),ur=At.extend({roots:J(cr)}),dr=kt.extend({method:X(`notifications/roots/list_changed`)});gt([en,Jt,or,Wn,En,wn,fn,mn,gn,yn,bn,Vn,Rn]),gt([Ut,nn,Qt,dr]),gt([Ht,Xn,rr,ur]),gt([en,Yn,nr,lr]),gt([Ut,nn,Gn,xn,vn,Hn,Fn]),gt([Ht,Zt,sr,Pn,Tn,pn,hn,_n,Bn,zn]);var fr=class extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}},pr=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},mr=class extends pr{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},hr=class extends pr{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},gr=class extends pr{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})}};const _r={APP_VERSION:`1.0.55`,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`}]},vr=f.get,yr=_r.APP_VERSION,br=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},xr=e=>{try{let t=new URL(e),n=t.pathname.split(`/`).filter(Boolean)[0]===`ingest`?`/ingest`:``;return`${t.protocol}//${t.host}${n}/endpoint-logs`}catch{return null}},Sr=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}},Cr=r(),wr=vr(`NODE_ENV`).default(_r.NODE_ENV||`development`).asEnum([`development`,`production`,`staging`,`test`]),Tr=vr(`DEBUG`).default(`false`).asBool()||vr(`MCP_GATEWAY_DEBUG`).default(`false`).asBool(),Er=vr(`MCP_GATEWAY_SCANNER_URL`).default(``).asString()||null,Dr=vr(`MCP_GATEWAY_SCANNER_API_KEY`).default(``).asString()||void 0,Or=vr(`MCP_GATEWAY_MIRROR_URL`).default(``).asString()||null,kr=(()=>{let e=vr(`MCP_GATEWAY_SCANNER_HEADERS`).required(!1).asString();return e?br(e):{}})(),Ar=vr(`MCP_GATEWAY_SCANNER_TIMEOUT_MS`).default(`20000`).asIntPositive(),jr=vr(`MCP_GATEWAY_SCANNER_FAIL_OPEN`).default(`true`).asBool(),Mr=vr(`MCP_GATEWAY_COMMAND`).default(`mcp-gateway`).asString(),Nr=vr(`CLIENT_APP_NAME`).default(``).asString(),Pr=vr(`MCP_GATEWAY_LOG_DIR`).default(l(m(),`.onyx`,`mcp-gateway`,`logs`)).asString(),Fr=vr(`MCP_GATEWAY_OAUTH_DIR`).default(l(m(),`.onyx`,`mcp-gateway`,`oauth`)).asString(),Ir=(()=>vr(`MCP_GATEWAY_ACCESS_CONTROL_URL`).default(``).asString()||(Er?Sr(Er):null))(),Lr=(()=>{let e=vr(`MCP_GATEWAY_ACCESS_CONTROL_HEADERS`).required(!1).asString();return e?br(e):{}})(),Rr=vr(`MCP_GATEWAY_ACCESS_CONTROL_TIMEOUT_MS`).default(`3000`).asIntPositive(),zr=vr(`MCP_GATEWAY_LOG_INGEST_ENABLED`).default(`true`).asBool(),Br=vr(`MCP_GATEWAY_LOG_INGEST_TIMEOUT_MS`).default(`5000`).asIntPositive(),Vr=(()=>vr(`MCP_GATEWAY_LOG_INGEST_URL`).default(``).asString()||(Or?xr(Or):Er?xr(Er):null))(),Hr={accessControl:{enabled:!!(Ir&&Dr),headers:Lr,timeoutMs:Rr,url:Ir},appVersion:yr,clientAppName:Nr,debug:Tr,environment:wr,logDir:Pr,logIngest:{apiKey:Dr,enabled:zr&&!!(Vr&&Dr),timeoutMs:Br,url:Vr},oauthDir:Fr,proxyCommand:Mr,scanner:{apiKey:Dr,enabled:!!Er,failOpen:jr,headers:kr,timeoutMs:Ar,url:Er}};var Ur=e(((exports,n)=>{n.exports=t(`util`).deprecate})),Wr=e(((exports,n)=>{n.exports=t(`stream`)})),Gr=e(((exports,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),Kr=e(((exports,t)=>{let n={};function r(e,t,r){r||=Error;function i(e,n,r){return typeof t==`string`?t:t(e,n,r)}class a extends r{constructor(e,t,n){super(i(e,t,n))}}a.prototype.name=r.name,a.prototype.code=e,n[e]=a}function i(e,t){if(Array.isArray(e)){let n=e.length;return e=e.map(e=>String(e)),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return`of ${t} ${String(e)}`}function a(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function o(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function s(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}r(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),r(`ERR_INVALID_ARG_TYPE`,function(e,t,n){let r;typeof t==`string`&&a(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;let c;if(o(e,` argument`))c=`The ${e} ${r} ${i(t,`type`)}`;else{let n=s(e,`.`)?`property`:`argument`;c=`The "${e}" ${n} ${r} ${i(t,`type`)}`}return c+=`. Received type ${typeof n}`,c},TypeError),r(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),r(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),r(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),r(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),r(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),r(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),r(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),r(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),r(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),r(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=n})),qr=e(((exports,t)=>{var n=Kr().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16*1024}t.exports={getHighWaterMark:i}})),Jr=e(((exports,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Yr=e(((exports,n)=>{try{var r=t(`util`);if(typeof r.inherits!=`function`)throw``;n.exports=r.inherits}catch{n.exports=Jr()}})),Xr=e(((exports,n)=>{function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r(Object(n),!0).forEach(function(t){a(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function a(e,t,n){return t=l(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function s(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,l(r.key),r)}}function c(e,t,n){return t&&s(e.prototype,t),n&&s(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function l(e){var t=u(e,`string`);return typeof t==`symbol`?t:String(t)}function u(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var d=t(`buffer`),f=d.Buffer,p=t(`util`),m=p.inspect,h=m&&m.custom||`inspect`;function g(e,t,n){f.prototype.copy.call(e,t,n)}n.exports=function(){function e(){o(this,e),this.head=null,this.tail=null,this.length=0}return c(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return f.alloc(0);for(var t=f.allocUnsafe(e>>>0),n=this.head,r=0;n;)g(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=f.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:h,value:function(e,t){return m(this,i(i({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),Zr=e(((exports,n)=>{
2
2
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
3
3
  var r=t(`buffer`),i=r.Buffer;function a(e,t){for(var n in e)t[n]=e[n]}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?n.exports=r:(a(r,exports),exports.Buffer=o);function o(e,t,n){return i(e,t,n)}o.prototype=Object.create(i.prototype),a(i,o),o.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return i(e,t,n)},o.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var r=i(e);return t===void 0?r.fill(0):typeof n==`string`?r.fill(t,n):r.fill(t),r},o.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return i(e)},o.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r.SlowBuffer(e)}})),Qr=e((exports=>{var t=Zr().Buffer,n=t.isEncoding||function(e){switch(e=``+e,e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function r(e){if(!e)return`utf8`;for(var t;;)switch(e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:if(t)return;e=(``+e).toLowerCase(),t=!0}}function i(e){var i=r(e);if(typeof i!=`string`&&(t.isEncoding===n||!n(e)))throw Error(`Unknown encoding: `+e);return i||e}exports.StringDecoder=a;function a(e){this.encoding=i(e);var n;switch(this.encoding){case`utf16le`:this.text=f,this.end=p,n=4;break;case`utf8`:this.fillLast=l,n=4;break;case`base64`:this.text=m,this.end=h,n=3;break;default:this.write=g,this.end=_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}a.prototype.write=function(e){if(e.length===0)return``;var t,n;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return``;n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||``},a.prototype.end=d,a.prototype.text=u,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function c(e,t,n){if((t[0]&192)!=128)return e.lastNeed=0,`�`;if(e.lastNeed>1&&t.length>1){if((t[1]&192)!=128)return e.lastNeed=1,`�`;if(e.lastNeed>2&&t.length>2&&(t[2]&192)!=128)return e.lastNeed=2,`�`}}function l(e){var t=this.lastTotal-this.lastNeed,n=c(this,e,t);if(n!==void 0)return n;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function u(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString(`utf8`,t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString(`utf8`,t,r)}function d(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+`�`:t}function f(e,t){if((e.length-t)%2==0){var n=e.toString(`utf16le`,t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(`utf16le`,t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):``;if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(`utf16le`,0,n)}return t}function m(e,t){var n=(e.length-t)%3;return n===0?e.toString(`base64`,t):(this.lastNeed=3-n,this.lastTotal=3,n===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(`base64`,t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+this.lastChar.toString(`base64`,0,3-this.lastNeed):t}function g(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):``}})),$r=e(((exports,t)=>{var n=Kr().codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;var n=[...arguments];e.apply(this,n)}}}function i(){}function a(e){return e.setHeader&&typeof e.abort==`function`}function o(e,t,s){if(typeof t==`function`)return o(e,null,t);t||={},s=r(s||i);var c=t.readable||t.readable!==!1&&e.readable,l=t.writable||t.writable!==!1&&e.writable,u=function(){e.writable||f()},d=e._writableState&&e._writableState.finished,f=function(){l=!1,d=!0,c||s.call(e)},p=e._readableState&&e._readableState.endEmitted,m=function(){c=!1,p=!0,l||s.call(e)},h=function(t){s.call(e,t)},g=function(){var t;if(c&&!p)return(!e._readableState||!e._readableState.ended)&&(t=new n),s.call(e,t);if(l&&!d)return(!e._writableState||!e._writableState.ended)&&(t=new n),s.call(e,t)},_=function(){e.req.on(`finish`,f)};return a(e)?(e.on(`complete`,f),e.on(`abort`,g),e.req?_():e.on(`request`,_)):l&&!e._writableState&&(e.on(`end`,u),e.on(`close`,u)),e.on(`end`,m),e.on(`finish`,f),t.error!==!1&&e.on(`error`,h),e.on(`close`,g),function(){e.removeListener(`complete`,f),e.removeListener(`abort`,g),e.removeListener(`request`,_),e.req&&e.req.removeListener(`finish`,f),e.removeListener(`end`,u),e.removeListener(`close`,u),e.removeListener(`finish`,f),e.removeListener(`end`,m),e.removeListener(`error`,h),e.removeListener(`close`,g)}}t.exports=o})),ei=e(((exports,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=$r(),s=Symbol(`lastResolve`),c=Symbol(`lastReject`),l=Symbol(`error`),u=Symbol(`ended`),d=Symbol(`lastPromise`),f=Symbol(`handlePromise`),p=Symbol(`stream`);function m(e,t){return{value:e,done:t}}function h(e){var t=e[s];if(t!==null){var n=e[p].read();n!==null&&(e[d]=null,e[s]=null,e[c]=null,t(m(n,!1)))}}function g(e){process.nextTick(h,e)}function _(e,t){return function(n,r){e.then(function(){if(t[u]){n(m(void 0,!0));return}t[f](n,r)},r)}}var v=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((n={get stream(){return this[p]},next:function(){var e=this,t=this[l];if(t!==null)return Promise.reject(t);if(this[u])return Promise.resolve(m(void 0,!0));if(this[p].destroyed)return new Promise(function(t,n){process.nextTick(function(){e[l]?n(e[l]):t(m(void 0,!0))})});var n=this[d],r;if(n)r=new Promise(_(n,this));else{var i=this[p].read();if(i!==null)return Promise.resolve(m(i,!1));r=new Promise(this[f])}return this[d]=r,r}},r(n,Symbol.asyncIterator,function(){return this}),r(n,`return`,function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){if(e){n(e);return}t(m(void 0,!0))})})}),n),v);t.exports=function(e){var t,n=Object.create(y,(t={},r(t,p,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,f,{value:function(e,t){var r=n[p].read();r?(n[d]=null,n[s]=null,n[c]=null,e(m(r,!1))):(n[s]=e,n[c]=t)},writable:!0}),t));return n[d]=null,o(e,function(e){if(e&&e.code!==`ERR_STREAM_PREMATURE_CLOSE`){var t=n[c];t!==null&&(n[d]=null,n[s]=null,n[c]=null,t(e)),n[l]=e;return}var r=n[s];r!==null&&(n[d]=null,n[s]=null,n[c]=null,r(m(void 0,!0))),n[u]=!0}),e.on(`readable`,g.bind(null,n)),n}})),ti=e(((exports,t)=>{function n(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function r(e){return function(){var t=this,r=arguments;return new Promise(function(i,a){var o=e.apply(t,r);function s(e){n(o,i,a,s,c,`next`,e)}function c(e){n(o,i,a,s,c,`throw`,e)}s(void 0)})}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return t=s(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:String(t)}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var l=Kr().codes.ERR_INVALID_ARG_TYPE;function u(e,t,n){var i;if(t&&typeof t.next==`function`)i=t;else if(t&&t[Symbol.asyncIterator])i=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])i=t[Symbol.iterator]();else throw new l(`iterable`,[`Iterable`],t);var o=new e(a({objectMode:!0},n)),s=!1;o._read=function(){s||(s=!0,c())};function c(){return u.apply(this,arguments)}function u(){return u=r(function*(){try{var e=yield i.next(),t=e.value;e.done?o.push(null):o.push(yield t)?c():s=!1}catch(e){o.destroy(e)}}),u.apply(this,arguments)}return o}t.exports=u})),ni=e(((exports,n)=>{n.exports=O;var r;O.ReadableState=D,t(`events`).EventEmitter;var i=function(e,t){return e.listeners(t).length},a=Wr(),o=t(`buffer`).Buffer,s=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function c(e){return o.from(e)}function l(e){return o.isBuffer(e)||e instanceof s}var u=t(`util`),d=u&&u.debuglog?u.debuglog(`stream`):function(){},f=Xr(),p=Gr(),m=qr(),h=m.getHighWaterMark,g=Kr().codes,_=g.ERR_INVALID_ARG_TYPE,v=g.ERR_STREAM_PUSH_AFTER_EOF,y=g.ERR_METHOD_NOT_IMPLEMENTED,b=g.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,x,S,C;Yr()(O,a);var w=p.errorOrDestroy,T=[`error`,`close`,`destroy`,`pause`,`resume`];function E(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function D(e,t,n){r||=ri(),e||={},typeof n!=`boolean`&&(n=t instanceof r),this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=h(this,e,`readableHighWaterMark`,n),this.buffer=new f,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(x||=Qr().StringDecoder,this.decoder=new x(e.encoding),this.encoding=e.encoding)}function O(e){if(r||=ri(),!(this instanceof O))return new O(e);var t=this instanceof r;this._readableState=new D(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),a.call(this)}Object.defineProperty(O.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),O.prototype.destroy=p.destroy,O.prototype._undestroy=p.undestroy,O.prototype._destroy=function(e,t){t(e)},O.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=o.from(e,t),t=``),r=!0),k(this,e,t,!1,r)},O.prototype.unshift=function(e){return k(this,e,null,!0,!1)};function k(e,t,n,r,i){d(`readableAddChunk`,t);var a=e._readableState;if(t===null)a.reading=!1,P(e,a);else{var s;if(i||(s=ee(a,t)),s)w(e,s);else if(a.objectMode||t&&t.length>0)if(typeof t!=`string`&&!a.objectMode&&Object.getPrototypeOf(t)!==o.prototype&&(t=c(t)),r)a.endEmitted?w(e,new b):A(e,a,t,!0);else if(a.ended)w(e,new v);else if(a.destroyed)return!1;else a.reading=!1,a.decoder&&!n?(t=a.decoder.write(t),a.objectMode||t.length!==0?A(e,a,t,!1):I(e,a)):A(e,a,t,!1);else r||(a.reading=!1,I(e,a))}return!a.ended&&(a.length<a.highWaterMark||a.length===0)}function A(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&F(e)),I(e,t)}function ee(e,t){var n;return!l(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new _(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}O.prototype.isPaused=function(){return this._readableState.flowing===!1},O.prototype.setEncoding=function(e){x||=Qr().StringDecoder;var t=new x(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var j=1073741824;function M(e){return e>=j?e=j:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function N(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=M(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}O.prototype.read=function(e){d(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return d(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?W(this):F(this),null;if(e=N(e,t),e===0&&t.ended)return t.length===0&&W(this),null;var r=t.needReadable;d(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,d(`length less than watermark`,r)),t.ended||t.reading?(r=!1,d(`reading or ended`,r)):r&&(d(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=N(n,t)));var i=e>0?U(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&W(this)),i!==null&&this.emit(`data`,i),i};function P(e,t){if(d(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?F(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,te(e)))}}function F(e){var t=e._readableState;d(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(te,e))}function te(e){var t=e._readableState;d(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,H(e)}function I(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(L,e,t))}function L(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(d(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}O.prototype._read=function(e){w(this,new y(`_read()`))},O.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e);break}r.pipesCount+=1,d(`pipe count=%d opts=%j`,r.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;r.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){d(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,u())}function s(){d(`onend`),e.end()}var c=ne(n);e.on(`drain`,c);var l=!1;function u(){d(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,r.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){d(`ondata`);var i=e.write(t);d(`dest.write`,i),i===!1&&((r.pipesCount===1&&r.pipes===e||r.pipesCount>1&&re(r.pipes,e)!==-1)&&!l&&(d(`false write response, pause`,r.awaitDrain),r.awaitDrain++),n.pause())}function p(t){d(`onerror`,t),g(),e.removeListener(`error`,p),i(e,`error`)===0&&w(e,t)}E(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){d(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){d(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),r.flowing||(d(`pipe resume`),n.resume()),e};function ne(e){return function(){var t=e._readableState;d(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&i(e,`data`)&&(t.flowing=!0,H(e))}}O.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=re(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},O.prototype.on=function(e,t){var n=a.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,d(`on readable`,r.length,r.reading),r.length?F(this):r.reading||process.nextTick(z,this)),n},O.prototype.addListener=O.prototype.on,O.prototype.removeListener=function(e,t){var n=a.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(R,this),n},O.prototype.removeAllListeners=function(e){var t=a.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(R,this),t};function R(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function z(e){d(`readable nexttick read 0`),e.read(0)}O.prototype.resume=function(){var e=this._readableState;return e.flowing||(d(`resume`),e.flowing=!e.readableListening,B(this,e)),e.paused=!1,this};function B(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(V,e,t))}function V(e,t){d(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),H(e),t.flowing&&!t.reading&&e.read(0)}O.prototype.pause=function(){return d(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(d(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function H(e){var t=e._readableState;for(d(`flow`,t.flowing);t.flowing&&e.read()!==null;);}O.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(d(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){d(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(!n.objectMode&&(!i||!i.length)||t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<T.length;a++)e.on(T[a],this.emit.bind(this,T[a]));return this._read=function(t){d(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(O.prototype[Symbol.asyncIterator]=function(){return S===void 0&&(S=ei()),S(this)}),Object.defineProperty(O.prototype,`readableHighWaterMark`,{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(O.prototype,`readableBuffer`,{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(O.prototype,`readableFlowing`,{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),O._fromList=U,Object.defineProperty(O.prototype,`readableLength`,{enumerable:!1,get:function(){return this._readableState.length}});function U(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function W(e){var t=e._readableState;d(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(G,t,e))}function G(e,t){if(d(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(O.from=function(e,t){return C===void 0&&(C=ti()),C(O,e,t)});function re(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),ri=e(((exports,t)=>{var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var r=ni(),i=ii();Yr()(c,r);for(var a=n(i.prototype),o=0;o<a.length;o++){var s=a[o];c.prototype[s]||(c.prototype[s]=i.prototype[s])}function c(e){if(!(this instanceof c))return new c(e);r.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once(`end`,l)))}Object.defineProperty(c.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function l(){this._writableState.ended||process.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(c.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})})),ii=e(((exports,n)=>{n.exports=D;function r(e){var t=this;this.next=null,this.entry=null,this.finish=function(){V(t,e)}}var i;D.WritableState=T;var a={deprecate:Ur()},o=Wr(),s=t(`buffer`).Buffer,c=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function l(e){return s.from(e)}function u(e){return s.isBuffer(e)||e instanceof c}var d=Gr(),f=qr(),p=f.getHighWaterMark,m=Kr().codes,h=m.ERR_INVALID_ARG_TYPE,g=m.ERR_METHOD_NOT_IMPLEMENTED,_=m.ERR_MULTIPLE_CALLBACK,v=m.ERR_STREAM_CANNOT_PIPE,y=m.ERR_STREAM_DESTROYED,b=m.ERR_STREAM_NULL_VALUES,x=m.ERR_STREAM_WRITE_AFTER_END,S=m.ERR_UNKNOWN_ENCODING,C=d.errorOrDestroy;Yr()(D,o);function w(){}function T(e,t,n){i||=ri(),e||={},typeof n!=`boolean`&&(n=t instanceof i),this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=p(this,e,`writableHighWaterMark`,n),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1,this.decodeStrings=e.decodeStrings!==!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){P(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new r(this)}T.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},(function(){try{Object.defineProperty(T.prototype,`buffer`,{get:a.deprecate(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`,`DEP0003`)})}catch{}})();var E;typeof Symbol==`function`&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==`function`?(E=Function.prototype[Symbol.hasInstance],Object.defineProperty(D,Symbol.hasInstance,{value:function(e){return E.call(this,e)?!0:this===D?e&&e._writableState instanceof T:!1}})):E=function(e){return e instanceof this};function D(e){i||=ri();var t=this instanceof i;if(!t&&!E.call(D,this))return new D(e);this._writableState=new T(e,this,t),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev),typeof e.destroy==`function`&&(this._destroy=e.destroy),typeof e.final==`function`&&(this._final=e.final)),o.call(this)}D.prototype.pipe=function(){C(this,new v)};function O(e,t){var n=new x;C(e,n),process.nextTick(t,n)}function k(e,t,n,r){var i;return n===null?i=new b:typeof n!=`string`&&!t.objectMode&&(i=new h(`chunk`,[`string`,`Buffer`],n)),i?(C(e,i),process.nextTick(r,i),!1):!0}D.prototype.write=function(e,t,n){var r=this._writableState,i=!1,a=!r.objectMode&&u(e);return a&&!s.isBuffer(e)&&(e=l(e)),typeof t==`function`&&(n=t,t=null),a?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=w),r.ending?O(this,n):(a||k(this,r,e,n))&&(r.pendingcb++,i=ee(this,r,a,e,t,n)),i},D.prototype.cork=function(){this._writableState.corked++},D.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&I(this,e))},D.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw new S(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(D.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function A(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=s.from(t,n)),t}Object.defineProperty(D.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function ee(e,t,n,r,i,a){if(!n){var o=A(t,r,i);r!==o&&(n=!0,i=`buffer`,r=o)}var s=t.objectMode?1:r.length;t.length+=s;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else j(e,t,!1,s,r,i,a);return c}function j(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new y(`write`)):n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function M(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(z,e,t),e._writableState.errorEmitted=!0,C(e,r)):(i(r),e._writableState.errorEmitted=!0,C(e,r),z(e,t))}function N(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function P(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new _;if(N(n),t)M(e,n,r,t,i);else{var a=L(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&I(e,n),r?process.nextTick(F,e,n,a,i):F(e,n,a,i)}}function F(e,t,n,r){n||te(e,t),t.pendingcb--,r(),z(e,t)}function te(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function I(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var i=t.bufferedRequestCount,a=Array(i),o=t.corkedRequestsFree;o.entry=n;for(var s=0,c=!0;n;)a[s]=n,n.isBuf||(c=!1),n=n.next,s+=1;a.allBuffers=c,j(e,t,!0,t.length,a,``,o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new r(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,u=n.encoding,d=n.callback,f=t.objectMode?1:l.length;if(j(e,t,!1,f,l,u,d),n=n.next,t.bufferedRequestCount--,t.writing)break}n===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}D.prototype._write=function(e,t,n){n(new g(`_write()`))},D.prototype._writev=null,D.prototype.end=function(e,t,n){var r=this._writableState;return typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||B(this,r,n),this},Object.defineProperty(D.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function L(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function ne(e,t){e._final(function(n){t.pendingcb--,n&&C(e,n),t.prefinished=!0,e.emit(`prefinish`),z(e,t)})}function R(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(ne,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function z(e,t){var n=L(t);if(n&&(R(e,t),t.pendingcb===0&&(t.finished=!0,e.emit(`finish`),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function B(e,t,n){t.ending=!0,z(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function V(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}Object.defineProperty(D.prototype,`destroyed`,{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),D.prototype.destroy=d.destroy,D.prototype._undestroy=d.undestroy,D.prototype._destroy=function(e,t){t(e)}})),ai=e((exports=>{exports.levels={error:0,warn:1,help:2,data:3,info:4,debug:5,prompt:6,verbose:7,input:8,silly:9},exports.colors={error:`red`,warn:`yellow`,help:`cyan`,data:`grey`,info:`green`,debug:`blue`,prompt:`grey`,verbose:`cyan`,input:`grey`,silly:`magenta`}})),oi=e((exports=>{exports.levels={error:0,warn:1,info:2,http:3,verbose:4,debug:5,silly:6},exports.colors={error:`red`,warn:`yellow`,info:`green`,http:`green`,verbose:`cyan`,debug:`blue`,silly:`magenta`}})),si=e((exports=>{exports.levels={emerg:0,alert:1,crit:2,error:3,warning:4,notice:5,info:6,debug:7},exports.colors={emerg:`red`,alert:`yellow`,crit:`red`,error:`red`,warning:`red`,notice:`yellow`,info:`green`,debug:`blue`}})),ci=e((exports=>{Object.defineProperty(exports,`cli`,{value:ai()}),Object.defineProperty(exports,`npm`,{value:oi()}),Object.defineProperty(exports,`syslog`,{value:si()})})),li=e((exports=>{Object.defineProperty(exports,`LEVEL`,{value:Symbol.for(`level`)}),Object.defineProperty(exports,`MESSAGE`,{value:Symbol.for(`message`)}),Object.defineProperty(exports,`SPLAT`,{value:Symbol.for(`splat`)}),Object.defineProperty(exports,`configs`,{value:ci()})})),ui=e(((exports,n)=>{let r=t(`util`),i=ii(),{LEVEL:a}=li(),o=n.exports=function(e={}){i.call(this,{objectMode:!0,highWaterMark:e.highWaterMark}),this.format=e.format,this.level=e.level,this.handleExceptions=e.handleExceptions,this.handleRejections=e.handleRejections,this.silent=e.silent,e.log&&(this.log=e.log),e.logv&&(this.logv=e.logv),e.close&&(this.close=e.close),this.once(`pipe`,e=>{this.levels=e.levels,this.parent=e}),this.once(`unpipe`,e=>{e===this.parent&&(this.parent=null,this.close&&this.close())})};r.inherits(o,i),o.prototype._write=function(e,t,n){if(this.silent||e.exception===!0&&!this.handleExceptions)return n(null);let r=this.level||this.parent&&this.parent.level;if(!r||this.levels[r]>=this.levels[e[a]]){if(e&&!this.format)return this.log(e,n);let t,r;try{r=this.format.transform(Object.assign({},e),this.format.options)}catch(e){t=e}if(t||!r){if(n(),t)throw t;return}return this.log(r,n)}return this._writableState.sync=!1,n(null)},o.prototype._writev=function(e,t){if(this.logv){let n=e.filter(this._accept,this);return n.length?this.logv(n,t):t(null)}for(let n=0;n<e.length;n++){if(!this._accept(e[n]))continue;if(e[n].chunk&&!this.format){this.log(e[n].chunk,e[n].callback);continue}let r,i;try{i=this.format.transform(Object.assign({},e[n].chunk),this.format.options)}catch(e){r=e}if(r||!i){if(e[n].callback(),r)throw t(null),r}else this.log(i,e[n].callback)}return t(null)},o.prototype._accept=function(e){let t=e.chunk;if(this.silent)return!1;let n=this.level||this.parent&&this.parent.level;return!!((t.exception===!0||!n||this.levels[n]>=this.levels[t[a]])&&(this.handleExceptions||t.exception!==!0))},o.prototype._nop=function(){}})),di=e(((exports,n)=>{let r=t(`util`),{LEVEL:i}=li(),a=ui(),o=n.exports=function(e={}){if(a.call(this,e),!e.transport||typeof e.transport.log!=`function`)throw Error(`Invalid transport, must be an object with a log method.`);this.transport=e.transport,this.level=this.level||e.transport.level,this.handleExceptions=this.handleExceptions||e.transport.handleExceptions,this._deprecated();function t(e){this.emit(`error`,e,this.transport)}this.transport.__winstonError||(this.transport.__winstonError=t.bind(this),this.transport.on(`error`,this.transport.__winstonError))};r.inherits(o,a),o.prototype._write=function(e,t,n){if(this.silent||e.exception===!0&&!this.handleExceptions)return n(null);(!this.level||this.levels[this.level]>=this.levels[e[i]])&&this.transport.log(e[i],e.message,e,this._nop),n(null)},o.prototype._writev=function(e,t){for(let t=0;t<e.length;t++)this._accept(e[t])&&(this.transport.log(e[t].chunk[i],e[t].chunk.message,e[t].chunk,this._nop),e[t].callback());return t(null)},o.prototype._deprecated=function(){console.error([`${this.transport.name} is a legacy winston transport. Consider upgrading: `,`- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md`].join(`
4
4
  `))},o.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener(`error`,this.transport.__winstonError),this.transport.__winstonError=null)}})),fi=n(e(((exports,t)=>{t.exports=ui(),t.exports.LegacyTransportStream=di()}))(),1);const pi=new Set([`apikey`,`auth`,`credential`,`key`,`password`,`secret`,`token`]);var mi=class extends fi.default{apiKey;extraAttributes;httpTimeout;ingestUrl;pendingRequests=new Set;constructor(e){super({}),this.apiKey=e.apiKey,this.ingestUrl=e.ingestUrl,this.httpTimeout=e.httpTimeout??5e3;let t=h()||`unknown`;this.extraAttributes={arch:p(),hostname:t,instance:`mcp-gateway-${t}`,os:g(),source:`onyx-mcp-gateway`,version:Hr.appVersion,workload:`mcp-gateway`}}async flush(e=5e3){let t=Array.from(this.pendingRequests);t.length!==0&&await Promise.race([Promise.all(t),new Promise(t=>setTimeout(t,e))])}log(e,t){setImmediate(()=>this.emit(`logged`,e));let n=this.enrichEntry(e),r=this.sendEntry(n);this.pendingRequests.add(r),r.finally(()=>this.pendingRequests.delete(r)),t()}enrichEntry(e){let t={...this.extraAttributes,level:(e.level||`info`).toUpperCase(),message:e.message||``,timestamp:e.timestamp||new Date().toISOString()};for(let[n,r]of Object.entries(e)){if([`level`,`message`,`timestamp`].includes(n))continue;pi.has(n.toLowerCase())?t[n]=`[REDACTED]`:t[n]=gi(r)}return t}async sendEntry(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.httpTimeout);try{let n=hi(e);await(await fetch(this.ingestUrl,{body:n,headers:{apikey:this.apiKey,"Content-Type":`application/json`,"x-source-type":`endpoint-logs`},method:`POST`,signal:t.signal})).text()}catch{}finally{clearTimeout(n)}}};function hi(e){try{return JSON.stringify(e)}catch(t){let n={_serializationError:!0,level:`ERROR`,message:`[Log entry could not be serialized]`,originalError:t instanceof Error?t.message:String(t),timestamp:new Date().toISOString()};if(e&&typeof e==`object`)for(let t of[`level`,`message`,`timestamp`,`source`,`workload`]){let r=e[t];typeof r==`string`&&(n[t]=r)}return JSON.stringify(n)}}function gi(e,t=0,n=new WeakSet){if(t>10)return`[max depth exceeded]`;if(e==null)return e;let r=typeof e;if(r===`string`||r===`number`||r===`boolean`)return r===`number`&&(Number.isNaN(e)||!Number.isFinite(e))?String(e):e;if(r===`function`)return`[Function: ${e.name||`anonymous`}]`;if(r===`symbol`)return`[Symbol: ${e.description||``}]`;if(r===`bigint`)return String(e);if(r===`object`){if(n.has(e))return`[Circular]`;if(n.add(e),e instanceof Date)return e.toISOString();if(e instanceof Error)return{message:e.message,name:e.name,stack:e.stack};if(e instanceof RegExp)return e.toString();if(e instanceof Map){let r={};for(let[i,a]of e){let e=typeof i==`string`?i:String(i);r[e]=gi(a,t+1,n)}return r}if(e instanceof Set)return Array.from(e).map(e=>gi(e,t+1,n));if(Array.isArray(e))return e.map(e=>gi(e,t+1,n));if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return`[Binary Data]`;let r={},i;try{i=Object.keys(e)}catch{return`[Object with inaccessible keys]`}for(let a of i){if(pi.has(a.toLowerCase())){r[a]=`[REDACTED]`;continue}try{let i=e[a];r[a]=gi(i,t+1,n)}catch{r[a]=`[Unserializable]`}}return r}return`[Unknown Type]`}const _i=a(),vi=new i;function yi(e,t){return vi.run({traceId:e},t)}let bi=_i;function xi(e){let t=e?.traceparent;if(t){let e=t.split(`-`);if(e.length>=2&&e[1])return e[1]}}function Si(){return vi.getStore()?.traceId??bi}function Ci(e){bi=e}const wi=Hr.logDir,Ti=Hr.debug?`debug`:`info`;let Ei=!1;try{o(wi)||s(wi,{recursive:!0}),Ei=!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: ${wi}`),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 Di=u.format.combine(u.format.timestamp(),u.format.errors({stack:!0}),u.format.json());let Oi=null;const ki=[];if(Ei){let e=new d({datePattern:`YYYY-MM-DD`,filename:l(wi,`mcp-gateway-%DATE%.log`),format:Di,handleExceptions:!1,handleRejections:!1,level:Ti,maxFiles:10,maxSize:`10m`});ki.push(e)}let Ai=null;const ji=Hr.logIngest.enabled&&Hr.logIngest.url&&Hr.logIngest.apiKey;ji&&(Ai=new mi({apiKey:Hr.logIngest.apiKey,httpTimeout:Hr.logIngest.timeoutMs,ingestUrl:Hr.logIngest.url}),ki.push(Ai));const Mi=u.format(e=>(e.traceId=Si(),e)),Ni=u.createLogger({defaultMeta:{service:`mcp-gateway`,version:Hr.appVersion},format:u.format.combine(Mi(),u.format.errors({stack:!0})),level:Ti,transports:ki}),Pi=e=>{let[t,...n]=e;if(typeof t!=`string`)return{message:String(t??``),meta:void 0,sessionData:Oi||void 0};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:Oi||void 0}},Q={debug:(...e)=>{let{message:t,meta:n,sessionData:r}=Pi(e);Ni.debug(t,{sessionData:r,...n})},error:(...e)=>{let{message:t,meta:n,sessionData:r}=Pi(e);Ni.error(t,{sessionData:r,...n})},getSessionData:()=>Oi,getTraceId:()=>Si(),info:(...e)=>{let{message:t,meta:n,sessionData:r}=Pi(e);Ni.info(t,{sessionData:r,...n})},setSessionData:e=>{Oi=e,Q.debug(`Session data set for logger`,e)},setTraceId:e=>{Ci(e),Q.debug(`Trace ID updated for logger`,{traceId:e})},warn:(...e)=>{let{message:t,meta:n,sessionData:r}=Pi(e);Ni.warn(t,{sessionData:r,...n})}},Fi=async e=>{Ai&&await Ai.flush(e)};Q.info(`MCP Gateway logger initialized`,{debug:Hr.debug,fileLoggingEnabled:Ei,ingestLoggingEnabled:ji,logDir:wi,logLevel:Ti});const Ii=Hr.clientAppName;let Li=null;const Ri=async()=>(Li||=await import(`systeminformation`),Li);function zi(){return l(m(),`.claude.json`)}function Bi(){return l(m(),`.codex`,`auth.json`)}function Vi(){try{return h()}catch{return`unknown-device`}}async function Hi(e){try{return(await v()).find(t=>t.pid===e)?.name||`unknown`}catch{return`unknown`}}async function Ui(){try{let e=(await(await Ri()).system()).serial;return e&&e!==``&&e!==`0`&&!e.toLowerCase().includes(`to be filled`)?e:void 0}catch{return}}function Wi(){try{let e=Ki();return e?.oauthAccount?.emailAddress?e.oauthAccount.emailAddress:qi()||void 0}catch{return}}function Gi(){try{let e=_();if(e.username)return e.username;throw Error(`userInfo() returned empty username`)}catch{return process.env.USER||process.env.USERNAME||process.env.LOGNAME}}function Ki(){try{let e=zi();if(!o(e))return null;let t=c(e,`utf-8`);return JSON.parse(t)}catch{return null}}function qi(){try{let e=Bi();if(!o(e))return null;let t=c(e,`utf-8`),n=JSON.parse(t)?.tokens?.id_token;if(!n)return null;let r=n.split(`.`);if(r.length!==3)return null;let i=Buffer.from(r[1],`base64url`).toString(`utf-8`);return JSON.parse(i).email||null}catch{return null}}const Ji=async()=>{let e=process.pid,t=process.ppid;try{let n=Vi(),[r,i]=await Promise.all([Ui(),Hi(t)]),a=Wi(),o=Gi();return{clientAppName:Ii||`unknown`,deviceName:n,email:a,gatewayVersion:Hr.appVersion,parentProcessId:t,parentProcessName:i,processId:e,systemSerialNumber:r,username:o}}catch{return{clientAppName:Ii||`unknown`,deviceName:`unknown-device`,email:void 0,gatewayVersion:Hr.appVersion,parentProcessId:t,parentProcessName:`unknown`,processId:e,systemSerialNumber:void 0,username:void 0}}};function Yi(e){let t=y(JSON.stringify(e));return Buffer.from(t).toString(`base64url`)}var Xi=class{clientAppName;clientInfoBase64;sessionData;get scannerConfig(){return{apiKey:this.config.scanApiKey,enabled:this.config.scanEnabled,failOpen:this.config.scanFailOpen,headers:this.config.scanHeaders,timeoutMs:this.config.scanTimeoutMs,url:this.config.scanUrl}}config;constructor(e,t){this.config=e,this.sessionData=t,this.clientAppName=t.clientAppName||``,this.clientInfoBase64=this.getClientInfoBase64()}async evaluate(e){let t={action:`allow`};if(this.isScanEnabled())try{if(t=await this.scan({data:e.data,id:e.id,method:e.method,originalRequestId:e.originalRequestId,timestamp:e.timestamp,type:e.type}),Q.info(`Scan result`,{action:t.action,id:e.id,method:e.method,originalRequestId:e.originalRequestId}),t.action===`block`)return Q.warn(`Request blocked by security policy`),t}catch(t){if(Q.error(`Scanning failed`,{error:t,method:e.method,requestType:e.type,scannerUrl:this.config.scanUrl}),!this.config.scanFailOpen)return Q.warn(`Scanning service unavailable, blocking traffic (fail-closed)`),{action:`block`};Q.warn(`Scanning service unavailable, allowing traffic (fail-open)`)}return t}isEnabled(){return this.isScanEnabled()}isScanEnabled(){return this.config.scanEnabled&&!!this.config.scanUrl}async scan(e){if(!this.isScanEnabled())return{action:`allow`};let t={data:e.data,id:e.id,metadata:this.sessionData,method:e.method,originalRequestId:e.originalRequestId,type:e.type};Q.info(`Scanning traffic`,{id:e.id,method:e.method,originalRequestId:e.originalRequestId,type:e.type});let n=await this.sendScanRequest(t);return Q.info(`Scan result`,{action:n.action,blockReason:n.block_reason,hasModifiedData:!!n.modified_data,id:e.id,originalRequestId:e.originalRequestId}),n}updateConfig(e){this.config={...this.config,...e}}getClientInfoBase64(){return Yi(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:Cr,...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 Zi=null;const Qi=async e=>{let t=await Ji(),n=e.cliArgs.proxyType,r={...t,proxyType:n,remoteCliArgs:n===`remote`?e.cliArgs:void 0,stdioCliArgs:n===`stdio`?e.cliArgs:void 0};return Q.setSessionData(r),Zi=new Xi(e,r),Zi},$i=()=>Zi,ea=new class{counts=new Map;lastLogTime=Date.now();logIntervalMs=6e4;increment(e){this.counts.set(e,(this.counts.get(e)||0)+1),this.maybeLog()}logAndReset(){if(this.counts.size===0)return;let e=(Array.from(this.counts.values()).reduce((e,t)=>e+t,0));Q.info(`Requests intercepted`,{byMethod:Object.fromEntries(this.counts),eventType:`mcp_requests_intercepted`,totalCount:e}),this.counts.clear(),this.lastLogTime=Date.now()}maybeLog(){Date.now()-this.lastLogTime>=this.logIntervalMs&&this.logAndReset()}},ta=()=>{ea.logAndReset()},na=e=>e.length>1&&e[1]&&typeof e[1]==`object`&&`requestId`in e[1]?e[1].requestId:void 0,ra=(e,t,n,i)=>async(...a)=>{ea.increment(e);let o=$i(),s=e,c=a[0],l=r(),u=na(a)?.toString();c&&typeof c==`object`&&`method`in c&&typeof c.method==`string`&&(s=c.method);let d=async(e,t,n)=>{try{if(!o?.isEnabled()&&!o?.isScanEnabled())return;let r;try{r=await o.evaluate({data:t,id:l,method:s,originalRequestId:u,timestamp:new Date().toISOString(),type:e})}catch(t){if(Q.error(`${e} evaluation failed, applying fail-safe`,{error:t}),o?.isScanEnabled()&&!o.scannerConfig?.failOpen)throw Error(`Security scanning service unavailable`);return}if(Q.info(`${e} scan result`,{action:r.action,id:l,method:s,...e===`request`&&{originalRequestId:u}}),r.action===`block`||r.action===`modify`){let t=r.action===`block`?`blocked`:`modified`,i=r.action===`block`&&e===`request`?`warn`:`log`;if(r.modified_data){if(r.action===`block`){let n=`${e} ${t} by security policy${e===`request`?`, returning error response`:``}`;return i===`warn`?Q.warn(n):Q.info(n),r.modified_data}if(n){let a=`${e} ${t} by security policy`;i===`warn`?Q.warn(a):Q.info(a),n(r.modified_data);return}return r.modified_data}Q.warn(`${r.action} action without modified_data, allowing original ${e}`)}return}catch(t){if(Q.error(`Unexpected error during ${e} processing`,{error:t}),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`)throw Q.error(`Security scanning unavailable (fail-closed)`,{error:n.message,handlerName:e,operation:t}),n;Q.error(`Unexpected error during request processing, continuing`,{error:n,handlerName:e,operation:t})}if(f!==void 0)return f;if(i&&!await i.isAllowed()){let n=i.getBlockReason();throw Q.warn(`MCP server blocked by access control`,{handlerName:e,operation:t,reason:n}),new mr(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){Q.error(`Error during response processing, returning original result`,{error:e})}return e}catch(n){if(n instanceof mr)throw Q.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){Q.warn(`Failed to evaluate error`,{evalError:e})}throw Q.error(`Handler error in ${e}`,{argsCount:a.length,errorMessage:n instanceof Error?n.message:String(n),operation:t}),n}},ia=async({authorizer:e,client:t,server:n,serverCapabilities:r})=>{r?.logging&&(n.setNotificationHandler(Gn,ra(`notifications/message`,`server-to-client`,async e=>t.notification(e),e)),t.setNotificationHandler(Gn,ra(`notifications/message`,`client-to-server`,async e=>n.notification(e),e))),r?.prompts&&(n.setRequestHandler(En,ra(`prompts/get`,`get`,async e=>t.getPrompt(e.params),e)),n.setRequestHandler(wn,ra(`prompts/list`,`list`,async e=>t.listPrompts(e.params),e))),r?.resources&&(n.setRequestHandler(fn,ra(`resources/list`,`list`,async e=>t.listResources(e.params),e)),n.setRequestHandler(mn,ra(`resources/templates/list`,`list`,async e=>t.listResourceTemplates(e.params),e)),n.setRequestHandler(gn,ra(`resources/read`,`read`,async e=>t.readResource(e.params),e)),r?.resources.subscribe&&(n.setNotificationHandler(xn,ra(`notifications/resources/updated`,`notify`,async e=>t.notification(e),e)),n.setRequestHandler(yn,ra(`resources/subscribe`,`subscribe`,async e=>t.subscribeResource(e.params),e)),n.setRequestHandler(bn,ra(`resources/unsubscribe`,`unsubscribe`,async e=>t.unsubscribeResource(e.params),e)))),r?.tools&&(n.setRequestHandler(Vn,ra(`tools/call`,`call`,async e=>t.callTool(e.params),e)),n.setRequestHandler(Rn,ra(`tools/list`,`list`,async e=>t.listTools(e.params),e))),n.setRequestHandler(or,ra(`completion/complete`,`complete`,async e=>t.complete(e.params),e))};var aa=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)}})),oa=e(((exports,n)=>{
@@ -29,4 +29,4 @@ return fn.apply(this, arguments)
29
29
  `&&r++}}return[t,n]}var Qo=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(ts(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(ts(this),t)}};function $o(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function es(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(es).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${es(e.cause)}`:e.message:`${e}`}function ts(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var ns=e=>{throw TypeError(e)},rs=(e,t,n)=>t.has(e)||ns(`Cannot `+n),$=(e,t,n)=>(rs(e,t,`read from private field`),n?n.call(e):t.get(e)),os=(e,t,n)=>t.has(e)?ns(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),ss=(e,t,n,r)=>(rs(e,t,`write to private field`),t.set(e,n),n),cs=(e,t,n)=>(rs(e,t,`access private method`),n),ls,us,ds,fs,ps,ms,hs,gs,_s,vs,ys,bs,xs,Ss,Cs,ws,Ts,Es,Ds,Os,ks,As,js,Ms=class extends EventTarget{constructor(e,t){super(),os(this,Ss),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,os(this,ls),os(this,us),os(this,ds),os(this,fs),os(this,ps),os(this,ms),os(this,hs),os(this,gs,null),os(this,_s),os(this,vs),os(this,ys,null),os(this,bs,null),os(this,xs,null),os(this,ws,async e=>{var t;$(this,vs).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){cs(this,Ss,ks).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?ss(this,ds,new URL(e.url)):ss(this,ds,void 0),i!==200){cs(this,Ss,ks).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){cs(this,Ss,ks).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if($(this,ls)===this.CLOSED)return;ss(this,ls,this.OPEN);let o=new Event(`open`);if((t=$(this,xs))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){cs(this,Ss,ks).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&$(this,vs).feed(s.decode(t,{stream:!e})),e&&(l=!1,$(this,vs).reset(),cs(this,Ss,As).call(this))}while(l)}),os(this,Ts,e=>{ss(this,_s,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&cs(this,Ss,As).call(this,es(e))}),os(this,Ds,e=>{typeof e.id==`string`&&ss(this,gs,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:$(this,ds)?$(this,ds).origin:$(this,us).origin,lastEventId:e.id||``});$(this,bs)&&(!e.event||e.event===`message`)&&$(this,bs).call(this,t),this.dispatchEvent(t)}),os(this,Os,e=>{ss(this,ms,e)}),os(this,js,()=>{ss(this,hs,void 0),$(this,ls)===this.CONNECTING&&cs(this,Ss,Cs).call(this)});try{if(e instanceof URL)ss(this,us,e);else if(typeof e==`string`)ss(this,us,new URL(e,Ns()));else throw Error(`Invalid URL`)}catch{throw $o(`An invalid or illegal string was specified`)}ss(this,vs,Xo({onEvent:$(this,Ds),onRetry:$(this,Os)})),ss(this,ls,this.CONNECTING),ss(this,ms,3e3),ss(this,ps,t?.fetch??globalThis.fetch),ss(this,fs,t?.withCredentials??!1),cs(this,Ss,Cs).call(this)}get readyState(){return $(this,ls)}get url(){return $(this,us).href}get withCredentials(){return $(this,fs)}get onerror(){return $(this,ys)}set onerror(e){ss(this,ys,e)}get onmessage(){return $(this,bs)}set onmessage(e){ss(this,bs,e)}get onopen(){return $(this,xs)}set onopen(e){ss(this,xs,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){$(this,hs)&&clearTimeout($(this,hs)),$(this,ls)!==this.CLOSED&&($(this,_s)&&$(this,_s).abort(),ss(this,ls,this.CLOSED),ss(this,_s,void 0))}};ls=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,ps=new WeakMap,ms=new WeakMap,hs=new WeakMap,gs=new WeakMap,_s=new WeakMap,vs=new WeakMap,ys=new WeakMap,bs=new WeakMap,xs=new WeakMap,Ss=new WeakSet,Cs=function(){ss(this,ls,this.CONNECTING),ss(this,_s,new AbortController),$(this,ps)($(this,us),cs(this,Ss,Es).call(this)).then($(this,ws)).catch($(this,Ts))},ws=new WeakMap,Ts=new WeakMap,Es=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...$(this,gs)?{"Last-Event-ID":$(this,gs)}:void 0},cache:`no-store`,signal:$(this,_s)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},Ds=new WeakMap,Os=new WeakMap,ks=function(e,t){var n;$(this,ls)!==this.CLOSED&&ss(this,ls,this.CLOSED);let r=new Qo(`error`,{code:t,message:e});(n=$(this,ys))==null||n.call(this,r),this.dispatchEvent(r)},As=function(e,t){var n;if($(this,ls)===this.CLOSED)return;ss(this,ls,this.CONNECTING);let r=new Qo(`error`,{code:t,message:e});(n=$(this,ys))==null||n.call(this,r),this.dispatchEvent(r),ss(this,hs,setTimeout($(this,js),$(this,ms)))},js=new WeakMap,Ms.CONNECTING=0,Ms.OPEN=1,Ms.CLOSED=2;function Ns(){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 Ps;Ps=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function Fs(e){return(await Ps).getRandomValues(new Uint8Array(e))}async function Is(e){let t=``,n=await Fs(e);for(let r=0;r<e;r++){let e=n[r]%66;t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e]}return t}async function Ls(e){return await Is(e)}async function Rs(e){let t=await(await Ps).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function zs(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Ls(e),n=await Rs(t);return{code_verifier:t,code_challenge:n}}const Bs=q().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:O.custom,message:`URL must be parseable`,fatal:!0}),bt}).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`}),Vs=Y({resource:q().url(),authorization_servers:J(Bs).optional(),jwks_uri:q().url().optional(),scopes_supported:J(q()).optional(),bearer_methods_supported:J(q()).optional(),resource_signing_alg_values_supported:J(q()).optional(),resource_name:q().optional(),resource_documentation:q().optional(),resource_policy_uri:q().url().optional(),resource_tos_uri:q().url().optional(),tls_client_certificate_bound_access_tokens:pt().optional(),authorization_details_types_supported:J(q()).optional(),dpop_signing_alg_values_supported:J(q()).optional(),dpop_bound_access_tokens_required:pt().optional()}).passthrough(),Hs=Y({issuer:q(),authorization_endpoint:Bs,token_endpoint:Bs,registration_endpoint:Bs.optional(),scopes_supported:J(q()).optional(),response_types_supported:J(q()),response_modes_supported:J(q()).optional(),grant_types_supported:J(q()).optional(),token_endpoint_auth_methods_supported:J(q()).optional(),token_endpoint_auth_signing_alg_values_supported:J(q()).optional(),service_documentation:Bs.optional(),revocation_endpoint:Bs.optional(),revocation_endpoint_auth_methods_supported:J(q()).optional(),revocation_endpoint_auth_signing_alg_values_supported:J(q()).optional(),introspection_endpoint:q().optional(),introspection_endpoint_auth_methods_supported:J(q()).optional(),introspection_endpoint_auth_signing_alg_values_supported:J(q()).optional(),code_challenge_methods_supported:J(q()).optional()}).passthrough(),Us=Y({issuer:q(),authorization_endpoint:Bs,token_endpoint:Bs,userinfo_endpoint:Bs.optional(),jwks_uri:Bs,registration_endpoint:Bs.optional(),scopes_supported:J(q()).optional(),response_types_supported:J(q()),response_modes_supported:J(q()).optional(),grant_types_supported:J(q()).optional(),acr_values_supported:J(q()).optional(),subject_types_supported:J(q()),id_token_signing_alg_values_supported:J(q()),id_token_encryption_alg_values_supported:J(q()).optional(),id_token_encryption_enc_values_supported:J(q()).optional(),userinfo_signing_alg_values_supported:J(q()).optional(),userinfo_encryption_alg_values_supported:J(q()).optional(),userinfo_encryption_enc_values_supported:J(q()).optional(),request_object_signing_alg_values_supported:J(q()).optional(),request_object_encryption_alg_values_supported:J(q()).optional(),request_object_encryption_enc_values_supported:J(q()).optional(),token_endpoint_auth_methods_supported:J(q()).optional(),token_endpoint_auth_signing_alg_values_supported:J(q()).optional(),display_values_supported:J(q()).optional(),claim_types_supported:J(q()).optional(),claims_supported:J(q()).optional(),service_documentation:q().optional(),claims_locales_supported:J(q()).optional(),ui_locales_supported:J(q()).optional(),claims_parameter_supported:pt().optional(),request_parameter_supported:pt().optional(),request_uri_parameter_supported:pt().optional(),require_request_uri_registration:pt().optional(),op_policy_uri:Bs.optional(),op_tos_uri:Bs.optional()}).passthrough().merge(Hs.pick({code_challenge_methods_supported:!0})),Ws=Y({access_token:q(),id_token:q().optional(),token_type:q(),expires_in:ft().optional(),scope:q().optional(),refresh_token:q().optional()}).strip(),Gs=Y({error:q(),error_description:q().optional(),error_uri:q().optional()}),Ks=Y({redirect_uris:J(Bs),token_endpoint_auth_method:q().optional(),grant_types:J(q()).optional(),response_types:J(q()).optional(),client_name:q().optional(),client_uri:Bs.optional(),logo_uri:Bs.optional(),scope:q().optional(),contacts:J(q()).optional(),tos_uri:Bs.optional(),policy_uri:q().optional(),jwks_uri:Bs.optional(),jwks:mt().optional(),software_id:q().optional(),software_version:q().optional(),software_statement:q().optional()}).strip(),qs=Y({client_id:q(),client_secret:q().optional(),client_id_issued_at:ft().optional(),client_secret_expires_at:ft().optional()}).strip(),Js=Ks.merge(qs);Y({error:q(),error_description:q().optional()}).strip(),Y({token:q(),token_type_hint:q().optional()}).strip();function Ys(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Xs({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 Zs=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}},Qs=class extends Zs{};Qs.errorCode=`invalid_request`;var $s=class extends Zs{};$s.errorCode=`invalid_client`;var ec=class extends Zs{};ec.errorCode=`invalid_grant`;var tc=class extends Zs{};tc.errorCode=`unauthorized_client`;var nc=class extends Zs{};nc.errorCode=`unsupported_grant_type`;var rc=class extends Zs{};rc.errorCode=`invalid_scope`;var ic=class extends Zs{};ic.errorCode=`access_denied`;var ac=class extends Zs{};ac.errorCode=`server_error`;var oc=class extends Zs{};oc.errorCode=`temporarily_unavailable`;var sc=class extends Zs{};sc.errorCode=`unsupported_response_type`;var cc=class extends Zs{};cc.errorCode=`unsupported_token_type`;var lc=class extends Zs{};lc.errorCode=`invalid_token`;var uc=class extends Zs{};uc.errorCode=`method_not_allowed`;var dc=class extends Zs{};dc.errorCode=`too_many_requests`;var fc=class extends Zs{};fc.errorCode=`invalid_client_metadata`;var pc=class extends Zs{};pc.errorCode=`insufficient_scope`;const mc={[Qs.errorCode]:Qs,[$s.errorCode]:$s,[ec.errorCode]:ec,[tc.errorCode]:tc,[nc.errorCode]:nc,[rc.errorCode]:rc,[ic.errorCode]:ic,[ac.errorCode]:ac,[oc.errorCode]:oc,[sc.errorCode]:sc,[cc.errorCode]:cc,[lc.errorCode]:lc,[uc.errorCode]:uc,[dc.errorCode]:dc,[fc.errorCode]:fc,[pc.errorCode]:pc};var hc=class extends Error{constructor(e){super(e??`Unauthorized`)}};function gc(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 _c(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:vc(i,a,n);return;case`client_secret_post`:yc(i,a,r);return;case`none`:bc(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function vc(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 yc(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function bc(e,t){t.set(`client_id`,e)}async function xc(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}=Gs.parse(JSON.parse(n));return new(mc[e]||ac)(t||``,r)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new ac(r)}}async function Sc(e,t){try{return await Cc(e,t)}catch(n){if(n instanceof $s||n instanceof tc)return await e.invalidateCredentials?.call(e,`all`),await Cc(e,t);if(n instanceof ec)return await e.invalidateCredentials?.call(e,`tokens`),await Cc(e,t);throw n}}async function Cc(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o,s;try{o=await Ec(t,{resourceMetadataUrl:i},a),o.authorization_servers&&o.authorization_servers.length>0&&(s=o.authorization_servers[0])}catch{}s||=t;let c=await wc(t,e,o),l=await Nc(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 Lc(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 Fc(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 Ic(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 Zs)||e instanceof ac))throw e}let f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:m}=await Pc(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 wc(e,t,n){let r=Ys(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Xs({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function Tc(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 Ec(e,t,n=fetch){let r=await jc(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 Vs.parse(await r.json())}async function Dc(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Dc(e,void 0,n):void 0;throw r}}function Oc(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function kc(e,t,n=fetch){return await Dc(e,{"MCP-Protocol-Version":t},n)}function Ac(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function jc(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??xt,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Oc(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await kc(o,a,n);if(!r?.metadataUrl&&Ac(s,i.pathname)){let e=new URL(`/.well-known/${t}`,i);s=await kc(e,a,n)}return s}function Mc(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 Nc(e,{fetchFn:t=fetch,protocolVersion:n=xt}={}){let r={"MCP-Protocol-Version":n},i=Mc(e);for(let{url:e,type:n}of i){let i=await Dc(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 Hs.parse(await i.json());{let t=Us.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 Pc(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 zs(),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 Fc(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=gc(n,e);_c(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 xc(p);return Ws.parse(await p.json())}async function Ic(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=gc(n,e);_c(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 xc(d);return Ws.parse({refresh_token:r,...await d.json()})}async function Lc(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 xc(a);return Js.parse(await a.json())}var Rc=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},zc=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 hc(`No auth provider`);let t;try{t=await Sc(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 hc;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 Ms(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=Tc(i)),i}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{var r;if(e.code===401&&this._authProvider){this._authThenStart().then(t,n);return}let i=new Rc(e.code,e.message,e);n(i),(r=this.onerror)==null||r.call(this,i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener(`endpoint`,e=>{var r;let i=e;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){n(e),(r=this.onerror)==null||r.call(this,e),this.close();return}t()}),this._eventSource.onmessage=e=>{var t,n;let r=e,i;try{i=Vt.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 hc(`No auth provider`);if(await Sc(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new hc(`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=Tc(r),await Sc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new hc;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}},Bc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Xo({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 Vc={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Hc=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Uc=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??Vc}async _authThenStart(){var e;if(!this._authProvider)throw new hc(`No auth provider`);let t;try{t=await Sc(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 hc;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 Hc(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 Bc).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=Vt.parse(JSON.parse(e.data));i!==void 0&&Lt(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 hc(`No auth provider`);if(await Sc(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new hc(`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:Nt(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=Tc(s),await Sc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new hc;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){$t(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=>Vt.parse(e)):[Vt.parse(e)];for(let e of t)(n=this.onmessage)==null||n.call(this,e)}else throw new Hc(-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 Hc(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}},Wc=n(Go(),1),Gc=class extends Za{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Un.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(Jt,e=>this._oninitialize(e)),this.setNotificationHandler(Qt,()=>this.oninitialized?.call(this)),this._capabilities.logging&&this.setRequestHandler(Wn,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Un.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=Qa(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:St.includes(t)?t:xt,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`},Ht)}async createMessage(e,t){return this.request({method:`sampling/createMessage`,params:e},Xn,t)}async elicitInput(e,t){let n=await this.request({method:`elicitation/create`,params:e},rr,t);if(n.action===`accept`&&n.content)try{let t=new Wc.default,r=t.compile(e.requestedSchema);if(!r(n.content))throw new fr(Rt.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(r.errors)}`)}catch(e){throw e instanceof fr?e:new fr(Rt.InternalError,`Error validating elicitation response: ${e}`)}return n}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ur,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`})}},Kc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
30
30
  `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),qc(t)}clear(){this._buffer=void 0}};function qc(e){return Vt.parse(JSON.parse(e))}function Jc(e){return JSON.stringify(e)+`
31
31
  `}var Yc=class{constructor(e=S.stdin,t=S.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Kc,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=Jc(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function Xc(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{mr as AccessControlBlockError,_r as BUILD_TIME_CONFIG,qo as Client,hr as ConfigurationError,C as InMemoryEventStore,gr as ProxyConnectionError,Kc as ReadBuffer,zc as SSEClientTransport,Gc as Server,Yc as StdioServerTransport,Uc as StreamableHTTPClientTransport,hc as UnauthorizedError,Yi as compressClientInfo,Hr as config,Xo as createParser,Nc as discoverAuthorizationServerMetadata,Ec as discoverOAuthProtectedResourceMetadata,Fc as exchangeAuthorization,xi as extractTraceIdFromHeaders,Fi as flushLogs,Ji as getSessionData,Qi as initializeTrafficMirror,ta as logRequestCounts,Q as logger,Xc as normalizeUrl,ia as proxyServer,Ic as refreshAuthorization,Lc as registerClient,Jc as serializeMessage,Pc as startAuthorization,Xa as startHTTPServer};
32
- //# sourceMappingURL=normalizeUrl-F8UPDdZN.js.map
32
+ //# sourceMappingURL=normalizeUrl-BUnsFC9r.js.map