browser-console-mcp 1.0.9 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.d.ts +0 -9
- package/dist/browser/index.js +1 -1
- package/dist/client/browser-console-mcp.js +1 -1
- package/dist/client/index.d.ts +0 -2
- package/dist/client/index.js +0 -4
- package/package.json +69 -68
- package/readme.md +189 -75
- package/dist/server/index.d.ts +0 -48
- package/dist/server/index.js +0 -154
- package/dist/server/static-server.d.ts +0 -44
- package/dist/server/static-server.js +0 -205
package/dist/browser/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as e,mkdirSync as t,writeFileSync as r}from"node:fs";import{createServer as s}from"node:http";import{homedir as n}from"node:os";import{dirname as i,join as a}from"node:path";import{fileURLToPath as o}from"node:url";import c from"node:process";import d from"events";import l from"https";import u from"http";import h from"net";import p from"tls";import f from"crypto";import m from"stream";import g from"url";import _ from"zlib";import y from"buffer";var v,b;!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),s={};for(const e of r)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(v||(v={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(b||(b={}));const w=v.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),x=e=>{switch(typeof e){case"undefined":return w.undefined;case"string":return w.string;case"number":return isNaN(e)?w.nan:w.number;case"boolean":return w.boolean;case"function":return w.function;case"bigint":return w.bigint;case"symbol":return w.symbol;case"object":return Array.isArray(e)?w.array:null===e?w.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?w.promise:"undefined"!=typeof Map&&e instanceof Map?w.map:"undefined"!=typeof Set&&e instanceof Set?w.set:"undefined"!=typeof Date&&e instanceof Date?w.date:w.object;default:return w.unknown}},k=v.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class S 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]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,s=0;for(;s<n.path.length;){const r=n.path[s];s===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof S))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}S.create=e=>new S(e);const E=(e,t)=>{let r;switch(e.code){case k.invalid_type:r=e.received===w.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,v.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${v.joinValues(e.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${v.joinValues(e.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${v.joinValues(e.options)}, received '${e.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:v.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case k.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`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 k.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=t.defaultError,v.assertNever(e)}return{message:r}};let C=E;function T(){return C}const O=e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,i=[...r,...n.path||[]],a={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const c=s.filter((e=>!!e)).slice().reverse();for(const e of c)o=e(a,{data:t,defaultError:o}).message;return{...n,path:i,message:o}};function P(e,t){const r=T(),s=O({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===E?void 0:E].filter((e=>!!e))});e.common.issues.push(s)}class N{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return j;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,s=await e.value;r.push({key:t,value:s})}return N.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return j;if("aborted"===n.status)return j;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const j=Object.freeze({status:"aborted"}),I=e=>({status:"dirty",value:e}),R=e=>({status:"valid",value:e}),M=e=>"aborted"===e.status,A=e=>"dirty"===e.status,Z=e=>"valid"===e.status,L=e=>"undefined"!=typeof Promise&&e instanceof Promise;function $(e,t,r,s){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function B(e,t,r,s,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var q,F,U;"function"==typeof SuppressedError&&SuppressedError,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(q||(q={}));class D{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const z=(e,t)=>{if(Z(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new S(e.common.issues);return this._error=t,this._error}}};function H(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{var i,a;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:n.defaultError}:void 0===n.data?{message:null!==(i=null!=o?o:s)&&void 0!==i?i:n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:null!==(a=null!=o?o:r)&&void 0!==a?a:n.defaultError}},description:n}}class W{get description(){return this._def.description}_getType(e){return x(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:x(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new N,ctx:{common:e.parent.common,data:e.data,parsedType:x(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(L(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const s={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)},n=this._parseSync({data:e,path:s.path,parent:s});return z(s,n)}"~validate"(e){var t,r;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:s});return Z(t)?{value:t.value}:{issues:s.common.issues}}catch(e){(null===(r=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then((e=>Z(e)?{value:e.value}:{issues:s.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(L(s)?s:Promise.resolve(s));return z(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,s)=>{const n=e(t),i=()=>s.addIssue({code:k.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(i(),!1))):!!n||(i(),!1)}))}refinement(e,t){return this._refinement(((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1)))}_refinement(e){return new We({schema:this,typeName:it.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 Ve.create(this,this._def)}nullable(){return Ge.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Te.create(this)}promise(){return He.create(this,this._def)}or(e){return Ne.create([this,e],this._def)}and(e){return Me.create(this,e,this._def)}transform(e){return new We({...H(this._def),schema:this,typeName:it.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Je({...H(this._def),innerType:this,defaultValue:t,typeName:it.ZodDefault})}brand(){return new Qe({typeName:it.ZodBranded,type:this,...H(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ke({...H(this._def),innerType:this,catchValue:t,typeName:it.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return et.create(this,e)}readonly(){return tt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const V=/^c[^\s-]{8,}$/i,G=/^[0-9a-z]+$/,J=/^[0-9A-HJKMNP-TV-Z]{26}$/i,K=/^[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,Y=/^[a-z0-9_-]{21}$/i,X=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Q=/^[-+]?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)?)??$/,ee=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let te;const re=/^(?:(?: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])$/,se=/^(?:(?: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])$/,ne=/^(([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]))$/,ie=/^(([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])$/,ae=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,oe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ce="((\\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])))",de=new RegExp(`^${ce}$`);function le(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function ue(e){let t=`${ce}T${le(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function he(e,t){if(!X.test(e))return!1;try{const[r]=e.split("."),s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return"object"==typeof n&&null!==n&&(!(!n.typ||!n.alg)&&(!t||n.alg===t))}catch(e){return!1}}function pe(e,t){return!("v4"!==t&&t||!se.test(e))||!("v6"!==t&&t||!ie.test(e))}class fe extends W{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==w.string){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.string,received:t.parsedType}),j}const t=new N;let r;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:k.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:k.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const s=e.data.length>i.value,n=e.data.length<i.value;(s||n)&&(r=this._getOrReturnCtx(e,r),s?P(r,{code:k.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&P(r,{code:k.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)ee.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"email",code:k.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)te||(te=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),te.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"emoji",code:k.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)K.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"uuid",code:k.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)Y.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"nanoid",code:k.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)V.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid",code:k.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)G.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid2",code:k.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)J.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"ulid",code:k.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch(s){r=this._getOrReturnCtx(e,r),P(r,{validation:"url",code:k.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"regex",code:k.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),P(r,{code:k.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),P(r,{code:k.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),P(r,{code:k.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){ue(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:k.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){de.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:k.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${le(i)}$`).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:k.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?Q.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"duration",code:k.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(s=e.data,("v4"!==(n=i.version)&&n||!re.test(s))&&("v6"!==n&&n||!ne.test(s))&&(r=this._getOrReturnCtx(e,r),P(r,{validation:"ip",code:k.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?he(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"jwt",code:k.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?pe(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cidr",code:k.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?ae.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64",code:k.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?oe.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64url",code:k.invalid_string,message:i.message}),t.dirty()):v.assertNever(i);var s,n;return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:k.invalid_string,...q.errToObj(r)})}_addCheck(e){return new fe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...q.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...q.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...q.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...q.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...q.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...q.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...q.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...q.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...q.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...q.errToObj(t)})}nonempty(e){return this.min(1,q.errToObj(e))}trim(){return new fe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new fe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new fe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function me(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=r>s?r:s;return parseInt(e.toFixed(n).replace(".",""))%parseInt(t.toFixed(n).replace(".",""))/Math.pow(10,n)}fe.create=e=>{var t;return new fe({checks:[],typeName:it.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...H(e)})};class ge extends W{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==w.number){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.number,received:t.parsedType}),j}let t;const r=new N;for(const s of this._def.checks)if("int"===s.kind)v.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==me(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:k.not_finite,message:s.message}),r.dirty()):v.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,q.toString(t))}gt(e,t){return this.setLimit("min",e,!1,q.toString(t))}lte(e,t){return this.setLimit("max",e,!0,q.toString(t))}lt(e,t){return this.setLimit("max",e,!1,q.toString(t))}setLimit(e,t,r,s){return new ge({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:q.toString(s)}]})}_addCheck(e){return new ge({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:q.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:q.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&v.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ge.create=e=>new ge({checks:[],typeName:it.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...H(e)});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(t){return this._getInvalidInput(e)}if(this._getType(e)!==w.bigint)return this._getInvalidInput(e);let t;const r=new N;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),P(t,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):v.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.bigint,received:t.parsedType}),j}gte(e,t){return this.setLimit("min",e,!0,q.toString(t))}gt(e,t){return this.setLimit("min",e,!1,q.toString(t))}lte(e,t){return this.setLimit("max",e,!0,q.toString(t))}lt(e,t){return this.setLimit("max",e,!1,q.toString(t))}setLimit(e,t,r,s){return new _e({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:q.toString(s)}]})}_addCheck(e){return new _e({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:q.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}_e.create=e=>{var t;return new _e({checks:[],typeName:it.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...H(e)})};class ye extends W{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==w.boolean){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.boolean,received:t.parsedType}),j}return R(e.data)}}ye.create=e=>new ye({typeName:it.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...H(e)});class ve extends W{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==w.date){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.date,received:t.parsedType}),j}if(isNaN(e.data.getTime())){return P(this._getOrReturnCtx(e),{code:k.invalid_date}),j}const t=new N;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):v.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ve({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:q.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:q.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ve.create=e=>new ve({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:it.ZodDate,...H(e)});class be extends W{_parse(e){if(this._getType(e)!==w.symbol){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.symbol,received:t.parsedType}),j}return R(e.data)}}be.create=e=>new be({typeName:it.ZodSymbol,...H(e)});class we extends W{_parse(e){if(this._getType(e)!==w.undefined){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.undefined,received:t.parsedType}),j}return R(e.data)}}we.create=e=>new we({typeName:it.ZodUndefined,...H(e)});class xe extends W{_parse(e){if(this._getType(e)!==w.null){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.null,received:t.parsedType}),j}return R(e.data)}}xe.create=e=>new xe({typeName:it.ZodNull,...H(e)});class ke extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return R(e.data)}}ke.create=e=>new ke({typeName:it.ZodAny,...H(e)});class Se extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return R(e.data)}}Se.create=e=>new Se({typeName:it.ZodUnknown,...H(e)});class Ee extends W{_parse(e){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.never,received:t.parsedType}),j}}Ee.create=e=>new Ee({typeName:it.ZodNever,...H(e)});class Ce extends W{_parse(e){if(this._getType(e)!==w.undefined){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.void,received:t.parsedType}),j}return R(e.data)}}Ce.create=e=>new Ce({typeName:it.ZodVoid,...H(e)});class Te extends W{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==w.array)return P(t,{code:k.invalid_type,expected:w.array,received:t.parsedType}),j;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(P(t,{code:e?k.too_big:k.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(P(t,{code:k.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(P(t,{code:k.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>s.type._parseAsync(new D(t,e,t.path,r))))).then((e=>N.mergeArray(r,e)));const n=[...t.data].map(((e,r)=>s.type._parseSync(new D(t,e,t.path,r))));return N.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Te({...this._def,minLength:{value:e,message:q.toString(t)}})}max(e,t){return new Te({...this._def,maxLength:{value:e,message:q.toString(t)}})}length(e,t){return new Te({...this._def,exactLength:{value:e,message:q.toString(t)}})}nonempty(e){return this.min(1,e)}}function Oe(e){if(e instanceof Pe){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Ve.create(Oe(s))}return new Pe({...e._def,shape:()=>t})}return e instanceof Te?new Te({...e._def,type:Oe(e.element)}):e instanceof Ve?Ve.create(Oe(e.unwrap())):e instanceof Ge?Ge.create(Oe(e.unwrap())):e instanceof Ae?Ae.create(e.items.map((e=>Oe(e)))):e}Te.create=(e,t)=>new Te({type:e,minLength:null,maxLength:null,exactLength:null,typeName:it.ZodArray,...H(t)});class Pe extends W{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=v.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==w.object){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.object,received:t.parsedType}),j}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Ee&&"strip"===this._def.unknownKeys))for(const e in r.data)n.includes(e)||i.push(e);const a=[];for(const e of n){const t=s[e],n=r.data[e];a.push({key:{status:"valid",value:e},value:t._parse(new D(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof Ee){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)a.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(P(r,{code:k.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=r.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new D(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of a){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e})).then((e=>N.mergeObjectSync(t,e))):N.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return q.errToObj,new Pe({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var s,n,i,a;const o=null!==(i=null===(n=(s=this._def).errorMap)||void 0===n?void 0:n.call(s,t,r).message)&&void 0!==i?i:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(a=q.errToObj(e).message)&&void 0!==a?a:o}:{message:o}}}:{}})}strip(){return new Pe({...this._def,unknownKeys:"strip"})}passthrough(){return new Pe({...this._def,unknownKeys:"passthrough"})}extend(e){return new Pe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Pe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:it.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Pe({...this._def,catchall:e})}pick(e){const t={};return v.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new Pe({...this._def,shape:()=>t})}omit(e){const t={};return v.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new Pe({...this._def,shape:()=>t})}deepPartial(){return Oe(this)}partial(e){const t={};return v.objectKeys(this.shape).forEach((r=>{const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()})),new Pe({...this._def,shape:()=>t})}required(e){const t={};return v.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Ve;)e=e._def.innerType;t[r]=e}})),new Pe({...this._def,shape:()=>t})}keyof(){return Ue(v.objectKeys(this.shape))}}Pe.create=(e,t)=>new Pe({shape:()=>e,unknownKeys:"strip",catchall:Ee.create(),typeName:it.ZodObject,...H(t)}),Pe.strictCreate=(e,t)=>new Pe({shape:()=>e,unknownKeys:"strict",catchall:Ee.create(),typeName:it.ZodObject,...H(t)}),Pe.lazycreate=(e,t)=>new Pe({shape:e,unknownKeys:"strip",catchall:Ee.create(),typeName:it.ZodObject,...H(t)});class Ne extends W{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map((e=>new S(e.ctx.common.issues)));return P(t,{code:k.invalid_union,unionErrors:r}),j}));{let e;const s=[];for(const n of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map((e=>new S(e)));return P(t,{code:k.invalid_union,unionErrors:n}),j}}get options(){return this._def.options}}Ne.create=(e,t)=>new Ne({options:e,typeName:it.ZodUnion,...H(t)});const je=e=>e instanceof qe?je(e.schema):e instanceof We?je(e.innerType()):e instanceof Fe?[e.value]:e instanceof De?e.options:e instanceof ze?v.objectValues(e.enum):e instanceof Je?je(e._def.innerType):e instanceof we?[void 0]:e instanceof xe?[null]:e instanceof Ve?[void 0,...je(e.unwrap())]:e instanceof Ge?[null,...je(e.unwrap())]:e instanceof Qe||e instanceof tt?je(e.unwrap()):e instanceof Ke?je(e._def.innerType):[];class Ie extends W{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.object)return P(t,{code:k.invalid_type,expected:w.object,received:t.parsedType}),j;const r=this.discriminator,s=t.data[r],n=this.optionsMap.get(s);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(P(t,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),j)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const s=new Map;for(const r of t){const t=je(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const n of t){if(s.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);s.set(n,r)}}return new Ie({typeName:it.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...H(r)})}}function Re(e,t){const r=x(e),s=x(t);if(e===t)return{valid:!0,data:e};if(r===w.object&&s===w.object){const r=v.objectKeys(t),s=v.objectKeys(e).filter((e=>-1!==r.indexOf(e))),n={...e,...t};for(const r of s){const s=Re(e[r],t[r]);if(!s.valid)return{valid:!1};n[r]=s.data}return{valid:!0,data:n}}if(r===w.array&&s===w.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=Re(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===w.date&&s===w.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Me extends W{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(M(e)||M(s))return j;const n=Re(e.value,s.value);return n.valid?((A(e)||A(s))&&t.dirty(),{status:t.value,value:n.data}):(P(r,{code:k.invalid_intersection_types}),j)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>s(e,t))):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Me.create=(e,t,r)=>new Me({left:e,right:t,typeName:it.ZodIntersection,...H(r)});class Ae extends W{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==w.array)return P(r,{code:k.invalid_type,expected:w.array,received:r.parsedType}),j;if(r.data.length<this._def.items.length)return P(r,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),j;!this._def.rest&&r.data.length>this._def.items.length&&(P(r,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map(((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new D(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(s).then((e=>N.mergeArray(t,e))):N.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Ae({...this._def,rest:e})}}Ae.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ae({items:e,typeName:it.ZodTuple,rest:null,...H(t)})};class Ze extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==w.object)return P(r,{code:k.invalid_type,expected:w.object,received:r.parsedType}),j;const s=[],n=this._def.keyType,i=this._def.valueType;for(const e in r.data)s.push({key:n._parse(new D(r,e,r.path,e)),value:i._parse(new D(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?N.mergeObjectAsync(t,s):N.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new Ze(t instanceof W?{keyType:e,valueType:t,typeName:it.ZodRecord,...H(r)}:{keyType:fe.create(),valueType:e,typeName:it.ZodRecord,...H(t)})}}class Le extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==w.map)return P(r,{code:k.invalid_type,expected:w.map,received:r.parsedType}),j;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map((([e,t],i)=>({key:s._parse(new D(r,e,r.path,[i,"key"])),value:n._parse(new D(r,t,r.path,[i,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of i){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return j;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of i){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return j;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}Le.create=(e,t,r)=>new Le({valueType:t,keyType:e,typeName:it.ZodMap,...H(r)});class $e extends W{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==w.set)return P(r,{code:k.invalid_type,expected:w.set,received:r.parsedType}),j;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(P(r,{code:k.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(P(r,{code:k.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const r=new Set;for(const s of e){if("aborted"===s.status)return j;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const a=[...r.data.values()].map(((e,t)=>n._parse(new D(r,e,r.path,t))));return r.common.async?Promise.all(a).then((e=>i(e))):i(a)}min(e,t){return new $e({...this._def,minSize:{value:e,message:q.toString(t)}})}max(e,t){return new $e({...this._def,maxSize:{value:e,message:q.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}$e.create=(e,t)=>new $e({valueType:e,minSize:null,maxSize:null,typeName:it.ZodSet,...H(t)});class Be extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.function)return P(t,{code:k.invalid_type,expected:w.function,received:t.parsedType}),j;function r(e,r){return O({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,T(),E].filter((e=>!!e)),issueData:{code:k.invalid_arguments,argumentsError:r}})}function s(e,r){return O({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,T(),E].filter((e=>!!e)),issueData:{code:k.invalid_return_type,returnTypeError:r}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof He){const e=this;return R((async function(...t){const a=new S([]),o=await e._def.args.parseAsync(t,n).catch((e=>{throw a.addIssue(r(t,e)),a})),c=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(c,n).catch((e=>{throw a.addIssue(s(c,e)),a}))}))}{const e=this;return R((function(...t){const a=e._def.args.safeParse(t,n);if(!a.success)throw new S([r(t,a.error)]);const o=Reflect.apply(i,this,a.data),c=e._def.returns.safeParse(o,n);if(!c.success)throw new S([s(o,c.error)]);return c.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Be({...this._def,args:Ae.create(e).rest(Se.create())})}returns(e){return new Be({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new Be({args:e||Ae.create([]).rest(Se.create()),returns:t||Se.create(),typeName:it.ZodFunction,...H(r)})}}class qe extends W{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}qe.create=(e,t)=>new qe({getter:e,typeName:it.ZodLazy,...H(t)});class Fe extends W{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:k.invalid_literal,expected:this._def.value}),j}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Ue(e,t){return new De({values:e,typeName:it.ZodEnum,...H(t)})}Fe.create=(e,t)=>new Fe({value:e,typeName:it.ZodLiteral,...H(t)});class De extends W{constructor(){super(...arguments),F.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return P(t,{expected:v.joinValues(r),received:t.parsedType,code:k.invalid_type}),j}if($(this,F)||B(this,F,new Set(this._def.values)),!$(this,F).has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return P(t,{received:t.data,code:k.invalid_enum_value,options:r}),j}return R(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return De.create(e,{...this._def,...t})}exclude(e,t=this._def){return De.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}F=new WeakMap,De.create=Ue;class ze extends W{constructor(){super(...arguments),U.set(this,void 0)}_parse(e){const t=v.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==w.string&&r.parsedType!==w.number){const e=v.objectValues(t);return P(r,{expected:v.joinValues(e),received:r.parsedType,code:k.invalid_type}),j}if($(this,U)||B(this,U,new Set(v.getValidEnumValues(this._def.values))),!$(this,U).has(e.data)){const e=v.objectValues(t);return P(r,{received:r.data,code:k.invalid_enum_value,options:e}),j}return R(e.data)}get enum(){return this._def.values}}U=new WeakMap,ze.create=(e,t)=>new ze({values:e,typeName:it.ZodNativeEnum,...H(t)});class He extends W{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.promise&&!1===t.common.async)return P(t,{code:k.invalid_type,expected:w.promise,received:t.parsedType}),j;const r=t.parsedType===w.promise?t.data:Promise.resolve(t.data);return R(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}He.create=(e,t)=>new He({type:e,typeName:it.ZodPromise,...H(t)});class We extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===it.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:e=>{P(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){const e=s.transform(r.data,n);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return j;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?j:"dirty"===s.status||"dirty"===t.value?I(s.value):s}));{if("aborted"===t.value)return j;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?j:"dirty"===s.status||"dirty"===t.value?I(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,n);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===s.status?j:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?j:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Z(e))return e;const i=s.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>Z(e)?Promise.resolve(s.transform(e.value,n)).then((e=>({status:t.value,value:e}))):e))}v.assertNever(s)}}We.create=(e,t,r)=>new We({schema:e,typeName:it.ZodEffects,effect:t,...H(r)}),We.createWithPreprocess=(e,t,r)=>new We({schema:t,effect:{type:"preprocess",transform:e},typeName:it.ZodEffects,...H(r)});class Ve extends W{_parse(e){return this._getType(e)===w.undefined?R(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ve.create=(e,t)=>new Ve({innerType:e,typeName:it.ZodOptional,...H(t)});class Ge extends W{_parse(e){return this._getType(e)===w.null?R(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ge.create=(e,t)=>new Ge({innerType:e,typeName:it.ZodNullable,...H(t)});class Je extends W{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===w.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Je.create=(e,t)=>new Je({innerType:e,typeName:it.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...H(t)});class Ke extends W{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return L(s)?s.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new S(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new S(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ke.create=(e,t)=>new Ke({innerType:e,typeName:it.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...H(t)});class Ye extends W{_parse(e){if(this._getType(e)!==w.nan){const t=this._getOrReturnCtx(e);return P(t,{code:k.invalid_type,expected:w.nan,received:t.parsedType}),j}return{status:"valid",value:e.data}}}Ye.create=e=>new Ye({typeName:it.ZodNaN,...H(e)});const Xe=Symbol("zod_brand");class Qe extends W{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class et extends W{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?j:"dirty"===e.status?(t.dirty(),I(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?j:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new et({in:e,out:t,typeName:it.ZodPipeline})}}class tt extends W{_parse(e){const t=this._def.innerType._parse(e),r=e=>(Z(e)&&(e.value=Object.freeze(e.value)),e);return L(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function rt(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function st(e,t={},r){return e?ke.create().superRefine(((s,n)=>{var i,a;const o=e(s);if(o instanceof Promise)return o.then((e=>{var i,a;if(!e){const e=rt(t,s),o=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;n.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=rt(t,s),o=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;n.addIssue({code:"custom",...e,fatal:o})}})):ke.create()}tt.create=(e,t)=>new tt({innerType:e,typeName:it.ZodReadonly,...H(t)});const nt={object:Pe.lazycreate};var it;!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"}(it||(it={}));const at=fe.create,ot=ge.create,ct=Ye.create,dt=_e.create,lt=ye.create,ut=ve.create,ht=be.create,pt=we.create,ft=xe.create,mt=ke.create,gt=Se.create,_t=Ee.create,yt=Ce.create,vt=Te.create,bt=Pe.create,wt=Pe.strictCreate,xt=Ne.create,kt=Ie.create,St=Me.create,Et=Ae.create,Ct=Ze.create,Tt=Le.create,Ot=$e.create,Pt=Be.create,Nt=qe.create,jt=Fe.create,It=De.create,Rt=ze.create,Mt=He.create,At=We.create,Zt=Ve.create,Lt=Ge.create,$t=We.createWithPreprocess,Bt=et.create,qt={string:e=>fe.create({...e,coerce:!0}),number:e=>ge.create({...e,coerce:!0}),boolean:e=>ye.create({...e,coerce:!0}),bigint:e=>_e.create({...e,coerce:!0}),date:e=>ve.create({...e,coerce:!0})},Ft=j;var Ut=Object.freeze({__proto__:null,defaultErrorMap:E,setErrorMap:function(e){C=e},getErrorMap:T,makeIssue:O,EMPTY_PATH:[],addIssueToContext:P,ParseStatus:N,INVALID:j,DIRTY:I,OK:R,isAborted:M,isDirty:A,isValid:Z,isAsync:L,get util(){return v},get objectUtil(){return b},ZodParsedType:w,getParsedType:x,ZodType:W,datetimeRegex:ue,ZodString:fe,ZodNumber:ge,ZodBigInt:_e,ZodBoolean:ye,ZodDate:ve,ZodSymbol:be,ZodUndefined:we,ZodNull:xe,ZodAny:ke,ZodUnknown:Se,ZodNever:Ee,ZodVoid:Ce,ZodArray:Te,ZodObject:Pe,ZodUnion:Ne,ZodDiscriminatedUnion:Ie,ZodIntersection:Me,ZodTuple:Ae,ZodRecord:Ze,ZodMap:Le,ZodSet:$e,ZodFunction:Be,ZodLazy:qe,ZodLiteral:Fe,ZodEnum:De,ZodNativeEnum:ze,ZodPromise:He,ZodEffects:We,ZodTransformer:We,ZodOptional:Ve,ZodNullable:Ge,ZodDefault:Je,ZodCatch:Ke,ZodNaN:Ye,BRAND:Xe,ZodBranded:Qe,ZodPipeline:et,ZodReadonly:tt,custom:st,Schema:W,ZodSchema:W,late:nt,get ZodFirstPartyTypeKind(){return it},coerce:qt,any:mt,array:vt,bigint:dt,boolean:lt,date:ut,discriminatedUnion:kt,effect:At,enum:It,function:Pt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>st((t=>t instanceof e),t),intersection:St,lazy:Nt,literal:jt,map:Tt,nan:ct,nativeEnum:Rt,never:_t,null:ft,nullable:Lt,number:ot,object:bt,oboolean:()=>lt().optional(),onumber:()=>ot().optional(),optional:Zt,ostring:()=>at().optional(),pipeline:Bt,preprocess:$t,promise:Mt,record:Ct,set:Ot,strictObject:wt,string:at,symbol:ht,transformer:At,tuple:Et,undefined:pt,union:xt,unknown:gt,void:yt,NEVER:Ft,ZodIssueCode:k,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:S});const Dt="2024-11-05",zt=[Dt,"2024-10-07"],Ht="2.0",Wt=Ut.union([Ut.string(),Ut.number().int()]),Vt=Ut.string(),Gt=Ut.object({_meta:Ut.optional(Ut.object({progressToken:Ut.optional(Wt)}).passthrough())}).passthrough(),Jt=Ut.object({method:Ut.string(),params:Ut.optional(Gt)}),Kt=Ut.object({_meta:Ut.optional(Ut.object({}).passthrough())}).passthrough(),Yt=Ut.object({method:Ut.string(),params:Ut.optional(Kt)}),Xt=Ut.object({_meta:Ut.optional(Ut.object({}).passthrough())}).passthrough(),Qt=Ut.union([Ut.string(),Ut.number().int()]),er=Ut.object({jsonrpc:Ut.literal(Ht),id:Qt}).merge(Jt).strict(),tr=Ut.object({jsonrpc:Ut.literal(Ht)}).merge(Yt).strict(),rr=Ut.object({jsonrpc:Ut.literal(Ht),id:Qt,result:Xt}).strict();var sr;!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"}(sr||(sr={}));const nr=Ut.object({jsonrpc:Ut.literal(Ht),id:Qt,error:Ut.object({code:Ut.number().int(),message:Ut.string(),data:Ut.optional(Ut.unknown())})}).strict(),ir=Ut.union([er,tr,rr,nr]),ar=Xt.strict(),or=Yt.extend({method:Ut.literal("notifications/cancelled"),params:Kt.extend({requestId:Qt,reason:Ut.string().optional()})}),cr=Ut.object({name:Ut.string(),version:Ut.string()}).passthrough(),dr=Ut.object({experimental:Ut.optional(Ut.object({}).passthrough()),sampling:Ut.optional(Ut.object({}).passthrough()),roots:Ut.optional(Ut.object({listChanged:Ut.optional(Ut.boolean())}).passthrough())}).passthrough(),lr=Jt.extend({method:Ut.literal("initialize"),params:Gt.extend({protocolVersion:Ut.string(),capabilities:dr,clientInfo:cr})}),ur=Ut.object({experimental:Ut.optional(Ut.object({}).passthrough()),logging:Ut.optional(Ut.object({}).passthrough()),prompts:Ut.optional(Ut.object({listChanged:Ut.optional(Ut.boolean())}).passthrough()),resources:Ut.optional(Ut.object({subscribe:Ut.optional(Ut.boolean()),listChanged:Ut.optional(Ut.boolean())}).passthrough()),tools:Ut.optional(Ut.object({listChanged:Ut.optional(Ut.boolean())}).passthrough())}).passthrough(),hr=Xt.extend({protocolVersion:Ut.string(),capabilities:ur,serverInfo:cr,instructions:Ut.optional(Ut.string())}),pr=Yt.extend({method:Ut.literal("notifications/initialized")}),fr=Jt.extend({method:Ut.literal("ping")}),mr=Ut.object({progress:Ut.number(),total:Ut.optional(Ut.number())}).passthrough(),gr=Yt.extend({method:Ut.literal("notifications/progress"),params:Kt.merge(mr).extend({progressToken:Wt})}),_r=Jt.extend({params:Gt.extend({cursor:Ut.optional(Vt)}).optional()}),yr=Xt.extend({nextCursor:Ut.optional(Vt)}),vr=Ut.object({uri:Ut.string(),mimeType:Ut.optional(Ut.string())}).passthrough(),br=vr.extend({text:Ut.string()}),wr=vr.extend({blob:Ut.string().base64()}),xr=Ut.object({uri:Ut.string(),name:Ut.string(),description:Ut.optional(Ut.string()),mimeType:Ut.optional(Ut.string())}).passthrough(),kr=Ut.object({uriTemplate:Ut.string(),name:Ut.string(),description:Ut.optional(Ut.string()),mimeType:Ut.optional(Ut.string())}).passthrough(),Sr=_r.extend({method:Ut.literal("resources/list")}),Er=yr.extend({resources:Ut.array(xr)}),Cr=_r.extend({method:Ut.literal("resources/templates/list")}),Tr=yr.extend({resourceTemplates:Ut.array(kr)}),Or=Jt.extend({method:Ut.literal("resources/read"),params:Gt.extend({uri:Ut.string()})}),Pr=Xt.extend({contents:Ut.array(Ut.union([br,wr]))}),Nr=Yt.extend({method:Ut.literal("notifications/resources/list_changed")}),jr=Jt.extend({method:Ut.literal("resources/subscribe"),params:Gt.extend({uri:Ut.string()})}),Ir=Jt.extend({method:Ut.literal("resources/unsubscribe"),params:Gt.extend({uri:Ut.string()})}),Rr=Yt.extend({method:Ut.literal("notifications/resources/updated"),params:Kt.extend({uri:Ut.string()})}),Mr=Ut.object({name:Ut.string(),description:Ut.optional(Ut.string()),required:Ut.optional(Ut.boolean())}).passthrough(),Ar=Ut.object({name:Ut.string(),description:Ut.optional(Ut.string()),arguments:Ut.optional(Ut.array(Mr))}).passthrough(),Zr=_r.extend({method:Ut.literal("prompts/list")}),Lr=yr.extend({prompts:Ut.array(Ar)}),$r=Jt.extend({method:Ut.literal("prompts/get"),params:Gt.extend({name:Ut.string(),arguments:Ut.optional(Ut.record(Ut.string()))})}),Br=Ut.object({type:Ut.literal("text"),text:Ut.string()}).passthrough(),qr=Ut.object({type:Ut.literal("image"),data:Ut.string().base64(),mimeType:Ut.string()}).passthrough(),Fr=Ut.object({type:Ut.literal("resource"),resource:Ut.union([br,wr])}).passthrough(),Ur=Ut.object({role:Ut.enum(["user","assistant"]),content:Ut.union([Br,qr,Fr])}).passthrough(),Dr=Xt.extend({description:Ut.optional(Ut.string()),messages:Ut.array(Ur)}),zr=Yt.extend({method:Ut.literal("notifications/prompts/list_changed")}),Hr=Ut.object({name:Ut.string(),description:Ut.optional(Ut.string()),inputSchema:Ut.object({type:Ut.literal("object"),properties:Ut.optional(Ut.object({}).passthrough())}).passthrough()}).passthrough(),Wr=_r.extend({method:Ut.literal("tools/list")}),Vr=yr.extend({tools:Ut.array(Hr)}),Gr=Xt.extend({content:Ut.array(Ut.union([Br,qr,Fr])),isError:Ut.boolean().default(!1).optional()});Gr.or(Xt.extend({toolResult:Ut.unknown()}));const Jr=Jt.extend({method:Ut.literal("tools/call"),params:Gt.extend({name:Ut.string(),arguments:Ut.optional(Ut.record(Ut.unknown()))})}),Kr=Yt.extend({method:Ut.literal("notifications/tools/list_changed")}),Yr=Ut.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Xr=Jt.extend({method:Ut.literal("logging/setLevel"),params:Gt.extend({level:Yr})}),Qr=Yt.extend({method:Ut.literal("notifications/message"),params:Kt.extend({level:Yr,logger:Ut.optional(Ut.string()),data:Ut.unknown()})}),es=Ut.object({name:Ut.string().optional()}).passthrough(),ts=Ut.object({hints:Ut.optional(Ut.array(es)),costPriority:Ut.optional(Ut.number().min(0).max(1)),speedPriority:Ut.optional(Ut.number().min(0).max(1)),intelligencePriority:Ut.optional(Ut.number().min(0).max(1))}).passthrough(),rs=Ut.object({role:Ut.enum(["user","assistant"]),content:Ut.union([Br,qr])}).passthrough(),ss=Jt.extend({method:Ut.literal("sampling/createMessage"),params:Gt.extend({messages:Ut.array(rs),systemPrompt:Ut.optional(Ut.string()),includeContext:Ut.optional(Ut.enum(["none","thisServer","allServers"])),temperature:Ut.optional(Ut.number()),maxTokens:Ut.number().int(),stopSequences:Ut.optional(Ut.array(Ut.string())),metadata:Ut.optional(Ut.object({}).passthrough()),modelPreferences:Ut.optional(ts)})}),ns=Xt.extend({model:Ut.string(),stopReason:Ut.optional(Ut.enum(["endTurn","stopSequence","maxTokens"]).or(Ut.string())),role:Ut.enum(["user","assistant"]),content:Ut.discriminatedUnion("type",[Br,qr])}),is=Ut.object({type:Ut.literal("ref/resource"),uri:Ut.string()}).passthrough(),as=Ut.object({type:Ut.literal("ref/prompt"),name:Ut.string()}).passthrough(),os=Jt.extend({method:Ut.literal("completion/complete"),params:Gt.extend({ref:Ut.union([as,is]),argument:Ut.object({name:Ut.string(),value:Ut.string()}).passthrough()})}),cs=Xt.extend({completion:Ut.object({values:Ut.array(Ut.string()).max(100),total:Ut.optional(Ut.number().int()),hasMore:Ut.optional(Ut.boolean())}).passthrough()}),ds=Ut.object({uri:Ut.string().startsWith("file://"),name:Ut.optional(Ut.string())}).passthrough(),ls=Jt.extend({method:Ut.literal("roots/list")}),us=Xt.extend({roots:Ut.array(ds)}),hs=Yt.extend({method:Ut.literal("notifications/roots/list_changed")});Ut.union([fr,lr,os,Xr,$r,Zr,Sr,Cr,Or,jr,Ir,Jr,Wr]),Ut.union([or,gr,pr,hs]),Ut.union([ar,ns,us]),Ut.union([fr,ss,ls]),Ut.union([or,gr,Qr,Rr,Nr,Kr,zr]),Ut.union([ar,hr,cs,Dr,Lr,Er,Tr,Pr,Gr,Vr]);class ps extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r}}class fs{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this.setNotificationHandler(or,(e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)})),this.setNotificationHandler(gr,(e=>{this._onprogress(e)})),this.setRequestHandler(fr,(e=>({})))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=e=>{this._onerror(e)},this._transport.onmessage=e=>{"method"in e?"id"in e?this._onrequest(e):this._onnotification(e):this._onresponse(e)},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new ps(sr.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then((()=>r(e))).catch((e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`))))}_onrequest(e){var t,r;const s=null!==(t=this._requestHandlers.get(e.method))&&void 0!==t?t:this.fallbackRequestHandler;if(void 0===s)return void(null===(r=this._transport)||void 0===r||r.send({jsonrpc:"2.0",id:e.id,error:{code:sr.MethodNotFound,message:"Method not found"}}).catch((e=>this._onerror(new Error(`Failed to send an error response: ${e}`)))));const n=new AbortController;this._requestHandlerAbortControllers.set(e.id,n),Promise.resolve().then((()=>s(e,{signal:n.signal}))).then((t=>{var r;if(!n.signal.aborted)return null===(r=this._transport)||void 0===r?void 0:r.send({result:t,jsonrpc:"2.0",id:e.id})}),(t=>{var r,s;if(!n.signal.aborted)return null===(r=this._transport)||void 0===r?void 0:r.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:sr.InternalError,message:null!==(s=t.message)&&void 0!==s?s:"Internal error"}})})).catch((e=>this._onerror(new Error(`Failed to send response: ${e}`)))).finally((()=>{this._requestHandlerAbortControllers.delete(e.id)}))}_onprogress(e){const{progressToken:t,...r}=e.params,s=this._progressHandlers.get(Number(t));void 0!==s?s(r):this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`))}_onresponse(e){const t=e.id,r=this._responseHandlers.get(Number(t));if(void 0!==r)if(this._responseHandlers.delete(Number(t)),this._progressHandlers.delete(Number(t)),"result"in e)r(e);else{r(new ps(e.error.code,e.error.message,e.error.data))}else this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){return new Promise(((s,n)=>{var i,a,o,c;if(!this._transport)return void n(new Error("Not connected"));!0===(null===(i=this._options)||void 0===i?void 0:i.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(a=null==r?void 0:r.signal)||void 0===a||a.throwIfAborted();const d=this._requestMessageId++,l={...e,jsonrpc:"2.0",id:d};let u;(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(d,r.onprogress),l.params={...e.params,_meta:{progressToken:d}}),this._responseHandlers.set(d,(e=>{var i;if(void 0!==u&&clearTimeout(u),!(null===(i=null==r?void 0:r.signal)||void 0===i?void 0:i.aborted)){if(e instanceof Error)return n(e);try{const r=t.parse(e.result);s(r)}catch(e){n(e)}}}));const h=e=>{var t;this._responseHandlers.delete(d),this._progressHandlers.delete(d),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(e)}}).catch((e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)))),n(e)};null===(o=null==r?void 0:r.signal)||void 0===o||o.addEventListener("abort",(()=>{var e;void 0!==u&&clearTimeout(u),h(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)}));const p=null!==(c=null==r?void 0:r.timeout)&&void 0!==c?c:6e4;u=setTimeout((()=>h(new ps(sr.RequestTimeout,"Request timed out",{timeout:p}))),p),this._transport.send(l).catch((e=>{void 0!==u&&clearTimeout(u),n(e)}))}))}async notification(e){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const t={...e,jsonrpc:"2.0"};await this._transport.send(t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,((r,s)=>Promise.resolve(t(e.parse(r),s))))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,(r=>Promise.resolve(t(e.parse(r)))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}class ms extends fs{constructor(e,t){var r;super(t),this._serverInfo=e,this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._instructions=null==t?void 0:t.instructions,this.setRequestHandler(lr,(e=>this._oninitialize(e))),this.setNotificationHandler(pr,(()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)}))}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t,r;this._capabilities=(t=this._capabilities,r=e,Object.entries(r).reduce(((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e)),{...t}))}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(null===(t=this._clientCapabilities)||void 0===t?void 0:t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(null===(r=this._clientCapabilities)||void 0===r?void 0:r.roots))throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new 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 new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`)}}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:zt.includes(t)?t:Dt,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"},ar)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},ns,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},us,t)}async sendLoggingMessage(e){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"})}}const gs=Symbol("Let zodToJsonSchema decide on which parser to use"),_s={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},ys=e=>{const t=(e=>({..._s,...e}))(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function vs(e,t,r,s){s?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function bs(e,t,r,s,n){e[t]=r,vs(e,t,s,n)}function ws(e,t){return Gs(e.type._def,t)}function xs(e,t,r){const s=r??t.dateStrategy;if(Array.isArray(s))return{anyOf:s.map(((r,s)=>xs(e,t,r)))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ks(e,t)}}const ks=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const s of e.checks)switch(s.kind){case"min":bs(r,"minimum",s.value,s.message,t);break;case"max":bs(r,"maximum",s.value,s.message,t)}return r};let Ss;const Es=/^[cC][^\s-]{8,}$/,Cs=/^[0-9a-z]+$/,Ts=/^[0-9A-HJKMNP-TV-Z]{26}$/,Os=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Ps=()=>(void 0===Ss&&(Ss=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ss),Ns=/^(?:(?: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])$/,js=/^(([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])$/,Is=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ms=/^[a-zA-Z0-9_-]{21}$/,As=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Zs(e,t){const r={type:"string"};if(e.checks)for(const s of e.checks)switch(s.kind){case"min":bs(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,s.value):s.value,s.message,t);break;case"max":bs(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,s.value):s.value,s.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Bs(r,"email",s.message,t);break;case"format:idn-email":Bs(r,"idn-email",s.message,t);break;case"pattern:zod":qs(r,Os,s.message,t)}break;case"url":Bs(r,"uri",s.message,t);break;case"uuid":Bs(r,"uuid",s.message,t);break;case"regex":qs(r,s.regex,s.message,t);break;case"cuid":qs(r,Es,s.message,t);break;case"cuid2":qs(r,Cs,s.message,t);break;case"startsWith":qs(r,RegExp(`^${Ls(s.value,t)}`),s.message,t);break;case"endsWith":qs(r,RegExp(`${Ls(s.value,t)}$`),s.message,t);break;case"datetime":Bs(r,"date-time",s.message,t);break;case"date":Bs(r,"date",s.message,t);break;case"time":Bs(r,"time",s.message,t);break;case"duration":Bs(r,"duration",s.message,t);break;case"length":bs(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,s.value):s.value,s.message,t),bs(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,s.value):s.value,s.message,t);break;case"includes":qs(r,RegExp(Ls(s.value,t)),s.message,t);break;case"ip":"v6"!==s.version&&Bs(r,"ipv4",s.message,t),"v4"!==s.version&&Bs(r,"ipv6",s.message,t);break;case"base64url":qs(r,Rs,s.message,t);break;case"jwt":qs(r,As,s.message,t);break;case"cidr":"v6"!==s.version&&qs(r,Ns,s.message,t),"v4"!==s.version&&qs(r,js,s.message,t);break;case"emoji":qs(r,Ps(),s.message,t);break;case"ulid":qs(r,Ts,s.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Bs(r,"binary",s.message,t);break;case"contentEncoding:base64":bs(r,"contentEncoding","base64",s.message,t);break;case"pattern:zod":qs(r,Is,s.message,t)}break;case"nanoid":qs(r,Ms,s.message,t)}return r}function Ls(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)$s.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}const $s=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Bs(e,t,r,s){e.format||e.anyOf?.some((e=>e.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&s.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&s.errorMessages&&{errorMessage:{format:r}}})):bs(e,"format",t,r,s)}function qs(e,t,r,s){e.pattern||e.allOf?.some((e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&s.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:Fs(t,s),...r&&s.errorMessages&&{errorMessage:{pattern:r}}})):bs(e,"pattern",Fs(t,s),r,s)}function Fs(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),s=e.flags.includes("m"),n=e.flags.includes("s"),i=r?e.source.toLowerCase():e.source;let a="",o=!1,c=!1,d=!1;for(let e=0;e<i.length;e++)if(o)a+=i[e],o=!1;else{if(r)if(c){if(i[e].match(/[a-z]/)){d?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),d=!1):"-"===i[e+1]&&i[e+2]?.match(/[a-z]/)?(a+=i[e],d=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}if(s){if("^"===i[e]){a+="(^|(?<=[\r\n]))";continue}if("$"===i[e]){a+="($|(?=[\r\n]))";continue}}n&&"."===i[e]?a+=c?`${i[e]}\r\n`:`[${i[e]}\r\n]`:(a+=i[e],"\\"===i[e]?o=!0:c&&"]"===i[e]?c=!1:c||"["!==i[e]||(c=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function Us(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===it.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce(((r,s)=>({...r,[s]:Gs(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??{}})),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Gs(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===it.ZodString&&e.keyType._def.checks?.length){const{type:s,...n}=Zs(e.keyType._def,t);return{...r,propertyNames:n}}if(e.keyType?._def.typeName===it.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===it.ZodBranded&&e.keyType._def.type._def.typeName===it.ZodString&&e.keyType._def.type._def.checks?.length){const{type:s,...n}=ws(e.keyType._def,t);return{...r,propertyNames:n}}return r}const Ds={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const zs=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>Gs(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return r.length?{anyOf:r}:void 0};function Hs(e,t){const r="openAi"===t.target,s={type:"object",properties:{}},n=[],i=e.shape();for(const e in i){let a=i[e];if(void 0===a||void 0===a._def)continue;let o=Ws(a);o&&r&&(a instanceof Ve&&(a=a._def.innerType),a.isNullable()||(a=a.nullable()),o=!1);const c=Gs(a._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(s.properties[e]=c,o||n.push(e))}n.length&&(s.required=n);const a=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return Gs(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==a&&(s.additionalProperties=a),s}function Ws(e){try{return e.isOptional()}catch{return!0}}const Vs=(e,t,r)=>{switch(t){case it.ZodString:return Zs(e,r);case it.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const s of e.checks)switch(s.kind){case"int":r.type="integer",vs(r,"type",s.message,t);break;case"min":"jsonSchema7"===t.target?s.inclusive?bs(r,"minimum",s.value,s.message,t):bs(r,"exclusiveMinimum",s.value,s.message,t):(s.inclusive||(r.exclusiveMinimum=!0),bs(r,"minimum",s.value,s.message,t));break;case"max":"jsonSchema7"===t.target?s.inclusive?bs(r,"maximum",s.value,s.message,t):bs(r,"exclusiveMaximum",s.value,s.message,t):(s.inclusive||(r.exclusiveMaximum=!0),bs(r,"maximum",s.value,s.message,t));break;case"multipleOf":bs(r,"multipleOf",s.value,s.message,t)}return r}(e,r);case it.ZodObject:return Hs(e,r);case it.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const s of e.checks)switch(s.kind){case"min":"jsonSchema7"===t.target?s.inclusive?bs(r,"minimum",s.value,s.message,t):bs(r,"exclusiveMinimum",s.value,s.message,t):(s.inclusive||(r.exclusiveMinimum=!0),bs(r,"minimum",s.value,s.message,t));break;case"max":"jsonSchema7"===t.target?s.inclusive?bs(r,"maximum",s.value,s.message,t):bs(r,"exclusiveMaximum",s.value,s.message,t):(s.inclusive||(r.exclusiveMaximum=!0),bs(r,"maximum",s.value,s.message,t));break;case"multipleOf":bs(r,"multipleOf",s.value,s.message,t)}return r}(e,r);case it.ZodBoolean:return{type:"boolean"};case it.ZodDate:return xs(e,r);case it.ZodUndefined:return{not:{}};case it.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case it.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==it.ZodAny&&(r.items=Gs(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&bs(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&bs(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(bs(r,"minItems",e.exactLength.value,e.exactLength.message,t),bs(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case it.ZodUnion:case it.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return zs(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e._def.typeName in Ds&&(!e._def.checks||!e._def.checks.length)))){const e=r.reduce(((e,t)=>{const r=Ds[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e}),[]);return{type:e.length>1?e:e[0]}}if(r.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=r.reduce(((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===r.length){const t=e.filter(((e,t,r)=>r.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:r.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(r.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:r.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return zs(e,t)}(e,r);case it.ZodIntersection:return function(e,t){const r=[Gs(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Gs(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let s="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const n=[];return r.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...s}=e;t=s}else s=void 0;n.push(t)}else n.push(...e.allOf),void 0===e.unevaluatedProperties&&(s=void 0);var t})),n.length?{allOf:n,...s}:void 0}(e,r);case it.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>Gs(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:Gs(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>Gs(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,r);case it.ZodRecord:return Us(e,r);case it.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case it.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case it.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),s=Array.from(new Set(r.map((e=>typeof e))));return{type:1===s.length?"string"===s[0]?"string":"number":["string","number"],enum:r}}(e);case it.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:Ds[e.innerType._def.typeName],nullable:!0}:{type:[Ds[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=Gs(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=Gs(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case it.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Gs(e.innerType._def,t);const r=Gs(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case it.ZodMap:return function(e,t){return"record"===t.mapStrategy?Us(e,t):{type:"array",maxItems:125,items:{type:"array",items:[Gs(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},Gs(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case it.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:Gs(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&bs(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&bs(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case it.ZodLazy:return()=>e.getter()._def;case it.ZodPromise:return function(e,t){return Gs(e.type._def,t)}(e,r);case it.ZodNaN:case it.ZodNever:return{not:{}};case it.ZodEffects:return function(e,t){return"input"===t.effectStrategy?Gs(e.schema._def,t):{}}(e,r);case it.ZodAny:case it.ZodUnknown:return{};case it.ZodDefault:return function(e,t){return{...Gs(e.innerType._def,t),default:e.defaultValue()}}(e,r);case it.ZodBranded:return ws(e,r);case it.ZodReadonly:case it.ZodCatch:return((e,t)=>Gs(e.innerType._def,t))(e,r);case it.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return Gs(e.in._def,t);if("output"===t.pipeStrategy)return Gs(e.out._def,t);const r=Gs(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,Gs(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}})(e,r);case it.ZodFunction:case it.ZodVoid:case it.ZodSymbol:default:return}};function Gs(e,t,r=!1){const s=t.seen.get(e);if(t.override){const n=t.override?.(e,t,s,r);if(n!==gs)return n}if(s&&!r){const e=Js(s,t);if(void 0!==e)return e}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const i=Vs(e,e.typeName,t),a="function"==typeof i?Gs(i(),t):i;if(a&&Ys(e,t,a),t.postProcess){const r=t.postProcess(a,e,t);return n.jsonSchema=a,r}return n.jsonSchema=a,a}const Js=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ks(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every(((e,r)=>t.currentPath[r]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):"seen"===t.$refStrategy?{}:void 0}},Ks=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},Ys=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),Xs=(e,t)=>{const r=ys(t),s=void 0,n=t?.name,i=Gs(e._def,r,!1)??{},a=void 0===n?i:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...s,[n]:i}};return"jsonSchema7"===r.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};var Qs;!function(e){e.Completable="McpCompletable"}(Qs||(Qs={}));class en extends W{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}function tn(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{var i,a;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:n.defaultError}:void 0===n.data?{message:null!==(i=null!=o?o:s)&&void 0!==i?i:n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:null!==(a=null!=o?o:r)&&void 0!==a?a:n.defaultError}},description:n}}en.create=(e,t)=>new en({type:e,typeName:Qs.Completable,complete:t.complete,...tn(t)});const rn={type:"object"};function sn(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const nn={completion:{values:[],hasMore:!1}};class an{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e);return this._buffer=this._buffer.subarray(e+1),function(e){return ir.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}function on(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var cn={exports:{}};const dn=["nodebuffer","arraybuffer","fragments"],ln="undefined"!=typeof Blob;ln&&dn.push("blob");var un={BINARY_TYPES:dn,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ln,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:hn}=un,pn=Buffer[Symbol.species];function fn(e,t,r,s,n){for(let i=0;i<n;i++)r[s+i]=e[i]^t[3&i]}function mn(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(cn.exports={concat:function(e,t){if(0===e.length)return hn;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let s=0;for(let t=0;t<e.length;t++){const n=e[t];r.set(n,s),s+=n.length}return s<t?new pn(r.buffer,r.byteOffset,s):r},mask:fn,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new pn(t):ArrayBuffer.isView(t)?r=new pn(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:mn},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");cn.exports.mask=function(t,r,s,n,i){i<48?fn(t,r,s,n,i):e.mask(t,r,s,n,i)},cn.exports.unmask=function(t,r){t.length<32?mn(t,r):e.unmask(t,r)}}catch(e){}var gn=cn.exports;const _n=Symbol("kDone"),yn=Symbol("kRun");const vn=_,bn=gn,wn=class{constructor(e){this[_n]=()=>{this.pending--,this[yn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[yn]()}[yn](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[_n])}}},{kStatusCode:xn}=un,kn=Buffer[Symbol.species],Sn=Buffer.from([0,0,255,255]),En=Symbol("permessage-deflate"),Cn=Symbol("total-length"),Tn=Symbol("callback"),On=Symbol("buffers"),Pn=Symbol("error");let Nn;var jn=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Nn){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Nn=new wn(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[Tn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){Nn.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){Nn.add((s=>{this._compress(e,t,((e,t)=>{s(),r(e,t)}))}))}_decompress(e,t,r){const s=this._isServer?"client":"server";if(!this._inflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?vn.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=vn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[En]=this,this._inflate[Cn]=0,this._inflate[On]=[],this._inflate.on("error",Mn),this._inflate.on("data",Rn)}this._inflate[Tn]=r,this._inflate.write(e),t&&this._inflate.write(Sn),this._inflate.flush((()=>{const e=this._inflate[Pn];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=bn.concat(this._inflate[On],this._inflate[Cn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Cn]=0,this._inflate[On]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,n)}))}_compress(e,t,r){const s=this._isServer?"server":"client";if(!this._deflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?vn.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=vn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Cn]=0,this._deflate[On]=[],this._deflate.on("data",In)}this._deflate[Tn]=r,this._deflate.write(e),this._deflate.flush(vn.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=bn.concat(this._deflate[On],this._deflate[Cn]);t&&(e=new kn(e.buffer,e.byteOffset,e.length-4)),this._deflate[Tn]=null,this._deflate[Cn]=0,this._deflate[On]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function In(e){this[On].push(e),this[Cn]+=e.length}function Rn(e){this[Cn]+=e.length,this[En]._maxPayload<1||this[Cn]<=this[En]._maxPayload?this[On].push(e):(this[Pn]=new RangeError("Max payload size exceeded"),this[Pn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pn][xn]=1009,this.removeListener("data",Rn),this.reset())}function Mn(e){this[En]._inflate=null,this[Pn]?this[Tn](this[Pn]):(e[xn]=1007,this[Tn](e))}var An={exports:{}};const{isUtf8:Zn}=y,{hasBlob:Ln}=un;function $n(e){const t=e.length;let r=0;for(;r<t;)if(128&e[r])if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}else r++;return!0}if(An.exports={isBlob:function(e){return Ln&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:$n,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},Zn)An.exports.isValidUTF8=function(e){return e.length<24?$n(e):Zn(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");An.exports.isValidUTF8=function(t){return t.length<32?$n(t):e(t)}}catch(e){}var Bn=An.exports;const{Writable:qn}=m,Fn=jn,{BINARY_TYPES:Un,EMPTY_BUFFER:Dn,kStatusCode:zn,kWebSocket:Hn}=un,{concat:Wn,toArrayBuffer:Vn,unmask:Gn}=gn,{isValidStatusCode:Jn,isValidUTF8:Kn}=Bn,Yn=Buffer[Symbol.species];var Xn=class extends qn{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Un[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Hn]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Yn(t.buffer,t.byteOffset+e,t.length-e),new Yn(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Yn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const r=!(64&~t[0]);if(!r||this._extensions[Fn.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=r}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else{e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}else this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}else this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=Dn;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&Gn(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[Fn.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let s;s="nodebuffer"===this._binaryType?Wn(r,t):"arraybuffer"===this._binaryType?Vn(Wn(r,t)):"blob"===this._binaryType?new Blob(r):r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",s,!0),this._state=0,this.startLoop(e)})))}else{const s=Wn(r,t);if(!this._skipUTF8Validation&&!Kn(s)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",s,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,Dn),this.end();else{const r=e.readUInt16BE(0);if(!Jn(r)){const e=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const s=new Yn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Kn(s)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=0}}createError(e,t,r,s,n){this._loop=!1,this._errored=!0;const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=n,i[zn]=s,i}};const{Duplex:Qn}=m,{randomFillSync:ei}=f,ti=jn,{EMPTY_BUFFER:ri,kWebSocket:si,NOOP:ni}=un,{isBlob:ii,isValidStatusCode:ai}=Bn,{mask:oi,toBuffer:ci}=gn,di=Symbol("kByteLength"),li=Buffer.alloc(4),ui=8192;let hi,pi=ui;var fi=class e{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=ni,this[si]=void 0}static frame(e,t){let r,s,n=!1,i=2,a=!1;t.mask&&(r=t.maskBuffer||li,t.generateMask?t.generateMask(r):(pi===ui&&(void 0===hi&&(hi=Buffer.alloc(ui)),ei(hi,0,ui),pi=0),r[0]=hi[pi++],r[1]=hi[pi++],r[2]=hi[pi++],r[3]=hi[pi++]),a=!(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?s=t.mask&&!a||void 0===t[di]?(e=Buffer.from(e)).length:t[di]:(s=e.length,n=t.mask&&t.readOnly&&!a);let o=s;s>=65536?(i+=8,o=127):s>125&&(i+=2,o=126);const c=Buffer.allocUnsafe(n?s+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=o,126===o?c.writeUInt16BE(s,2):127===o&&(c[2]=c[3]=0,c.writeUIntBE(s,4,6)),t.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],a?[c,e]:n?(oi(e,r,c,i,s),[c]):(oi(e,r,e,0,s),[c,e])):[c,e]}close(t,r,s,n){let i;if(void 0===t)i=ri;else{if("number"!=typeof t||!ai(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==r&&r.length){const e=Buffer.byteLength(r);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+e),i.writeUInt16BE(t,0),"string"==typeof r?i.write(r,2):i.set(r,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(t,0)}const a={[di]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,a,n]):this.sendFrame(e.frame(i,a),n)}ping(t,r,s){let n,i;if("string"==typeof t?(n=Buffer.byteLength(t),i=!1):ii(t)?(n=t.size,i=!1):(n=(t=ci(t)).length,i=ci.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const a={[di]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ii(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,a,s]):this.getBlobData(t,!1,a,s):0!==this._state?this.enqueue([this.dispatch,t,!1,a,s]):this.sendFrame(e.frame(t,a),s)}pong(t,r,s){let n,i;if("string"==typeof t?(n=Buffer.byteLength(t),i=!1):ii(t)?(n=t.size,i=!1):(n=(t=ci(t)).length,i=ci.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const a={[di]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ii(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,a,s]):this.getBlobData(t,!1,a,s):0!==this._state?this.enqueue([this.dispatch,t,!1,a,s]):this.sendFrame(e.frame(t,a),s)}send(e,t,r){const s=this._extensions[ti.extensionName];let n,i,a=t.binary?2:1,o=t.compress;"string"==typeof e?(n=Buffer.byteLength(e),i=!1):ii(e)?(n=e.size,i=!1):(n=(e=ci(e)).length,i=ci.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=n>=s._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);const c={[di]:n,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:i,rsv1:o};ii(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(t,r,s,n){this._bufferedBytes+=s[di],this._state=2,t.arrayBuffer().then((t=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(mi,this,e,n)}this._bufferedBytes-=s[di];const i=ci(t);r?this.dispatch(i,r,s,n):(this._state=0,this.sendFrame(e.frame(i,s),n),this.dequeue())})).catch((e=>{process.nextTick(gi,this,e,n)}))}dispatch(t,r,s,n){if(!r)return void this.sendFrame(e.frame(t,s),n);const i=this._extensions[ti.extensionName];this._bufferedBytes+=s[di],this._state=1,i.compress(t,s.fin,((t,r)=>{if(this._socket.destroyed){mi(this,new Error("The socket was closed while data was being compressed"),n)}else this._bufferedBytes-=s[di],this._state=0,s.readOnly=!1,this.sendFrame(e.frame(r,s),n),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][di],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][di],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function mi(e,t,r){"function"==typeof r&&r(t);for(let r=0;r<e._queue.length;r++){const s=e._queue[r],n=s[s.length-1];"function"==typeof n&&n(t)}}function gi(e,t,r){mi(e,t,r),e.onerror(t)}const{kForOnEventAttribute:_i,kListener:yi}=un,vi=Symbol("kCode"),bi=Symbol("kData"),wi=Symbol("kError"),xi=Symbol("kMessage"),ki=Symbol("kReason"),Si=Symbol("kTarget"),Ei=Symbol("kType"),Ci=Symbol("kWasClean");class Ti{constructor(e){this[Si]=null,this[Ei]=e}get target(){return this[Si]}get type(){return this[Ei]}}Object.defineProperty(Ti.prototype,"target",{enumerable:!0}),Object.defineProperty(Ti.prototype,"type",{enumerable:!0});class Oi extends Ti{constructor(e,t={}){super(e),this[vi]=void 0===t.code?0:t.code,this[ki]=void 0===t.reason?"":t.reason,this[Ci]=void 0!==t.wasClean&&t.wasClean}get code(){return this[vi]}get reason(){return this[ki]}get wasClean(){return this[Ci]}}Object.defineProperty(Oi.prototype,"code",{enumerable:!0}),Object.defineProperty(Oi.prototype,"reason",{enumerable:!0}),Object.defineProperty(Oi.prototype,"wasClean",{enumerable:!0});class Pi extends Ti{constructor(e,t={}){super(e),this[wi]=void 0===t.error?null:t.error,this[xi]=void 0===t.message?"":t.message}get error(){return this[wi]}get message(){return this[xi]}}Object.defineProperty(Pi.prototype,"error",{enumerable:!0}),Object.defineProperty(Pi.prototype,"message",{enumerable:!0});class Ni extends Ti{constructor(e,t={}){super(e),this[bi]=void 0===t.data?null:t.data}get data(){return this[bi]}}Object.defineProperty(Ni.prototype,"data",{enumerable:!0});var ji={EventTarget:{addEventListener(e,t,r={}){for(const s of this.listeners(e))if(!r[_i]&&s[yi]===t&&!s[_i])return;let s;if("message"===e)s=function(e,r){const s=new Ni("message",{data:r?e:e.toString()});s[Si]=this,Ii(t,this,s)};else if("close"===e)s=function(e,r){const s=new Oi("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Si]=this,Ii(t,this,s)};else if("error"===e)s=function(e){const r=new Pi("error",{error:e,message:e.message});r[Si]=this,Ii(t,this,r)};else{if("open"!==e)return;s=function(){const e=new Ti("open");e[Si]=this,Ii(t,this,e)}}s[_i]=!!r[_i],s[yi]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[yi]===t&&!r[_i]){this.removeListener(e,r);break}}}};function Ii(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:Ri}=Bn;function Mi(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var Ai={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,s,n=Object.create(null),i=!1,a=!1,o=!1,c=-1,d=-1,l=-1,u=0;for(;u<e.length;u++)if(d=e.charCodeAt(u),void 0===r)if(-1===l&&1===Ri[d])-1===c&&(c=u);else if(0===u||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u);const s=e.slice(c,l);44===d?(Mi(t,s,n),n=Object.create(null)):r=s,c=l=-1}}else-1===l&&-1!==c&&(l=u);else if(void 0===s)if(-1===l&&1===Ri[d])-1===c&&(c=u);else if(32===d||9===d)-1===l&&-1!==c&&(l=u);else if(59===d||44===d){if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u),Mi(n,e.slice(c,l),!0),44===d&&(Mi(t,r,n),n=Object.create(null),r=void 0),c=l=-1}else{if(61!==d||-1===c||-1!==l)throw new SyntaxError(`Unexpected character at index ${u}`);s=e.slice(c,u),c=l=-1}else if(a){if(1!==Ri[d])throw new SyntaxError(`Unexpected character at index ${u}`);-1===c?c=u:i||(i=!0),a=!1}else if(o)if(1===Ri[d])-1===c&&(c=u);else if(34===d&&-1!==c)o=!1,l=u;else{if(92!==d)throw new SyntaxError(`Unexpected character at index ${u}`);a=!0}else if(34===d&&61===e.charCodeAt(u-1))o=!0;else if(-1===l&&1===Ri[d])-1===c&&(c=u);else if(-1===c||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u);let a=e.slice(c,l);i&&(a=a.replace(/\\/g,""),i=!1),Mi(n,s,a),44===d&&(Mi(t,r,n),n=Object.create(null),r=void 0),s=void 0,c=l=-1}}else-1===l&&(l=u);if(-1===c||o||32===d||9===d)throw new SyntaxError("Unexpected end of input");-1===l&&(l=u);const h=e.slice(c,l);return void 0===r?Mi(t,h,n):(void 0===s?Mi(n,h,!0):Mi(n,s,i?h.replace(/\\/g,""):h),Mi(t,r,n)),t}};const Zi=d,Li=l,$i=u,Bi=h,qi=p,{randomBytes:Fi,createHash:Ui}=f,{Duplex:Di,Readable:zi}=m,{URL:Hi}=g,Wi=jn,Vi=Xn,Gi=fi,{isBlob:Ji}=Bn,{BINARY_TYPES:Ki,EMPTY_BUFFER:Yi,GUID:Xi,kForOnEventAttribute:Qi,kListener:ea,kStatusCode:ta,kWebSocket:ra,NOOP:sa}=un,{EventTarget:{addEventListener:na,removeEventListener:ia}}=ji,{format:aa,parse:oa}=Ai,{toBuffer:ca}=gn,da=Symbol("kAborted"),la=[8,13],ua=["CONNECTING","OPEN","CLOSING","CLOSED"],ha=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let pa=class e extends Zi{constructor(t,r,s){super(),this._binaryType=Ki[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Yi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==t?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===r?r=[]:Array.isArray(r)||("object"==typeof r&&null!==r?(s=r,r=[]):r=[r]),ma(this,t,r,s)):(this._autoPong=s.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ki.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,s){const n=new Vi({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new Gi(t,this._extensions,s.generateMask);this._receiver=n,this._sender=i,this._socket=t,n[ra]=this,i[ra]=this,t[ra]=this,n.on("conclude",wa),n.on("drain",xa),n.on("error",ka),n.on("message",Ea),n.on("ping",Ca),n.on("pong",Ta),i.onerror=Pa,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",ja),t.on("data",Ia),t.on("end",Ra),t.on("error",Ma),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=e.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[Wi.extensionName]&&this._extensions[Wi.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this.readyState!==e.CLOSING?(this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),Na(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";va(this,this._req,e)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,r,s){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(s=t,t=r=void 0):"function"==typeof r&&(s=r,r=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===r&&(r=!this._isServer),this._sender.ping(t||Yi,r,s)):ba(this,t,s)}pong(t,r,s){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(s=t,t=r=void 0):"function"==typeof r&&(s=r,r=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===r&&(r=!this._isServer),this._sender.pong(t||Yi,r,s)):ba(this,t,s)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,s){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof r&&(s=r,r={}),"number"==typeof t&&(t=t.toString()),this.readyState!==e.OPEN)return void ba(this,t,s);const n={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Wi.extensionName]||(n.compress=!1),this._sender.send(t||Yi,n,s)}terminate(){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this._socket&&(this._readyState=e.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";va(this,this._req,e)}}};Object.defineProperty(pa,"CONNECTING",{enumerable:!0,value:ua.indexOf("CONNECTING")}),Object.defineProperty(pa.prototype,"CONNECTING",{enumerable:!0,value:ua.indexOf("CONNECTING")}),Object.defineProperty(pa,"OPEN",{enumerable:!0,value:ua.indexOf("OPEN")}),Object.defineProperty(pa.prototype,"OPEN",{enumerable:!0,value:ua.indexOf("OPEN")}),Object.defineProperty(pa,"CLOSING",{enumerable:!0,value:ua.indexOf("CLOSING")}),Object.defineProperty(pa.prototype,"CLOSING",{enumerable:!0,value:ua.indexOf("CLOSING")}),Object.defineProperty(pa,"CLOSED",{enumerable:!0,value:ua.indexOf("CLOSED")}),Object.defineProperty(pa.prototype,"CLOSED",{enumerable:!0,value:ua.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(pa.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(pa.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[Qi])return t[ea];return null},set(t){for(const t of this.listeners(e))if(t[Qi]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[Qi]:!0})}})})),pa.prototype.addEventListener=na,pa.prototype.removeEventListener=ia;var fa=pa;function ma(e,t,r,s){const n={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:la[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=n.autoPong,!la.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${la.join(", ")})`);let i;if(t instanceof Hi)i=t;else try{i=new Hi(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===i.protocol?i.protocol="ws:":"https:"===i.protocol&&(i.protocol="wss:"),e._url=i.href;const a="wss:"===i.protocol,o="ws+unix:"===i.protocol;let c;if("ws:"===i.protocol||a||o?o&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void ga(e,t)}const d=a?443:80,l=Fi(16).toString("base64"),u=a?Li.request:$i.request,h=new Set;let p,f;if(n.createConnection=n.createConnection||(a?ya:_a),n.defaultPort=n.defaultPort||d,n.port=i.port||d,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(p=new Wi(!0!==n.perMessageDeflate?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=aa({[Wi.extensionName]:p.offer()})),r.length){for(const e of r){if("string"!=typeof e||!ha.test(e)||h.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(e)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),o){const e=n.path.split(":");n.socketPath=e[0],n.path=e[1]}if(n.followRedirects){if(0===e._redirects){e._originalIpc=o,e._originalSecure=a,e._originalHostOrSocketPath=o?n.socketPath:i.host;const t=s&&s.headers;if(s={...s,headers:{}},t)for(const[e,r]of Object.entries(t))s.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=o?!!e._originalIpc&&n.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!a)&&(delete n.headers.authorization,delete n.headers.cookie,t||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),f=e._req=u(n),e._redirects&&e.emit("redirect",e.url,f)}else f=e._req=u(n);n.timeout&&f.on("timeout",(()=>{va(e,f,"Opening handshake has timed out")})),f.on("error",(t=>{null===f||f[da]||(f=e._req=null,ga(e,t))})),f.on("response",(i=>{const a=i.headers.location,o=i.statusCode;if(a&&n.followRedirects&&o>=300&&o<400){if(++e._redirects>n.maxRedirects)return void va(e,f,"Maximum redirects exceeded");let i;f.abort();try{i=new Hi(a,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${a}`);return void ga(e,r)}ma(e,i,r,s)}else e.emit("unexpected-response",f,i)||va(e,f,`Unexpected server response: ${i.statusCode}`)})),f.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==pa.CONNECTING)return;f=e._req=null;const i=t.headers.upgrade;if(void 0===i||"websocket"!==i.toLowerCase())return void va(e,r,"Invalid Upgrade header");const a=Ui("sha1").update(l+Xi).digest("base64");if(t.headers["sec-websocket-accept"]!==a)return void va(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let c;if(void 0!==o?h.size?h.has(o)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":h.size&&(c="Server sent no subprotocol"),c)return void va(e,r,c);o&&(e._protocol=o);const d=t.headers["sec-websocket-extensions"];if(void 0!==d){if(!p){return void va(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=oa(d)}catch(t){return void va(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==Wi.extensionName){return void va(e,r,"Server indicated an extension that was not requested")}try{p.accept(t[Wi.extensionName])}catch(t){return void va(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Wi.extensionName]=p}e.setSocket(r,s,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})})),n.finishRequest?n.finishRequest(f,e):f.end()}function ga(e,t){e._readyState=pa.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function _a(e){return e.path=e.socketPath,Bi.connect(e)}function ya(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Bi.isIP(e.host)?"":e.host),qi.connect(e)}function va(e,t,r){e._readyState=pa.CLOSING;const s=new Error(r);Error.captureStackTrace(s,va),t.setHeader?(t[da]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ga,e,s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function ba(e,t,r){if(t){const r=Ji(t)?t.size:ca(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${ua[e.readyState]})`);process.nextTick(r,t)}}function wa(e,t){const r=this[ra];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[ra]&&(r._socket.removeListener("data",Ia),process.nextTick(Oa,r._socket),1005===e?r.close():r.close(e,t))}function xa(){const e=this[ra];e.isPaused||e._socket.resume()}function ka(e){const t=this[ra];void 0!==t._socket[ra]&&(t._socket.removeListener("data",Ia),process.nextTick(Oa,t._socket),t.close(e[ta])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Sa(){this[ra].emitClose()}function Ea(e,t){this[ra].emit("message",e,t)}function Ca(e){const t=this[ra];t._autoPong&&t.pong(e,!this._isServer,sa),t.emit("ping",e)}function Ta(e){this[ra].emit("pong",e)}function Oa(e){e.resume()}function Pa(e){const t=this[ra];t.readyState!==pa.CLOSED&&(t.readyState===pa.OPEN&&(t._readyState=pa.CLOSING,Na(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Na(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function ja(){const e=this[ra];let t;this.removeListener("close",ja),this.removeListener("data",Ia),this.removeListener("end",Ra),e._readyState=pa.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[ra]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Sa),e._receiver.on("finish",Sa))}function Ia(e){this[ra]._receiver.write(e)||this.pause()}function Ra(){const e=this[ra];e._readyState=pa.CLOSING,e._receiver.end(),this.end()}function Ma(){const e=this[ra];this.removeListener("error",Ma),this.on("error",sa),e&&(e._readyState=pa.CLOSING,this.destroy())}const{Duplex:Aa}=m,{tokenChars:Za}=Bn;var La={parse:function(e){const t=new Set;let r=-1,s=-1,n=0;for(;n<e.length;n++){const i=e.charCodeAt(n);if(-1===s&&1===Za[i])-1===r&&(r=n);else if(0===n||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${n}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${n}`);-1===s&&(s=n);const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=s=-1}}else-1===s&&-1!==r&&(s=n)}if(-1===r||-1!==s)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const $a=d,Ba=u,{Duplex:qa}=m,{createHash:Fa}=f,Ua=Ai,Da=jn,za=La,Ha=fa,{GUID:Wa,kWebSocket:Va}=un,Ga=/^[+/0-9A-Za-z]{22}==$/;var Ja=class extends $a{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Ha,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=Ba.createServer(((e,t)=>{const r=Ba.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,s)=>{this.handleUpgrade(t,r,s,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(Ka,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ka,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Ka(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",Ya);const n=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Qa(this,e,t,405,"Invalid HTTP method")}if(void 0===i||"websocket"!==i.toLowerCase()){return void Qa(this,e,t,400,"Invalid Upgrade header")}if(void 0===n||!Ga.test(n)){return void Qa(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==a&&13!==a){return void Qa(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Xa(t,400);const o=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==o)try{c=za.parse(o)}catch(r){return void Qa(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const d=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==d){const r=new Da(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Ua.parse(d);e[Da.extensionName]&&(r.accept(e[Da.extensionName]),l[Da.extensionName]=r)}catch(r){return void Qa(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const i={origin:e.headers[""+(8===a?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(i,((i,a,o,d)=>{if(!i)return Xa(t,a||401,o,d);this.completeUpgrade(l,n,c,e,t,r,s)}));if(!this.options.verifyClient(i))return Xa(t,401)}this.completeUpgrade(l,n,c,e,t,r,s)}completeUpgrade(e,t,r,s,n,i,a){if(!n.readable||!n.writable)return n.destroy();if(n[Va])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Xa(n,503);const o=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Fa("sha1").update(t+Wa).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(o.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[Da.extensionName]){const t=e[Da.extensionName].params,r=Ua.format({[Da.extensionName]:[t]});o.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",o,s),n.write(o.concat("\r\n").join("\r\n")),n.removeListener("error",Ya),c.setSocket(n,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ka,this)}))),a(c,s)}};function Ka(e){e._state=2,e.emit("close")}function Ya(){this.destroy()}function Xa(e,t,r,s){r=r||Ba.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${Ba.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Qa(e,t,r,s,n){if(e.listenerCount("wsClientError")){const s=new Error(n);Error.captureStackTrace(s,Qa),e.emit("wsClientError",s,r,t)}else Xa(r,s,n)}var eo=on(Ja);const to=i(o(import.meta.url)),ro=a(to,"../.."),so=process.env.PORT?Number.parseInt(process.env.PORT):7898,no=[],io=[],ao=s(((t,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept"),"OPTIONS"===t.method)return r.writeHead(204),void r.end();if("/status"===t.url)return r.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*"}),void r.end(JSON.stringify({browserCount:no.length,cursorCount:io.length}));if("/browser-mcp-server.js"!==t.url)if("/browser-inject.js"!==t.url)if("/browser-console-mcp.js"!==t.url)if("/browser-console-mcp.js.map"!==t.url)r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset="utf-8">\n <title>Browser MCP Relay Server</title>\n <style>\n body {\n font-family: Arial, sans-serif;\n line-height: 1.6;\n max-width: 800px;\n margin: 0 auto;\n padding: 20px;\n }\n pre {\n background-color: #f5f5f5;\n padding: 10px;\n border-radius: 5px;\n overflow-x: auto;\n }\n code {\n font-family: monospace;\n }\n .bookmarklet {\n display: inline-block;\n padding: 8px 12px;\n background-color: #f0f0f0;\n border-radius: 4px;\n text-decoration: none;\n color: #333;\n border: 1px solid #ccc;\n }\n .button {\n display: inline-block;\n padding: 8px 12px;\n background-color: #4CAF50;\n color: white;\n border-radius: 4px;\n text-decoration: none;\n margin-right: 10px;\n }\n .button:hover {\n background-color: #45a049;\n }\n </style>\n </head>\n <body>\n <h1>Browser MCP Relay Server</h1>\n <p>Server is running. You can use it as follows:</p>\n \n <h2>Usage</h2>\n \n <h2>Step 1: Inject MCP Client in Browser</h2>\n <p>Drag the following link to your bookmarks bar:</p>\n <a class="bookmarklet" href="javascript:(function(){var s=document.createElement('script');s.src='http://localhost:${so}/browser-inject.js';document.head.appendChild(s);})();">Browser MCP</a>\n \n <p>Or paste the following code in your browser console:</p>\n <pre><code>var s = document.createElement('script');\ns.src = 'http://localhost:${so}/browser-inject.js';\ndocument.head.appendChild(s);</code></pre>\n\n <h2>Step 2: Use MCP Tools in Cursor</h2>\n <p>Now you can use MCP features in Cursor to execute browser commands, such as:</p>\n <pre><code>// Execute JavaScript code in the browser\nexecuteJS({ code: 'console.log(window.location.href)' })\n\n// Get page HTML\ngetPageHTML()\n\n// Get page title\ngetPageTitle()</code></pre>\n\n <h2>Connection Status</h2>\n <p>Browser connection count: <span id="browser-count">0</span></p>\n <p>Cursor connection count: <span id="cursor-count">0</span></p>\n \n <script>\n // Periodically update connection status\n setInterval(() => {\n fetch('/status')\n .then(res => res.json())\n .then(data => {\n document.getElementById('browser-count').textContent = data.browserCount;\n document.getElementById('cursor-count').textContent = data.cursorCount;\n })\n .catch(err => {\n console.error('Failed to get status:', err);\n // Display connection error if there's an error\n document.getElementById('browser-count').textContent = 'Connection error';\n document.getElementById('cursor-count').textContent = 'Connection error';\n });\n }, 5000);\n <\/script>\n </body>\n </html>\n `);else{r.writeHead(200,{"Content-Type":"application/json"});const t=a(ro,"dist/client/browser-console-mcp.js.map");try{const s=e(t,"utf8");r.end(s)}catch(e){console.error("[BCM] Error reading file:",e),r.writeHead(500),r.end("Internal Server Error")}}else{r.writeHead(200,{"Content-Type":"application/javascript"});const t=a(ro,"dist/client/browser-console-mcp.js");try{const s=e(t,"utf8");r.end(s)}catch(e){console.error("[BCM] Error reading file:",e),r.writeHead(500),r.end("Internal Server Error")}}else{r.writeHead(200,{"Content-Type":"application/javascript"});const t=a(to,"browser-inject.js");try{const s=e(t,"utf8");r.end(s)}catch(e){console.error("[BCM] Error reading file:",e),r.writeHead(500),r.end("Internal Server Error")}}else{r.writeHead(200,{"Content-Type":"application/javascript"});const t=a(to,"browser-mcp-server.js");try{const s=e(t,"utf8");r.end(s)}catch(e){console.error("[BCM] Error reading file:",e),r.writeHead(500),r.end("Internal Server Error")}}})),oo=new eo({server:ao});oo.on("connection",((e,t)=>{const r=new URL(t.url||"",`http://${t.headers.host}`).pathname;"/browser"===r?(no.push(e),e.send(JSON.stringify({type:"connection_status",status:"connected",message:"Connected to relay server"})),e.on("message",(e=>{try{if(io.length>0)for(const t of io)t.send(e.toString())}catch(e){console.error("[BCM] Error parsing browser message:",e)}})),e.on("close",(()=>{const t=no.indexOf(e);-1!==t&&no.splice(t,1)}))):"/cursor"===r&&(io.push(e),e.on("message",(e=>{try{JSON.parse(e.toString());if(no.length>0)for(const t of no)t.send(e.toString())}catch(e){console.error("[BCM] Error parsing Cursor message:",e)}})),e.on("close",(()=>{const t=io.indexOf(e);-1!==t&&io.splice(t,1),0===io.length&&setTimeout((()=>{uo(!0)}),2e3)})))}));const co=new class{constructor(e=c.stdin,t=c.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new an,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}}async start(){if(this._started)throw new 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{const t=this._readBuffer.readMessage();if(null===t)break;null===(e=this.onmessage)||void 0===e||e.call(this,t)}catch(e){null===(t=this.onerror)||void 0===t||t.call(this,e)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror);0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}send(e){return new Promise((t=>{const r=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(r)?t():this._stdout.once("drain",t)}))}},lo=new class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ms(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Wr.shape.method.value),this.server.assertCanSetRequestHandler(Jr.shape.method.value),this.server.registerCapabilities({tools:{}}),this.server.setRequestHandler(Wr,(()=>({tools:Object.entries(this._registeredTools).map((([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Xs(t.inputSchema):rn})))}))),this.server.setRequestHandler(Jr,(async(e,t)=>{const r=this._registeredTools[e.params.name];if(!r)throw new ps(sr.InvalidParams,`Tool ${e.params.name} not found`);if(r.inputSchema){const s=await r.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new ps(sr.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);const n=s.data,i=r.callback;try{return await Promise.resolve(i(n,t))}catch(e){return{content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}}else{const e=r.callback;try{return await Promise.resolve(e(t))}catch(e){return{content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}}})),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(os.shape.method.value),this.server.setRequestHandler(os,(async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new ps(sr.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}})),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){const r=this._registeredPrompts[t.name];if(!r)throw new ps(sr.InvalidParams,`Prompt ${e.params.ref.name} not found`);if(!r.argsSchema)return nn;const s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof en))return nn;const n=s._def;return sn(await n.complete(e.params.argument.value))}async handleResourceCompletion(e,t){const r=Object.values(this._registeredResourceTemplates).find((e=>e.resourceTemplate.uriTemplate.toString()===t.uri));if(!r){if(this._registeredResources[t.uri])return nn;throw new ps(sr.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return nn;return sn(await s(e.params.argument.value))}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Sr.shape.method.value),this.server.assertCanSetRequestHandler(Cr.shape.method.value),this.server.assertCanSetRequestHandler(Or.shape.method.value),this.server.registerCapabilities({resources:{}}),this.server.setRequestHandler(Sr,(async(e,t)=>{const r=Object.entries(this._registeredResources).map((([e,t])=>({uri:e,name:t.name,...t.metadata}))),s=[];for(const e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;const r=await e.resourceTemplate.listCallback(t);for(const t of r.resources)s.push({...t,...e.metadata})}return{resources:[...r,...s]}})),this.server.setRequestHandler(Cr,(async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map((([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata})))}))),this.server.setRequestHandler(Or,(async(e,t)=>{const r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s)return s.readCallback(r,t);for(const e of Object.values(this._registeredResourceTemplates)){const s=e.resourceTemplate.uriTemplate.match(r.toString());if(s)return e.readCallback(r,s,t)}throw new ps(sr.InvalidParams,`Resource ${r} not found`)})),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Zr.shape.method.value),this.server.assertCanSetRequestHandler($r.shape.method.value),this.server.registerCapabilities({prompts:{}}),this.server.setRequestHandler(Zr,(()=>({prompts:Object.entries(this._registeredPrompts).map((([e,t])=>{return{name:e,description:t.description,arguments:t.argsSchema?(r=t.argsSchema,Object.entries(r.shape).map((([e,t])=>({name:e,description:t.description,required:!t.isOptional()})))):void 0};var r}))}))),this.server.setRequestHandler($r,(async(e,t)=>{const r=this._registeredPrompts[e.params.name];if(!r)throw new ps(sr.InvalidParams,`Prompt ${e.params.name} not found`);if(r.argsSchema){const s=await r.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new ps(sr.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);const n=s.data,i=r.callback;return await Promise.resolve(i(n,t))}{const e=r.callback;return await Promise.resolve(e(t))}})),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;"object"==typeof r[0]&&(s=r.shift());const n=r[0];if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);this._registeredResources[t]={name:e,metadata:s,readCallback:n}}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);this._registeredResourceTemplates[e]={resourceTemplate:t,metadata:s,readCallback:n}}this.setResourceRequestHandlers()}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,s;"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(s=t.shift());const n=t[0];this._registeredTools[e]={description:r,inputSchema:void 0===s?void 0:Ut.object(s),callback:n},this.setToolRequestHandlers()}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r,s;"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(s=t.shift());const n=t[0];this._registeredPrompts[e]={description:r,argsSchema:void 0===s?void 0:Ut.object(s),callback:n},this.setPromptRequestHandlers()}}({name:"Browser MCP",version:"1.0.0",transport:co});function uo(e=!0){for(const e of no)try{e.close()}catch(e){console.error("[BCM] Error closing browser connection:",e)}for(const e of io)try{e.close()}catch(e){console.error("[BCM] Error closing Cursor connection:",e)}oo.close(),ao.close((()=>{e&&process.exit(0)}))}lo.tool("executeJS","Execute JavaScript code in the current page context",{code:Ut.string().describe("Execute JavaScript code in the current page context")},(async e=>{const t=e?.code||"";return 0===no.length?{content:[{type:"text",text:"Error: No browser connections. Please inject MCP server in the browser first."}],isError:!0}:new Promise((e=>{const r=`req_${Date.now()}_${Math.floor(1e3*Math.random())}`,s=setTimeout((()=>{e({content:[{type:"text",text:"Error: Request timed out. Browser did not respond."}],isError:!0})}),5e3),n=t=>{try{const i=t.toString();if(i.startsWith("[Browser MC"))return;const a=JSON.parse(i);if(a.requestId===r)if(clearTimeout(s),no[0].removeListener("message",n),a.error)e({content:[{type:"text",text:`Error: ${a.error}`}],isError:!0});else{let t="string"==typeof a.result?a.result:String(a.result);t||(t="Execution successful, no return value"),e({content:[{type:"text",text:t}]})}}catch(e){console.error("[BCM] Message parsing error:",e,"Raw data:",t.toString().substring(0,100))}};no[0].on("message",n),no[0].send(JSON.stringify({type:"execute_js",requestId:r,code:t}))}))})),lo.tool("getPageHTML","Get HTML content of the current page",(async()=>0===no.length?{content:[{type:"text",text:"Error: No browser connections. Please inject MCP server in the browser first."}],isError:!0}:new Promise((e=>{const t=`req_${Date.now()}_${Math.floor(1e3*Math.random())}`,r=setTimeout((()=>{e({content:[{type:"text",text:"Error: Request timed out. Browser did not respond."}],isError:!0})}),5e3),s=n=>{try{const i=n.toString();if(i.startsWith("[Browser MC"))return;const a=JSON.parse(i);a.requestId===t&&(clearTimeout(r),no[0].removeListener("message",s),a.error?e({content:[{type:"text",text:`Error: ${a.error}`}],isError:!0}):e({content:[{type:"text",text:a.html}]}))}catch(e){console.error("[BCM] Message parsing error:",e,"Raw data:",n.toString().substring(0,100))}};no[0].on("message",s),no[0].send(JSON.stringify({type:"get_page_html",requestId:t}))})))),lo.tool("getPageTitle","Get title of the current page",(async()=>0===no.length?{content:[{type:"text",text:"Error: No browser connections. Please inject MCP server in the browser first."}],isError:!0}:new Promise((e=>{const t=`req_${Date.now()}_${Math.floor(1e3*Math.random())}`,r=setTimeout((()=>{e({content:[{type:"text",text:"Error: Request timed out. Browser did not respond."}],isError:!0})}),5e3),s=n=>{try{const i=n.toString();if(i.startsWith("[Browser MC"))return;const a=JSON.parse(i);a.requestId===t&&(clearTimeout(r),no[0].removeListener("message",s),a.error?e({content:[{type:"text",text:`Error: ${a.error}`}],isError:!0}):e({content:[{type:"text",text:a.title}]}))}catch(e){console.error("[BCM] Message parsing error:",e,"Raw data:",n.toString().substring(0,100))}};no[0].on("message",s),no[0].send(JSON.stringify({type:"get_page_title",requestId:t}))})))),lo.tool("getElements","Use CSS selector to get elements on the page",{selector:Ut.string().describe("CSS selector")},(async e=>{const t=e?.selector;return t?0===no.length?{content:[{type:"text",text:"Error: No browser connections. Please inject MCP server in the browser first."}],isError:!0}:new Promise((e=>{const r=`req_${Date.now()}_${Math.floor(1e3*Math.random())}`,s=setTimeout((()=>{e({content:[{type:"text",text:"Error: Request timed out. Browser did not respond."}],isError:!0})}),5e3),n=t=>{try{const i=t.toString();if(i.startsWith("[Browser MC"))return;const a=JSON.parse(i);if(a.requestId===r)if(clearTimeout(s),no[0].removeListener("message",n),a.error)e({content:[{type:"text",text:`Error: ${a.error}`}],isError:!0});else{const t=JSON.stringify(a.elements,null,2);e({content:[{type:"text",text:t}]})}}catch(e){console.error("[BCM] Message parsing error:",e,"Raw data:",t.toString().substring(0,100))}};no[0].on("message",n),no[0].send(JSON.stringify({type:"get_elements",requestId:r,selector:t}))})):{content:[{type:"text",text:"Error: Missing required parameter 'selector'"}],isError:!0}})),lo.tool("captureScreenshot","Capture screenshot of the current page (using html2canvas)",{selector:Ut.string().optional().describe("Optional CSS selector, for capturing specific elements")},(async e=>{const s=e?.selector||"body";return 0===no.length?{content:[{type:"text",text:"Error: No browser connections. Please inject MCP server in the browser first."}],isError:!0}:new Promise((e=>{const i=`req_${Date.now()}_${Math.floor(1e3*Math.random())}`,o=setTimeout((()=>{e({content:[{type:"text",text:"Error: Request timed out. Browser did not respond."}],isError:!0})}),15e3),c=s=>{try{const d=s.toString();if(d.startsWith("[Browser MC"))return;const l=JSON.parse(d);if(l.requestId===i)if(clearTimeout(o),no[0].removeListener("message",c),l.error)e({content:[{type:"text",text:`Error: ${l.error}`}],isError:!0});else if(l.imageDataUrl)try{const s=l.imageDataUrl.split(",");if(2!==s.length)throw new Error("Screenshot data format is incorrect");const i=s[1];if(!i)throw new Error("Screenshot data format is incorrect");const o=n(),c=a(o,"Downloads","mcp-screenshots");try{t(c,{recursive:!0})}catch(e){console.error("[BCM] Failed to create screenshots directory:",e)}const d=(new Date).toISOString().replace(/[:.]/g,"-"),u=a(c,`screenshot-${d}.png`);try{r(u,i,"base64"),e({content:[{type:"text",text:`Screenshot saved successfully to: ${u}\n\nNote: If the screenshot has white space issues, you can try specifying a specific element selector, such as: captureScreenshot({selector: ".main-content"})`}]})}catch(t){console.error("[BCM] Failed to save screenshot:",t),e({content:[{type:"text",text:`Failed to save screenshot: ${t instanceof Error?t.message:String(t)}`}],isError:!0})}}catch(t){const r=t instanceof Error?t.message:String(t);e({content:[{type:"text",text:`Error: Failed to process screenshot data - ${r}`}],isError:!0})}else e({content:[{type:"text",text:"Error: No screenshot data received"}],isError:!0})}catch(e){console.error("[BCM] Error parsing screenshot response:",e)}};no[0].on("message",c),console.log(`[BCM] Sending screenshot request, ID: ${i}, selector: ${s}`),no[0].send(JSON.stringify({type:"capture_screenshot",requestId:i,selector:s}))}))})),lo.tool("getPageURL","Get URL of the current page",(async()=>0===no.length?{content:[{type:"text",text:"Error: No browser connections. Please inject MCP server in the browser first."}],isError:!0}:new Promise((e=>{const t=`req_${Date.now()}_${Math.floor(1e3*Math.random())}`,r=setTimeout((()=>{e({content:[{type:"text",text:"Error: Request timed out. Browser did not respond."}],isError:!0})}),5e3),s=n=>{try{const i=n.toString();if(i.startsWith("[Browser MC"))return;const a=JSON.parse(i);a.requestId===t&&(clearTimeout(r),no[0].removeListener("message",s),a.error?e({content:[{type:"text",text:`Error: ${a.error}`}],isError:!0}):e({content:[{type:"text",text:a.url}]}))}catch(e){console.error("[BCM] Message parsing error:",e,"Raw data:",n.toString().substring(0,100))}};no[0].on("message",s),no[0].send(JSON.stringify({type:"get_page_url",requestId:t}))})))),lo.tool("clickElement","Click element on the page",{selector:Ut.string().describe("CSS selector of the element to click")},(async e=>{const t=e?.selector;return t?0===no.length?{content:[{type:"text",text:"Error: No browser connections. Please inject MCP server in the browser first."}],isError:!0}:new Promise((e=>{const r=`req_${Date.now()}_${Math.floor(1e3*Math.random())}`,s=setTimeout((()=>{e({content:[{type:"text",text:"Error: Request timed out. Browser did not respond."}],isError:!0})}),5e3),n=t=>{try{const i=t.toString();if(i.startsWith("[Browser MC"))return;const a=JSON.parse(i);a.requestId===r&&(clearTimeout(s),no[0].removeListener("message",n),a.error?e({content:[{type:"text",text:`Error: ${a.error}`}],isError:!0}):e({content:[{type:"text",text:a.message||"Element clicked successfully"}]}))}catch(e){console.error("[BCM] Message parsing error:",e,"Raw data:",t.toString().substring(0,100))}};no[0].on("message",n),no[0].send(JSON.stringify({type:"click_element",requestId:r,selector:t}))})):{content:[{type:"text",text:"Error: Missing required parameter 'selector'"}],isError:!0}})),lo.tool("inputText","Enter text into input field",{selector:Ut.string().describe("CSS selector of the input field"),text:Ut.string().describe("Text to enter")},(async e=>{const t=e?.selector,r=e?.text;return t&&void 0!==r?0===no.length?{content:[{type:"text",text:"Error: No browser connections. Please inject MCP server in the browser first."}],isError:!0}:new Promise((e=>{const s=`req_${Date.now()}_${Math.floor(1e3*Math.random())}`,n=setTimeout((()=>{e({content:[{type:"text",text:"Error: Request timed out. Browser did not respond."}],isError:!0})}),5e3),i=t=>{try{const r=t.toString();if(r.startsWith("[Browser MC"))return;const a=JSON.parse(r);a.requestId===s&&(clearTimeout(n),no[0].removeListener("message",i),a.error?e({content:[{type:"text",text:`Error: ${a.error}`}],isError:!0}):e({content:[{type:"text",text:a.message||"Text entered successfully"}]}))}catch(e){console.error("[BCM] Message parsing error:",e,"Raw data:",t.toString().substring(0,100))}};no[0].on("message",i),no[0].send(JSON.stringify({type:"input_text",requestId:s,selector:t,text:r}))})):{content:[{type:"text",text:"Error: Missing required parameters 'selector' or 'text'"}],isError:!0}})),process.on("SIGINT",(()=>{uo(!0)})),process.on("SIGTERM",(()=>{uo(!0)})),process.on("uncaughtException",(e=>{console.error("[BCM] Uncaught exception:",e),uo(!0)})),process.on("unhandledRejection",(e=>{console.error("[BCM] Unhandled Promise rejection:",e)})),ao.listen(so,(()=>{console.log(`[BCM] Server started, listening on port ${so}`)})),lo.connect(co).catch((e=>{console.error("[BCM] MCP server initialization failed:",e),uo(!0)}));
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{promises as t,mkdirSync as r,writeFileSync as s}from"node:fs";import{createServer as n}from"node:http";import{homedir as i}from"node:os";import{dirname as a,join as o}from"node:path";import{fileURLToPath as c}from"node:url";import d from"node:process";import l from"events";import u from"https";import h from"http";import p from"net";import f from"tls";import m from"crypto";import _ from"stream";import g from"url";import y from"zlib";import v from"buffer";var b,w;!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),s={};for(const e of r)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(b||(b={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(w||(w={}));const k=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),x=e=>{switch(typeof e){case"undefined":return k.undefined;case"string":return k.string;case"number":return isNaN(e)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(e)?k.array:null===e?k.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?k.promise:"undefined"!=typeof Map&&e instanceof Map?k.map:"undefined"!=typeof Set&&e instanceof Set?k.set:"undefined"!=typeof Date&&e instanceof Date?k.date:k.object;default:return k.unknown}},S=b.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class 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]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,s=0;for(;s<n.path.length;){const r=n.path[s];s===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof E))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}E.create=e=>new E(e);const T=(e,t)=>{let r;switch(e.code){case S.invalid_type:r=e.received===k.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case S.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,b.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:r=`Unrecognized key(s) in object: ${b.joinValues(e.keys,", ")}`;break;case S.invalid_union:r="Invalid input";break;case S.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${b.joinValues(e.options)}`;break;case S.invalid_enum_value:r=`Invalid enum value. Expected ${b.joinValues(e.options)}, received '${e.received}'`;break;case S.invalid_arguments:r="Invalid function arguments";break;case S.invalid_return_type:r="Invalid function return type";break;case S.invalid_date:r="Invalid date";break;case S.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:b.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case S.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`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 S.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case S.custom:r="Invalid input";break;case S.invalid_intersection_types:r="Intersection results could not be merged";break;case S.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case S.not_finite:r="Number must be finite";break;default:r=t.defaultError,b.assertNever(e)}return{message:r}};let C=T;function O(){return C}const P=e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,i=[...r,...n.path||[]],a={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const c=s.filter((e=>!!e)).slice().reverse();for(const e of c)o=e(a,{data:t,defaultError:o}).message;return{...n,path:i,message:o}};function N(e,t){const r=O(),s=P({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===T?void 0:T].filter((e=>!!e))});e.common.issues.push(s)}class j{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return R;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,s=await e.value;r.push({key:t,value:s})}return j.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return R;if("aborted"===n.status)return R;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const R=Object.freeze({status:"aborted"}),A=e=>({status:"dirty",value:e}),I=e=>({status:"valid",value:e}),Z=e=>"aborted"===e.status,L=e=>"dirty"===e.status,M=e=>"valid"===e.status,$=e=>"undefined"!=typeof Promise&&e instanceof Promise;function B(e,t,r,s){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function U(e,t,r,s,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var F,D,q;"function"==typeof SuppressedError&&SuppressedError,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(F||(F={}));class z{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const H=(e,t)=>{if(M(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new E(e.common.issues);return this._error=t,this._error}}};function W(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{var i,a;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:n.defaultError}:void 0===n.data?{message:null!==(i=null!=o?o:s)&&void 0!==i?i:n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:null!==(a=null!=o?o:r)&&void 0!==a?a:n.defaultError}},description:n}}class V{get description(){return this._def.description}_getType(e){return x(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:x(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new j,ctx:{common:e.parent.common,data:e.data,parsedType:x(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if($(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const s={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)},n=this._parseSync({data:e,path:s.path,parent:s});return H(s,n)}"~validate"(e){var t,r;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:s});return M(t)?{value:t.value}:{issues:s.common.issues}}catch(e){(null===(r=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then((e=>M(e)?{value:e.value}:{issues:s.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await($(s)?s:Promise.resolve(s));return H(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,s)=>{const n=e(t),i=()=>s.addIssue({code:S.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(i(),!1))):!!n||(i(),!1)}))}refinement(e,t){return this._refinement(((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1)))}_refinement(e){return new Ve({schema:this,typeName:at.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 Ge.create(this,this._def)}nullable(){return Ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Oe.create(this)}promise(){return We.create(this,this._def)}or(e){return je.create([this,e],this._def)}and(e){return Ze.create(this,e,this._def)}transform(e){return new Ve({...W(this._def),schema:this,typeName:at.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Je({...W(this._def),innerType:this,defaultValue:t,typeName:at.ZodDefault})}brand(){return new et({typeName:at.ZodBranded,type:this,...W(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ye({...W(this._def),innerType:this,catchValue:t,typeName:at.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return tt.create(this,e)}readonly(){return rt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const G=/^c[^\s-]{8,}$/i,K=/^[0-9a-z]+$/,J=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Y=/^[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,X=/^[a-z0-9_-]{21}$/i,Q=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ee=/^[-+]?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)?)??$/,te=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let re;const se=/^(?:(?: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])$/,ne=/^(?:(?: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])$/,ie=/^(([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]))$/,ae=/^(([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])$/,oe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ce=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,de="((\\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])))",le=new RegExp(`^${de}$`);function ue(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function he(e){let t=`${de}T${ue(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function pe(e,t){if(!Q.test(e))return!1;try{const[r]=e.split("."),s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return"object"==typeof n&&null!==n&&(!(!n.typ||!n.alg)&&(!t||n.alg===t))}catch(e){return!1}}function fe(e,t){return!("v4"!==t&&t||!ne.test(e))||!("v6"!==t&&t||!ae.test(e))}class me extends V{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==k.string){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.string,received:t.parsedType}),R}const t=new j;let r;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),N(r,{code:S.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),N(r,{code:S.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const s=e.data.length>i.value,n=e.data.length<i.value;(s||n)&&(r=this._getOrReturnCtx(e,r),s?N(r,{code:S.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&N(r,{code:S.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)te.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"email",code:S.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)re||(re=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),re.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"emoji",code:S.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)Y.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"uuid",code:S.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)X.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"nanoid",code:S.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)G.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"cuid",code:S.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)K.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"cuid2",code:S.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)J.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"ulid",code:S.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch(s){r=this._getOrReturnCtx(e,r),N(r,{validation:"url",code:S.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"regex",code:S.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),N(r,{code:S.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),N(r,{code:S.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),N(r,{code:S.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){he(i).test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{code:S.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){le.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{code:S.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${ue(i)}$`).test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{code:S.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?ee.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"duration",code:S.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(s=e.data,("v4"!==(n=i.version)&&n||!se.test(s))&&("v6"!==n&&n||!ie.test(s))&&(r=this._getOrReturnCtx(e,r),N(r,{validation:"ip",code:S.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?pe(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"jwt",code:S.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?fe(e.data,i.version)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"cidr",code:S.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?oe.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"base64",code:S.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?ce.test(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{validation:"base64url",code:S.invalid_string,message:i.message}),t.dirty()):b.assertNever(i);var s,n;return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:S.invalid_string,...F.errToObj(r)})}_addCheck(e){return new me({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...F.errToObj(e)})}url(e){return this._addCheck({kind:"url",...F.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...F.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...F.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...F.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...F.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...F.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...F.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...F.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...F.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...F.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...F.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...F.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...F.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...F.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...F.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...F.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...F.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...F.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...F.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...F.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...F.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...F.errToObj(t)})}nonempty(e){return this.min(1,F.errToObj(e))}trim(){return new me({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new me({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new me({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function _e(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=r>s?r:s;return parseInt(e.toFixed(n).replace(".",""))%parseInt(t.toFixed(n).replace(".",""))/Math.pow(10,n)}me.create=e=>{var t;return new me({checks:[],typeName:at.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...W(e)})};class ge extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==k.number){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.number,received:t.parsedType}),R}let t;const r=new j;for(const s of this._def.checks)if("int"===s.kind)b.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),N(t,{code:S.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),N(t,{code:S.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),N(t,{code:S.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==_e(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),N(t,{code:S.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),N(t,{code:S.not_finite,message:s.message}),r.dirty()):b.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,F.toString(t))}gt(e,t){return this.setLimit("min",e,!1,F.toString(t))}lte(e,t){return this.setLimit("max",e,!0,F.toString(t))}lt(e,t){return this.setLimit("max",e,!1,F.toString(t))}setLimit(e,t,r,s){return new ge({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:F.toString(s)}]})}_addCheck(e){return new ge({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:F.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:F.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:F.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:F.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:F.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&b.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ge.create=e=>new ge({checks:[],typeName:at.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...W(e)});class ye extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(t){return this._getInvalidInput(e)}if(this._getType(e)!==k.bigint)return this._getInvalidInput(e);let t;const r=new j;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),N(t,{code:S.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),N(t,{code:S.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),N(t,{code:S.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):b.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.bigint,received:t.parsedType}),R}gte(e,t){return this.setLimit("min",e,!0,F.toString(t))}gt(e,t){return this.setLimit("min",e,!1,F.toString(t))}lte(e,t){return this.setLimit("max",e,!0,F.toString(t))}lt(e,t){return this.setLimit("max",e,!1,F.toString(t))}setLimit(e,t,r,s){return new ye({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:F.toString(s)}]})}_addCheck(e){return new ye({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:F.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ye.create=e=>{var t;return new ye({checks:[],typeName:at.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...W(e)})};class ve extends V{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==k.boolean){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.boolean,received:t.parsedType}),R}return I(e.data)}}ve.create=e=>new ve({typeName:at.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...W(e)});class be extends V{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==k.date){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.date,received:t.parsedType}),R}if(isNaN(e.data.getTime())){return N(this._getOrReturnCtx(e),{code:S.invalid_date}),R}const t=new j;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),N(r,{code:S.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),N(r,{code:S.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):b.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new be({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:F.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:F.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}be.create=e=>new be({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:at.ZodDate,...W(e)});class we extends V{_parse(e){if(this._getType(e)!==k.symbol){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.symbol,received:t.parsedType}),R}return I(e.data)}}we.create=e=>new we({typeName:at.ZodSymbol,...W(e)});class ke extends V{_parse(e){if(this._getType(e)!==k.undefined){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.undefined,received:t.parsedType}),R}return I(e.data)}}ke.create=e=>new ke({typeName:at.ZodUndefined,...W(e)});class xe extends V{_parse(e){if(this._getType(e)!==k.null){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.null,received:t.parsedType}),R}return I(e.data)}}xe.create=e=>new xe({typeName:at.ZodNull,...W(e)});class Se extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return I(e.data)}}Se.create=e=>new Se({typeName:at.ZodAny,...W(e)});class Ee extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return I(e.data)}}Ee.create=e=>new Ee({typeName:at.ZodUnknown,...W(e)});class Te extends V{_parse(e){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.never,received:t.parsedType}),R}}Te.create=e=>new Te({typeName:at.ZodNever,...W(e)});class Ce extends V{_parse(e){if(this._getType(e)!==k.undefined){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.void,received:t.parsedType}),R}return I(e.data)}}Ce.create=e=>new Ce({typeName:at.ZodVoid,...W(e)});class Oe extends V{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==k.array)return N(t,{code:S.invalid_type,expected:k.array,received:t.parsedType}),R;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(N(t,{code:e?S.too_big:S.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(N(t,{code:S.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(N(t,{code:S.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>s.type._parseAsync(new z(t,e,t.path,r))))).then((e=>j.mergeArray(r,e)));const n=[...t.data].map(((e,r)=>s.type._parseSync(new z(t,e,t.path,r))));return j.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Oe({...this._def,minLength:{value:e,message:F.toString(t)}})}max(e,t){return new Oe({...this._def,maxLength:{value:e,message:F.toString(t)}})}length(e,t){return new Oe({...this._def,exactLength:{value:e,message:F.toString(t)}})}nonempty(e){return this.min(1,e)}}function Pe(e){if(e instanceof Ne){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Ge.create(Pe(s))}return new Ne({...e._def,shape:()=>t})}return e instanceof Oe?new Oe({...e._def,type:Pe(e.element)}):e instanceof Ge?Ge.create(Pe(e.unwrap())):e instanceof Ke?Ke.create(Pe(e.unwrap())):e instanceof Le?Le.create(e.items.map((e=>Pe(e)))):e}Oe.create=(e,t)=>new Oe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:at.ZodArray,...W(t)});class Ne extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=b.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==k.object){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.object,received:t.parsedType}),R}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Te&&"strip"===this._def.unknownKeys))for(const e in r.data)n.includes(e)||i.push(e);const a=[];for(const e of n){const t=s[e],n=r.data[e];a.push({key:{status:"valid",value:e},value:t._parse(new z(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof Te){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)a.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(N(r,{code:S.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=r.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new z(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of a){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e})).then((e=>j.mergeObjectSync(t,e))):j.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return F.errToObj,new Ne({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var s,n,i,a;const o=null!==(i=null===(n=(s=this._def).errorMap)||void 0===n?void 0:n.call(s,t,r).message)&&void 0!==i?i:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(a=F.errToObj(e).message)&&void 0!==a?a:o}:{message:o}}}:{}})}strip(){return new Ne({...this._def,unknownKeys:"strip"})}passthrough(){return new Ne({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ne({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ne({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:at.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ne({...this._def,catchall:e})}pick(e){const t={};return b.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new Ne({...this._def,shape:()=>t})}omit(e){const t={};return b.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new Ne({...this._def,shape:()=>t})}deepPartial(){return Pe(this)}partial(e){const t={};return b.objectKeys(this.shape).forEach((r=>{const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()})),new Ne({...this._def,shape:()=>t})}required(e){const t={};return b.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Ge;)e=e._def.innerType;t[r]=e}})),new Ne({...this._def,shape:()=>t})}keyof(){return qe(b.objectKeys(this.shape))}}Ne.create=(e,t)=>new Ne({shape:()=>e,unknownKeys:"strip",catchall:Te.create(),typeName:at.ZodObject,...W(t)}),Ne.strictCreate=(e,t)=>new Ne({shape:()=>e,unknownKeys:"strict",catchall:Te.create(),typeName:at.ZodObject,...W(t)}),Ne.lazycreate=(e,t)=>new Ne({shape:e,unknownKeys:"strip",catchall:Te.create(),typeName:at.ZodObject,...W(t)});class je extends V{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map((e=>new E(e.ctx.common.issues)));return N(t,{code:S.invalid_union,unionErrors:r}),R}));{let e;const s=[];for(const n of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map((e=>new E(e)));return N(t,{code:S.invalid_union,unionErrors:n}),R}}get options(){return this._def.options}}je.create=(e,t)=>new je({options:e,typeName:at.ZodUnion,...W(t)});const Re=e=>e instanceof Fe?Re(e.schema):e instanceof Ve?Re(e.innerType()):e instanceof De?[e.value]:e instanceof ze?e.options:e instanceof He?b.objectValues(e.enum):e instanceof Je?Re(e._def.innerType):e instanceof ke?[void 0]:e instanceof xe?[null]:e instanceof Ge?[void 0,...Re(e.unwrap())]:e instanceof Ke?[null,...Re(e.unwrap())]:e instanceof et||e instanceof rt?Re(e.unwrap()):e instanceof Ye?Re(e._def.innerType):[];class Ae extends V{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==k.object)return N(t,{code:S.invalid_type,expected:k.object,received:t.parsedType}),R;const r=this.discriminator,s=t.data[r],n=this.optionsMap.get(s);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(N(t,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),R)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const s=new Map;for(const r of t){const t=Re(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const n of t){if(s.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);s.set(n,r)}}return new Ae({typeName:at.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...W(r)})}}function Ie(e,t){const r=x(e),s=x(t);if(e===t)return{valid:!0,data:e};if(r===k.object&&s===k.object){const r=b.objectKeys(t),s=b.objectKeys(e).filter((e=>-1!==r.indexOf(e))),n={...e,...t};for(const r of s){const s=Ie(e[r],t[r]);if(!s.valid)return{valid:!1};n[r]=s.data}return{valid:!0,data:n}}if(r===k.array&&s===k.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=Ie(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===k.date&&s===k.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Ze extends V{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(Z(e)||Z(s))return R;const n=Ie(e.value,s.value);return n.valid?((L(e)||L(s))&&t.dirty(),{status:t.value,value:n.data}):(N(r,{code:S.invalid_intersection_types}),R)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>s(e,t))):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Ze.create=(e,t,r)=>new Ze({left:e,right:t,typeName:at.ZodIntersection,...W(r)});class Le extends V{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.array)return N(r,{code:S.invalid_type,expected:k.array,received:r.parsedType}),R;if(r.data.length<this._def.items.length)return N(r,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;!this._def.rest&&r.data.length>this._def.items.length&&(N(r,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map(((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new z(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(s).then((e=>j.mergeArray(t,e))):j.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Le({...this._def,rest:e})}}Le.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Le({items:e,typeName:at.ZodTuple,rest:null,...W(t)})};class Me extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.object)return N(r,{code:S.invalid_type,expected:k.object,received:r.parsedType}),R;const s=[],n=this._def.keyType,i=this._def.valueType;for(const e in r.data)s.push({key:n._parse(new z(r,e,r.path,e)),value:i._parse(new z(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?j.mergeObjectAsync(t,s):j.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new Me(t instanceof V?{keyType:e,valueType:t,typeName:at.ZodRecord,...W(r)}:{keyType:me.create(),valueType:e,typeName:at.ZodRecord,...W(t)})}}class $e extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.map)return N(r,{code:S.invalid_type,expected:k.map,received:r.parsedType}),R;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map((([e,t],i)=>({key:s._parse(new z(r,e,r.path,[i,"key"])),value:n._parse(new z(r,t,r.path,[i,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of i){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return R;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of i){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return R;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}$e.create=(e,t,r)=>new $e({valueType:t,keyType:e,typeName:at.ZodMap,...W(r)});class Be extends V{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.set)return N(r,{code:S.invalid_type,expected:k.set,received:r.parsedType}),R;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(N(r,{code:S.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(N(r,{code:S.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const r=new Set;for(const s of e){if("aborted"===s.status)return R;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const a=[...r.data.values()].map(((e,t)=>n._parse(new z(r,e,r.path,t))));return r.common.async?Promise.all(a).then((e=>i(e))):i(a)}min(e,t){return new Be({...this._def,minSize:{value:e,message:F.toString(t)}})}max(e,t){return new Be({...this._def,maxSize:{value:e,message:F.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Be.create=(e,t)=>new Be({valueType:e,minSize:null,maxSize:null,typeName:at.ZodSet,...W(t)});class Ue extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==k.function)return N(t,{code:S.invalid_type,expected:k.function,received:t.parsedType}),R;function r(e,r){return P({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,O(),T].filter((e=>!!e)),issueData:{code:S.invalid_arguments,argumentsError:r}})}function s(e,r){return P({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,O(),T].filter((e=>!!e)),issueData:{code:S.invalid_return_type,returnTypeError:r}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof We){const e=this;return I((async function(...t){const a=new E([]),o=await e._def.args.parseAsync(t,n).catch((e=>{throw a.addIssue(r(t,e)),a})),c=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(c,n).catch((e=>{throw a.addIssue(s(c,e)),a}))}))}{const e=this;return I((function(...t){const a=e._def.args.safeParse(t,n);if(!a.success)throw new E([r(t,a.error)]);const o=Reflect.apply(i,this,a.data),c=e._def.returns.safeParse(o,n);if(!c.success)throw new E([s(o,c.error)]);return c.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ue({...this._def,args:Le.create(e).rest(Ee.create())})}returns(e){return new Ue({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new Ue({args:e||Le.create([]).rest(Ee.create()),returns:t||Ee.create(),typeName:at.ZodFunction,...W(r)})}}class Fe extends V{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Fe.create=(e,t)=>new Fe({getter:e,typeName:at.ZodLazy,...W(t)});class De extends V{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return N(t,{received:t.data,code:S.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:e.data}}get value(){return this._def.value}}function qe(e,t){return new ze({values:e,typeName:at.ZodEnum,...W(t)})}De.create=(e,t)=>new De({value:e,typeName:at.ZodLiteral,...W(t)});class ze extends V{constructor(){super(...arguments),D.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return N(t,{expected:b.joinValues(r),received:t.parsedType,code:S.invalid_type}),R}if(B(this,D)||U(this,D,new Set(this._def.values)),!B(this,D).has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return N(t,{received:t.data,code:S.invalid_enum_value,options:r}),R}return I(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ze.create(e,{...this._def,...t})}exclude(e,t=this._def){return ze.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}D=new WeakMap,ze.create=qe;class He extends V{constructor(){super(...arguments),q.set(this,void 0)}_parse(e){const t=b.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==k.string&&r.parsedType!==k.number){const e=b.objectValues(t);return N(r,{expected:b.joinValues(e),received:r.parsedType,code:S.invalid_type}),R}if(B(this,q)||U(this,q,new Set(b.getValidEnumValues(this._def.values))),!B(this,q).has(e.data)){const e=b.objectValues(t);return N(r,{received:r.data,code:S.invalid_enum_value,options:e}),R}return I(e.data)}get enum(){return this._def.values}}q=new WeakMap,He.create=(e,t)=>new He({values:e,typeName:at.ZodNativeEnum,...W(t)});class We extends V{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==k.promise&&!1===t.common.async)return N(t,{code:S.invalid_type,expected:k.promise,received:t.parsedType}),R;const r=t.parsedType===k.promise?t.data:Promise.resolve(t.data);return I(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}We.create=(e,t)=>new We({type:e,typeName:at.ZodPromise,...W(t)});class Ve extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===at.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:e=>{N(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){const e=s.transform(r.data,n);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return R;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?R:"dirty"===s.status||"dirty"===t.value?A(s.value):s}));{if("aborted"===t.value)return R;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?R:"dirty"===s.status||"dirty"===t.value?A(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,n);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===s.status?R:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?R:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!M(e))return e;const i=s.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>M(e)?Promise.resolve(s.transform(e.value,n)).then((e=>({status:t.value,value:e}))):e))}b.assertNever(s)}}Ve.create=(e,t,r)=>new Ve({schema:e,typeName:at.ZodEffects,effect:t,...W(r)}),Ve.createWithPreprocess=(e,t,r)=>new Ve({schema:t,effect:{type:"preprocess",transform:e},typeName:at.ZodEffects,...W(r)});class Ge extends V{_parse(e){return this._getType(e)===k.undefined?I(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ge.create=(e,t)=>new Ge({innerType:e,typeName:at.ZodOptional,...W(t)});class Ke extends V{_parse(e){return this._getType(e)===k.null?I(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ke.create=(e,t)=>new Ke({innerType:e,typeName:at.ZodNullable,...W(t)});class Je extends V{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===k.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Je.create=(e,t)=>new Je({innerType:e,typeName:at.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...W(t)});class Ye extends V{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return $(s)?s.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new E(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new E(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ye.create=(e,t)=>new Ye({innerType:e,typeName:at.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...W(t)});class Xe extends V{_parse(e){if(this._getType(e)!==k.nan){const t=this._getOrReturnCtx(e);return N(t,{code:S.invalid_type,expected:k.nan,received:t.parsedType}),R}return{status:"valid",value:e.data}}}Xe.create=e=>new Xe({typeName:at.ZodNaN,...W(e)});const Qe=Symbol("zod_brand");class et extends V{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class tt extends V{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?R:"dirty"===e.status?(t.dirty(),A(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?R:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new tt({in:e,out:t,typeName:at.ZodPipeline})}}class rt extends V{_parse(e){const t=this._def.innerType._parse(e),r=e=>(M(e)&&(e.value=Object.freeze(e.value)),e);return $(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function st(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function nt(e,t={},r){return e?Se.create().superRefine(((s,n)=>{var i,a;const o=e(s);if(o instanceof Promise)return o.then((e=>{var i,a;if(!e){const e=st(t,s),o=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;n.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=st(t,s),o=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;n.addIssue({code:"custom",...e,fatal:o})}})):Se.create()}rt.create=(e,t)=>new rt({innerType:e,typeName:at.ZodReadonly,...W(t)});const it={object:Ne.lazycreate};var at;!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"}(at||(at={}));const ot=me.create,ct=ge.create,dt=Xe.create,lt=ye.create,ut=ve.create,ht=be.create,pt=we.create,ft=ke.create,mt=xe.create,_t=Se.create,gt=Ee.create,yt=Te.create,vt=Ce.create,bt=Oe.create,wt=Ne.create,kt=Ne.strictCreate,xt=je.create,St=Ae.create,Et=Ze.create,Tt=Le.create,Ct=Me.create,Ot=$e.create,Pt=Be.create,Nt=Ue.create,jt=Fe.create,Rt=De.create,At=ze.create,It=He.create,Zt=We.create,Lt=Ve.create,Mt=Ge.create,$t=Ke.create,Bt=Ve.createWithPreprocess,Ut=tt.create,Ft={string:e=>me.create({...e,coerce:!0}),number:e=>ge.create({...e,coerce:!0}),boolean:e=>ve.create({...e,coerce:!0}),bigint:e=>ye.create({...e,coerce:!0}),date:e=>be.create({...e,coerce:!0})},Dt=R;var qt=Object.freeze({__proto__:null,defaultErrorMap:T,setErrorMap:function(e){C=e},getErrorMap:O,makeIssue:P,EMPTY_PATH:[],addIssueToContext:N,ParseStatus:j,INVALID:R,DIRTY:A,OK:I,isAborted:Z,isDirty:L,isValid:M,isAsync:$,get util(){return b},get objectUtil(){return w},ZodParsedType:k,getParsedType:x,ZodType:V,datetimeRegex:he,ZodString:me,ZodNumber:ge,ZodBigInt:ye,ZodBoolean:ve,ZodDate:be,ZodSymbol:we,ZodUndefined:ke,ZodNull:xe,ZodAny:Se,ZodUnknown:Ee,ZodNever:Te,ZodVoid:Ce,ZodArray:Oe,ZodObject:Ne,ZodUnion:je,ZodDiscriminatedUnion:Ae,ZodIntersection:Ze,ZodTuple:Le,ZodRecord:Me,ZodMap:$e,ZodSet:Be,ZodFunction:Ue,ZodLazy:Fe,ZodLiteral:De,ZodEnum:ze,ZodNativeEnum:He,ZodPromise:We,ZodEffects:Ve,ZodTransformer:Ve,ZodOptional:Ge,ZodNullable:Ke,ZodDefault:Je,ZodCatch:Ye,ZodNaN:Xe,BRAND:Qe,ZodBranded:et,ZodPipeline:tt,ZodReadonly:rt,custom:nt,Schema:V,ZodSchema:V,late:it,get ZodFirstPartyTypeKind(){return at},coerce:Ft,any:_t,array:bt,bigint:lt,boolean:ut,date:ht,discriminatedUnion:St,effect:Lt,enum:At,function:Nt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>nt((t=>t instanceof e),t),intersection:Et,lazy:jt,literal:Rt,map:Ot,nan:dt,nativeEnum:It,never:yt,null:mt,nullable:$t,number:ct,object:wt,oboolean:()=>ut().optional(),onumber:()=>ct().optional(),optional:Mt,ostring:()=>ot().optional(),pipeline:Ut,preprocess:Bt,promise:Zt,record:Ct,set:Pt,strictObject:kt,string:ot,symbol:pt,transformer:Lt,tuple:Tt,undefined:ft,union:xt,unknown:gt,void:vt,NEVER:Dt,ZodIssueCode:S,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:E});const zt="2024-11-05",Ht=[zt,"2024-10-07"],Wt="2.0",Vt=qt.union([qt.string(),qt.number().int()]),Gt=qt.string(),Kt=qt.object({_meta:qt.optional(qt.object({progressToken:qt.optional(Vt)}).passthrough())}).passthrough(),Jt=qt.object({method:qt.string(),params:qt.optional(Kt)}),Yt=qt.object({_meta:qt.optional(qt.object({}).passthrough())}).passthrough(),Xt=qt.object({method:qt.string(),params:qt.optional(Yt)}),Qt=qt.object({_meta:qt.optional(qt.object({}).passthrough())}).passthrough(),er=qt.union([qt.string(),qt.number().int()]),tr=qt.object({jsonrpc:qt.literal(Wt),id:er}).merge(Jt).strict(),rr=qt.object({jsonrpc:qt.literal(Wt)}).merge(Xt).strict(),sr=qt.object({jsonrpc:qt.literal(Wt),id:er,result:Qt}).strict();var nr;!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"}(nr||(nr={}));const ir=qt.object({jsonrpc:qt.literal(Wt),id:er,error:qt.object({code:qt.number().int(),message:qt.string(),data:qt.optional(qt.unknown())})}).strict(),ar=qt.union([tr,rr,sr,ir]),or=Qt.strict(),cr=Xt.extend({method:qt.literal("notifications/cancelled"),params:Yt.extend({requestId:er,reason:qt.string().optional()})}),dr=qt.object({name:qt.string(),version:qt.string()}).passthrough(),lr=qt.object({experimental:qt.optional(qt.object({}).passthrough()),sampling:qt.optional(qt.object({}).passthrough()),roots:qt.optional(qt.object({listChanged:qt.optional(qt.boolean())}).passthrough())}).passthrough(),ur=Jt.extend({method:qt.literal("initialize"),params:Kt.extend({protocolVersion:qt.string(),capabilities:lr,clientInfo:dr})}),hr=qt.object({experimental:qt.optional(qt.object({}).passthrough()),logging:qt.optional(qt.object({}).passthrough()),prompts:qt.optional(qt.object({listChanged:qt.optional(qt.boolean())}).passthrough()),resources:qt.optional(qt.object({subscribe:qt.optional(qt.boolean()),listChanged:qt.optional(qt.boolean())}).passthrough()),tools:qt.optional(qt.object({listChanged:qt.optional(qt.boolean())}).passthrough())}).passthrough(),pr=Qt.extend({protocolVersion:qt.string(),capabilities:hr,serverInfo:dr,instructions:qt.optional(qt.string())}),fr=Xt.extend({method:qt.literal("notifications/initialized")}),mr=Jt.extend({method:qt.literal("ping")}),_r=qt.object({progress:qt.number(),total:qt.optional(qt.number())}).passthrough(),gr=Xt.extend({method:qt.literal("notifications/progress"),params:Yt.merge(_r).extend({progressToken:Vt})}),yr=Jt.extend({params:Kt.extend({cursor:qt.optional(Gt)}).optional()}),vr=Qt.extend({nextCursor:qt.optional(Gt)}),br=qt.object({uri:qt.string(),mimeType:qt.optional(qt.string())}).passthrough(),wr=br.extend({text:qt.string()}),kr=br.extend({blob:qt.string().base64()}),xr=qt.object({uri:qt.string(),name:qt.string(),description:qt.optional(qt.string()),mimeType:qt.optional(qt.string())}).passthrough(),Sr=qt.object({uriTemplate:qt.string(),name:qt.string(),description:qt.optional(qt.string()),mimeType:qt.optional(qt.string())}).passthrough(),Er=yr.extend({method:qt.literal("resources/list")}),Tr=vr.extend({resources:qt.array(xr)}),Cr=yr.extend({method:qt.literal("resources/templates/list")}),Or=vr.extend({resourceTemplates:qt.array(Sr)}),Pr=Jt.extend({method:qt.literal("resources/read"),params:Kt.extend({uri:qt.string()})}),Nr=Qt.extend({contents:qt.array(qt.union([wr,kr]))}),jr=Xt.extend({method:qt.literal("notifications/resources/list_changed")}),Rr=Jt.extend({method:qt.literal("resources/subscribe"),params:Kt.extend({uri:qt.string()})}),Ar=Jt.extend({method:qt.literal("resources/unsubscribe"),params:Kt.extend({uri:qt.string()})}),Ir=Xt.extend({method:qt.literal("notifications/resources/updated"),params:Yt.extend({uri:qt.string()})}),Zr=qt.object({name:qt.string(),description:qt.optional(qt.string()),required:qt.optional(qt.boolean())}).passthrough(),Lr=qt.object({name:qt.string(),description:qt.optional(qt.string()),arguments:qt.optional(qt.array(Zr))}).passthrough(),Mr=yr.extend({method:qt.literal("prompts/list")}),$r=vr.extend({prompts:qt.array(Lr)}),Br=Jt.extend({method:qt.literal("prompts/get"),params:Kt.extend({name:qt.string(),arguments:qt.optional(qt.record(qt.string()))})}),Ur=qt.object({type:qt.literal("text"),text:qt.string()}).passthrough(),Fr=qt.object({type:qt.literal("image"),data:qt.string().base64(),mimeType:qt.string()}).passthrough(),Dr=qt.object({type:qt.literal("resource"),resource:qt.union([wr,kr])}).passthrough(),qr=qt.object({role:qt.enum(["user","assistant"]),content:qt.union([Ur,Fr,Dr])}).passthrough(),zr=Qt.extend({description:qt.optional(qt.string()),messages:qt.array(qr)}),Hr=Xt.extend({method:qt.literal("notifications/prompts/list_changed")}),Wr=qt.object({name:qt.string(),description:qt.optional(qt.string()),inputSchema:qt.object({type:qt.literal("object"),properties:qt.optional(qt.object({}).passthrough())}).passthrough()}).passthrough(),Vr=yr.extend({method:qt.literal("tools/list")}),Gr=vr.extend({tools:qt.array(Wr)}),Kr=Qt.extend({content:qt.array(qt.union([Ur,Fr,Dr])),isError:qt.boolean().default(!1).optional()});Kr.or(Qt.extend({toolResult:qt.unknown()}));const Jr=Jt.extend({method:qt.literal("tools/call"),params:Kt.extend({name:qt.string(),arguments:qt.optional(qt.record(qt.unknown()))})}),Yr=Xt.extend({method:qt.literal("notifications/tools/list_changed")}),Xr=qt.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Qr=Jt.extend({method:qt.literal("logging/setLevel"),params:Kt.extend({level:Xr})}),es=Xt.extend({method:qt.literal("notifications/message"),params:Yt.extend({level:Xr,logger:qt.optional(qt.string()),data:qt.unknown()})}),ts=qt.object({name:qt.string().optional()}).passthrough(),rs=qt.object({hints:qt.optional(qt.array(ts)),costPriority:qt.optional(qt.number().min(0).max(1)),speedPriority:qt.optional(qt.number().min(0).max(1)),intelligencePriority:qt.optional(qt.number().min(0).max(1))}).passthrough(),ss=qt.object({role:qt.enum(["user","assistant"]),content:qt.union([Ur,Fr])}).passthrough(),ns=Jt.extend({method:qt.literal("sampling/createMessage"),params:Kt.extend({messages:qt.array(ss),systemPrompt:qt.optional(qt.string()),includeContext:qt.optional(qt.enum(["none","thisServer","allServers"])),temperature:qt.optional(qt.number()),maxTokens:qt.number().int(),stopSequences:qt.optional(qt.array(qt.string())),metadata:qt.optional(qt.object({}).passthrough()),modelPreferences:qt.optional(rs)})}),is=Qt.extend({model:qt.string(),stopReason:qt.optional(qt.enum(["endTurn","stopSequence","maxTokens"]).or(qt.string())),role:qt.enum(["user","assistant"]),content:qt.discriminatedUnion("type",[Ur,Fr])}),as=qt.object({type:qt.literal("ref/resource"),uri:qt.string()}).passthrough(),os=qt.object({type:qt.literal("ref/prompt"),name:qt.string()}).passthrough(),cs=Jt.extend({method:qt.literal("completion/complete"),params:Kt.extend({ref:qt.union([os,as]),argument:qt.object({name:qt.string(),value:qt.string()}).passthrough()})}),ds=Qt.extend({completion:qt.object({values:qt.array(qt.string()).max(100),total:qt.optional(qt.number().int()),hasMore:qt.optional(qt.boolean())}).passthrough()}),ls=qt.object({uri:qt.string().startsWith("file://"),name:qt.optional(qt.string())}).passthrough(),us=Jt.extend({method:qt.literal("roots/list")}),hs=Qt.extend({roots:qt.array(ls)}),ps=Xt.extend({method:qt.literal("notifications/roots/list_changed")});qt.union([mr,ur,cs,Qr,Br,Mr,Er,Cr,Pr,Rr,Ar,Jr,Vr]),qt.union([cr,gr,fr,ps]),qt.union([or,is,hs]),qt.union([mr,ns,us]),qt.union([cr,gr,es,Ir,jr,Yr,Hr]),qt.union([or,pr,ds,zr,$r,Tr,Or,Nr,Kr,Gr]);class fs extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r}}class ms{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this.setNotificationHandler(cr,(e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)})),this.setNotificationHandler(gr,(e=>{this._onprogress(e)})),this.setRequestHandler(mr,(e=>({})))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=e=>{this._onerror(e)},this._transport.onmessage=e=>{"method"in e?"id"in e?this._onrequest(e):this._onnotification(e):this._onresponse(e)},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new fs(nr.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then((()=>r(e))).catch((e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`))))}_onrequest(e){var t,r;const s=null!==(t=this._requestHandlers.get(e.method))&&void 0!==t?t:this.fallbackRequestHandler;if(void 0===s)return void(null===(r=this._transport)||void 0===r||r.send({jsonrpc:"2.0",id:e.id,error:{code:nr.MethodNotFound,message:"Method not found"}}).catch((e=>this._onerror(new Error(`Failed to send an error response: ${e}`)))));const n=new AbortController;this._requestHandlerAbortControllers.set(e.id,n),Promise.resolve().then((()=>s(e,{signal:n.signal}))).then((t=>{var r;if(!n.signal.aborted)return null===(r=this._transport)||void 0===r?void 0:r.send({result:t,jsonrpc:"2.0",id:e.id})}),(t=>{var r,s;if(!n.signal.aborted)return null===(r=this._transport)||void 0===r?void 0:r.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:nr.InternalError,message:null!==(s=t.message)&&void 0!==s?s:"Internal error"}})})).catch((e=>this._onerror(new Error(`Failed to send response: ${e}`)))).finally((()=>{this._requestHandlerAbortControllers.delete(e.id)}))}_onprogress(e){const{progressToken:t,...r}=e.params,s=this._progressHandlers.get(Number(t));void 0!==s?s(r):this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`))}_onresponse(e){const t=e.id,r=this._responseHandlers.get(Number(t));if(void 0!==r)if(this._responseHandlers.delete(Number(t)),this._progressHandlers.delete(Number(t)),"result"in e)r(e);else{r(new fs(e.error.code,e.error.message,e.error.data))}else this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){return new Promise(((s,n)=>{var i,a,o,c;if(!this._transport)return void n(new Error("Not connected"));!0===(null===(i=this._options)||void 0===i?void 0:i.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(a=null==r?void 0:r.signal)||void 0===a||a.throwIfAborted();const d=this._requestMessageId++,l={...e,jsonrpc:"2.0",id:d};let u;(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(d,r.onprogress),l.params={...e.params,_meta:{progressToken:d}}),this._responseHandlers.set(d,(e=>{var i;if(void 0!==u&&clearTimeout(u),!(null===(i=null==r?void 0:r.signal)||void 0===i?void 0:i.aborted)){if(e instanceof Error)return n(e);try{const r=t.parse(e.result);s(r)}catch(e){n(e)}}}));const h=e=>{var t;this._responseHandlers.delete(d),this._progressHandlers.delete(d),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(e)}}).catch((e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)))),n(e)};null===(o=null==r?void 0:r.signal)||void 0===o||o.addEventListener("abort",(()=>{var e;void 0!==u&&clearTimeout(u),h(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)}));const p=null!==(c=null==r?void 0:r.timeout)&&void 0!==c?c:6e4;u=setTimeout((()=>h(new fs(nr.RequestTimeout,"Request timed out",{timeout:p}))),p),this._transport.send(l).catch((e=>{void 0!==u&&clearTimeout(u),n(e)}))}))}async notification(e){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const t={...e,jsonrpc:"2.0"};await this._transport.send(t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,((r,s)=>Promise.resolve(t(e.parse(r),s))))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,(r=>Promise.resolve(t(e.parse(r)))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}class _s extends ms{constructor(e,t){var r;super(t),this._serverInfo=e,this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._instructions=null==t?void 0:t.instructions,this.setRequestHandler(ur,(e=>this._oninitialize(e))),this.setNotificationHandler(fr,(()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)}))}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t,r;this._capabilities=(t=this._capabilities,r=e,Object.entries(r).reduce(((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e)),{...t}))}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(null===(t=this._clientCapabilities)||void 0===t?void 0:t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(null===(r=this._clientCapabilities)||void 0===r?void 0:r.roots))throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new 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 new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`)}}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ht.includes(t)?t:zt,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"},or)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},is,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},hs,t)}async sendLoggingMessage(e){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"})}}const gs=Symbol("Let zodToJsonSchema decide on which parser to use"),ys={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},vs=e=>{const t=(e=>({...ys,...e}))(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function bs(e,t,r,s){s?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function ws(e,t,r,s,n){e[t]=r,bs(e,t,s,n)}function ks(e,t){return Ks(e.type._def,t)}function xs(e,t,r){const s=r??t.dateStrategy;if(Array.isArray(s))return{anyOf:s.map(((r,s)=>xs(e,t,r)))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ss(e,t)}}const Ss=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const s of e.checks)switch(s.kind){case"min":ws(r,"minimum",s.value,s.message,t);break;case"max":ws(r,"maximum",s.value,s.message,t)}return r};let Es;const Ts=/^[cC][^\s-]{8,}$/,Cs=/^[0-9a-z]+$/,Os=/^[0-9A-HJKMNP-TV-Z]{26}$/,Ps=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Ns=()=>(void 0===Es&&(Es=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Es),js=/^(?:(?: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])$/,Rs=/^(([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])$/,As=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Is=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zs=/^[a-zA-Z0-9_-]{21}$/,Ls=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Ms(e,t){const r={type:"string"};if(e.checks)for(const s of e.checks)switch(s.kind){case"min":ws(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,s.value):s.value,s.message,t);break;case"max":ws(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,s.value):s.value,s.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Us(r,"email",s.message,t);break;case"format:idn-email":Us(r,"idn-email",s.message,t);break;case"pattern:zod":Fs(r,Ps,s.message,t)}break;case"url":Us(r,"uri",s.message,t);break;case"uuid":Us(r,"uuid",s.message,t);break;case"regex":Fs(r,s.regex,s.message,t);break;case"cuid":Fs(r,Ts,s.message,t);break;case"cuid2":Fs(r,Cs,s.message,t);break;case"startsWith":Fs(r,RegExp(`^${$s(s.value,t)}`),s.message,t);break;case"endsWith":Fs(r,RegExp(`${$s(s.value,t)}$`),s.message,t);break;case"datetime":Us(r,"date-time",s.message,t);break;case"date":Us(r,"date",s.message,t);break;case"time":Us(r,"time",s.message,t);break;case"duration":Us(r,"duration",s.message,t);break;case"length":ws(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,s.value):s.value,s.message,t),ws(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,s.value):s.value,s.message,t);break;case"includes":Fs(r,RegExp($s(s.value,t)),s.message,t);break;case"ip":"v6"!==s.version&&Us(r,"ipv4",s.message,t),"v4"!==s.version&&Us(r,"ipv6",s.message,t);break;case"base64url":Fs(r,Is,s.message,t);break;case"jwt":Fs(r,Ls,s.message,t);break;case"cidr":"v6"!==s.version&&Fs(r,js,s.message,t),"v4"!==s.version&&Fs(r,Rs,s.message,t);break;case"emoji":Fs(r,Ns(),s.message,t);break;case"ulid":Fs(r,Os,s.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Us(r,"binary",s.message,t);break;case"contentEncoding:base64":ws(r,"contentEncoding","base64",s.message,t);break;case"pattern:zod":Fs(r,As,s.message,t)}break;case"nanoid":Fs(r,Zs,s.message,t)}return r}function $s(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)Bs.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}const Bs=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Us(e,t,r,s){e.format||e.anyOf?.some((e=>e.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&s.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&s.errorMessages&&{errorMessage:{format:r}}})):ws(e,"format",t,r,s)}function Fs(e,t,r,s){e.pattern||e.allOf?.some((e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&s.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:Ds(t,s),...r&&s.errorMessages&&{errorMessage:{pattern:r}}})):ws(e,"pattern",Ds(t,s),r,s)}function Ds(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),s=e.flags.includes("m"),n=e.flags.includes("s"),i=r?e.source.toLowerCase():e.source;let a="",o=!1,c=!1,d=!1;for(let e=0;e<i.length;e++)if(o)a+=i[e],o=!1;else{if(r)if(c){if(i[e].match(/[a-z]/)){d?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),d=!1):"-"===i[e+1]&&i[e+2]?.match(/[a-z]/)?(a+=i[e],d=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}if(s){if("^"===i[e]){a+="(^|(?<=[\r\n]))";continue}if("$"===i[e]){a+="($|(?=[\r\n]))";continue}}n&&"."===i[e]?a+=c?`${i[e]}\r\n`:`[${i[e]}\r\n]`:(a+=i[e],"\\"===i[e]?o=!0:c&&"]"===i[e]?c=!1:c||"["!==i[e]||(c=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function qs(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===at.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce(((r,s)=>({...r,[s]:Ks(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??{}})),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Ks(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===at.ZodString&&e.keyType._def.checks?.length){const{type:s,...n}=Ms(e.keyType._def,t);return{...r,propertyNames:n}}if(e.keyType?._def.typeName===at.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===at.ZodBranded&&e.keyType._def.type._def.typeName===at.ZodString&&e.keyType._def.type._def.checks?.length){const{type:s,...n}=ks(e.keyType._def,t);return{...r,propertyNames:n}}return r}const zs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const Hs=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>Ks(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return r.length?{anyOf:r}:void 0};function Ws(e,t){const r="openAi"===t.target,s={type:"object",properties:{}},n=[],i=e.shape();for(const e in i){let a=i[e];if(void 0===a||void 0===a._def)continue;let o=Vs(a);o&&r&&(a instanceof Ge&&(a=a._def.innerType),a.isNullable()||(a=a.nullable()),o=!1);const c=Ks(a._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(s.properties[e]=c,o||n.push(e))}n.length&&(s.required=n);const a=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return Ks(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==a&&(s.additionalProperties=a),s}function Vs(e){try{return e.isOptional()}catch{return!0}}const Gs=(e,t,r)=>{switch(t){case at.ZodString:return Ms(e,r);case at.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const s of e.checks)switch(s.kind){case"int":r.type="integer",bs(r,"type",s.message,t);break;case"min":"jsonSchema7"===t.target?s.inclusive?ws(r,"minimum",s.value,s.message,t):ws(r,"exclusiveMinimum",s.value,s.message,t):(s.inclusive||(r.exclusiveMinimum=!0),ws(r,"minimum",s.value,s.message,t));break;case"max":"jsonSchema7"===t.target?s.inclusive?ws(r,"maximum",s.value,s.message,t):ws(r,"exclusiveMaximum",s.value,s.message,t):(s.inclusive||(r.exclusiveMaximum=!0),ws(r,"maximum",s.value,s.message,t));break;case"multipleOf":ws(r,"multipleOf",s.value,s.message,t)}return r}(e,r);case at.ZodObject:return Ws(e,r);case at.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const s of e.checks)switch(s.kind){case"min":"jsonSchema7"===t.target?s.inclusive?ws(r,"minimum",s.value,s.message,t):ws(r,"exclusiveMinimum",s.value,s.message,t):(s.inclusive||(r.exclusiveMinimum=!0),ws(r,"minimum",s.value,s.message,t));break;case"max":"jsonSchema7"===t.target?s.inclusive?ws(r,"maximum",s.value,s.message,t):ws(r,"exclusiveMaximum",s.value,s.message,t):(s.inclusive||(r.exclusiveMaximum=!0),ws(r,"maximum",s.value,s.message,t));break;case"multipleOf":ws(r,"multipleOf",s.value,s.message,t)}return r}(e,r);case at.ZodBoolean:return{type:"boolean"};case at.ZodDate:return xs(e,r);case at.ZodUndefined:return{not:{}};case at.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case at.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==at.ZodAny&&(r.items=Ks(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ws(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ws(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ws(r,"minItems",e.exactLength.value,e.exactLength.message,t),ws(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case at.ZodUnion:case at.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return Hs(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e._def.typeName in zs&&(!e._def.checks||!e._def.checks.length)))){const e=r.reduce(((e,t)=>{const r=zs[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e}),[]);return{type:e.length>1?e:e[0]}}if(r.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=r.reduce(((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===r.length){const t=e.filter(((e,t,r)=>r.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:r.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(r.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:r.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return Hs(e,t)}(e,r);case at.ZodIntersection:return function(e,t){const r=[Ks(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ks(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let s="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const n=[];return r.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...s}=e;t=s}else s=void 0;n.push(t)}else n.push(...e.allOf),void 0===e.unevaluatedProperties&&(s=void 0);var t})),n.length?{allOf:n,...s}:void 0}(e,r);case at.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>Ks(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:Ks(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>Ks(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,r);case at.ZodRecord:return qs(e,r);case at.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case at.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case at.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),s=Array.from(new Set(r.map((e=>typeof e))));return{type:1===s.length?"string"===s[0]?"string":"number":["string","number"],enum:r}}(e);case at.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:zs[e.innerType._def.typeName],nullable:!0}:{type:[zs[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=Ks(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=Ks(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case at.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ks(e.innerType._def,t);const r=Ks(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case at.ZodMap:return function(e,t){return"record"===t.mapStrategy?qs(e,t):{type:"array",maxItems:125,items:{type:"array",items:[Ks(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},Ks(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case at.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:Ks(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ws(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ws(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case at.ZodLazy:return()=>e.getter()._def;case at.ZodPromise:return function(e,t){return Ks(e.type._def,t)}(e,r);case at.ZodNaN:case at.ZodNever:return{not:{}};case at.ZodEffects:return function(e,t){return"input"===t.effectStrategy?Ks(e.schema._def,t):{}}(e,r);case at.ZodAny:case at.ZodUnknown:return{};case at.ZodDefault:return function(e,t){return{...Ks(e.innerType._def,t),default:e.defaultValue()}}(e,r);case at.ZodBranded:return ks(e,r);case at.ZodReadonly:case at.ZodCatch:return((e,t)=>Ks(e.innerType._def,t))(e,r);case at.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return Ks(e.in._def,t);if("output"===t.pipeStrategy)return Ks(e.out._def,t);const r=Ks(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,Ks(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}})(e,r);case at.ZodFunction:case at.ZodVoid:case at.ZodSymbol:default:return}};function Ks(e,t,r=!1){const s=t.seen.get(e);if(t.override){const n=t.override?.(e,t,s,r);if(n!==gs)return n}if(s&&!r){const e=Js(s,t);if(void 0!==e)return e}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const i=Gs(e,e.typeName,t),a="function"==typeof i?Ks(i(),t):i;if(a&&Xs(e,t,a),t.postProcess){const r=t.postProcess(a,e,t);return n.jsonSchema=a,r}return n.jsonSchema=a,a}const Js=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ys(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every(((e,r)=>t.currentPath[r]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):"seen"===t.$refStrategy?{}:void 0}},Ys=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},Xs=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),Qs=(e,t)=>{const r=vs(t),s=void 0,n=t?.name,i=Ks(e._def,r,!1)??{},a=void 0===n?i:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...s,[n]:i}};return"jsonSchema7"===r.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};var en;!function(e){e.Completable="McpCompletable"}(en||(en={}));class tn extends V{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}function rn(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{var i,a;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:n.defaultError}:void 0===n.data?{message:null!==(i=null!=o?o:s)&&void 0!==i?i:n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:null!==(a=null!=o?o:r)&&void 0!==a?a:n.defaultError}},description:n}}tn.create=(e,t)=>new tn({type:e,typeName:en.Completable,complete:t.complete,...rn(t)});const sn={type:"object"};function nn(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const an={completion:{values:[],hasMore:!1}};class on{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e);return this._buffer=this._buffer.subarray(e+1),function(e){return ar.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}function cn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dn={exports:{}};const ln=["nodebuffer","arraybuffer","fragments"],un="undefined"!=typeof Blob;un&&ln.push("blob");var hn={BINARY_TYPES:ln,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:un,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:pn}=hn,fn=Buffer[Symbol.species];function mn(e,t,r,s,n){for(let i=0;i<n;i++)r[s+i]=e[i]^t[3&i]}function _n(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(dn.exports={concat:function(e,t){if(0===e.length)return pn;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let s=0;for(let t=0;t<e.length;t++){const n=e[t];r.set(n,s),s+=n.length}return s<t?new fn(r.buffer,r.byteOffset,s):r},mask:mn,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new fn(t):ArrayBuffer.isView(t)?r=new fn(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:_n},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");dn.exports.mask=function(t,r,s,n,i){i<48?mn(t,r,s,n,i):e.mask(t,r,s,n,i)},dn.exports.unmask=function(t,r){t.length<32?_n(t,r):e.unmask(t,r)}}catch(e){}var gn=dn.exports;const yn=Symbol("kDone"),vn=Symbol("kRun");const bn=y,wn=gn,kn=class{constructor(e){this[yn]=()=>{this.pending--,this[vn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[vn]()}[vn](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[yn])}}},{kStatusCode:xn}=hn,Sn=Buffer[Symbol.species],En=Buffer.from([0,0,255,255]),Tn=Symbol("permessage-deflate"),Cn=Symbol("total-length"),On=Symbol("callback"),Pn=Symbol("buffers"),Nn=Symbol("error");let jn;var Rn=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!jn){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;jn=new kn(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[On];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){jn.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){jn.add((s=>{this._compress(e,t,((e,t)=>{s(),r(e,t)}))}))}_decompress(e,t,r){const s=this._isServer?"client":"server";if(!this._inflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?bn.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=bn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Tn]=this,this._inflate[Cn]=0,this._inflate[Pn]=[],this._inflate.on("error",Zn),this._inflate.on("data",In)}this._inflate[On]=r,this._inflate.write(e),t&&this._inflate.write(En),this._inflate.flush((()=>{const e=this._inflate[Nn];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=wn.concat(this._inflate[Pn],this._inflate[Cn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Cn]=0,this._inflate[Pn]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,n)}))}_compress(e,t,r){const s=this._isServer?"server":"client";if(!this._deflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?bn.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=bn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Cn]=0,this._deflate[Pn]=[],this._deflate.on("data",An)}this._deflate[On]=r,this._deflate.write(e),this._deflate.flush(bn.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=wn.concat(this._deflate[Pn],this._deflate[Cn]);t&&(e=new Sn(e.buffer,e.byteOffset,e.length-4)),this._deflate[On]=null,this._deflate[Cn]=0,this._deflate[Pn]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function An(e){this[Pn].push(e),this[Cn]+=e.length}function In(e){this[Cn]+=e.length,this[Tn]._maxPayload<1||this[Cn]<=this[Tn]._maxPayload?this[Pn].push(e):(this[Nn]=new RangeError("Max payload size exceeded"),this[Nn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Nn][xn]=1009,this.removeListener("data",In),this.reset())}function Zn(e){this[Tn]._inflate=null,this[Nn]?this[On](this[Nn]):(e[xn]=1007,this[On](e))}var Ln={exports:{}};const{isUtf8:Mn}=v,{hasBlob:$n}=hn;function Bn(e){const t=e.length;let r=0;for(;r<t;)if(128&e[r])if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}else r++;return!0}if(Ln.exports={isBlob:function(e){return $n&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:Bn,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},Mn)Ln.exports.isValidUTF8=function(e){return e.length<24?Bn(e):Mn(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Ln.exports.isValidUTF8=function(t){return t.length<32?Bn(t):e(t)}}catch(e){}var Un=Ln.exports;const{Writable:Fn}=_,Dn=Rn,{BINARY_TYPES:qn,EMPTY_BUFFER:zn,kStatusCode:Hn,kWebSocket:Wn}=hn,{concat:Vn,toArrayBuffer:Gn,unmask:Kn}=gn,{isValidStatusCode:Jn,isValidUTF8:Yn}=Un,Xn=Buffer[Symbol.species];var Qn=class extends Fn{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||qn[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Wn]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Xn(t.buffer,t.byteOffset+e,t.length-e),new Xn(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Xn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const r=!(64&~t[0]);if(!r||this._extensions[Dn.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=r}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else{e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}else this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}else this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=zn;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&Kn(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[Dn.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let s;s="nodebuffer"===this._binaryType?Vn(r,t):"arraybuffer"===this._binaryType?Gn(Vn(r,t)):"blob"===this._binaryType?new Blob(r):r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",s,!0),this._state=0,this.startLoop(e)})))}else{const s=Vn(r,t);if(!this._skipUTF8Validation&&!Yn(s)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",s,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,zn),this.end();else{const r=e.readUInt16BE(0);if(!Jn(r)){const e=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const s=new Xn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Yn(s)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=0}}createError(e,t,r,s,n){this._loop=!1,this._errored=!0;const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=n,i[Hn]=s,i}};const{Duplex:ei}=_,{randomFillSync:ti}=m,ri=Rn,{EMPTY_BUFFER:si,kWebSocket:ni,NOOP:ii}=hn,{isBlob:ai,isValidStatusCode:oi}=Un,{mask:ci,toBuffer:di}=gn,li=Symbol("kByteLength"),ui=Buffer.alloc(4),hi=8192;let pi,fi=hi;var mi=class e{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=ii,this[ni]=void 0}static frame(e,t){let r,s,n=!1,i=2,a=!1;t.mask&&(r=t.maskBuffer||ui,t.generateMask?t.generateMask(r):(fi===hi&&(void 0===pi&&(pi=Buffer.alloc(hi)),ti(pi,0,hi),fi=0),r[0]=pi[fi++],r[1]=pi[fi++],r[2]=pi[fi++],r[3]=pi[fi++]),a=!(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?s=t.mask&&!a||void 0===t[li]?(e=Buffer.from(e)).length:t[li]:(s=e.length,n=t.mask&&t.readOnly&&!a);let o=s;s>=65536?(i+=8,o=127):s>125&&(i+=2,o=126);const c=Buffer.allocUnsafe(n?s+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=o,126===o?c.writeUInt16BE(s,2):127===o&&(c[2]=c[3]=0,c.writeUIntBE(s,4,6)),t.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],a?[c,e]:n?(ci(e,r,c,i,s),[c]):(ci(e,r,e,0,s),[c,e])):[c,e]}close(t,r,s,n){let i;if(void 0===t)i=si;else{if("number"!=typeof t||!oi(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==r&&r.length){const e=Buffer.byteLength(r);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+e),i.writeUInt16BE(t,0),"string"==typeof r?i.write(r,2):i.set(r,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(t,0)}const a={[li]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,a,n]):this.sendFrame(e.frame(i,a),n)}ping(t,r,s){let n,i;if("string"==typeof t?(n=Buffer.byteLength(t),i=!1):ai(t)?(n=t.size,i=!1):(n=(t=di(t)).length,i=di.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const a={[li]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ai(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,a,s]):this.getBlobData(t,!1,a,s):0!==this._state?this.enqueue([this.dispatch,t,!1,a,s]):this.sendFrame(e.frame(t,a),s)}pong(t,r,s){let n,i;if("string"==typeof t?(n=Buffer.byteLength(t),i=!1):ai(t)?(n=t.size,i=!1):(n=(t=di(t)).length,i=di.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const a={[li]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ai(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,a,s]):this.getBlobData(t,!1,a,s):0!==this._state?this.enqueue([this.dispatch,t,!1,a,s]):this.sendFrame(e.frame(t,a),s)}send(e,t,r){const s=this._extensions[ri.extensionName];let n,i,a=t.binary?2:1,o=t.compress;"string"==typeof e?(n=Buffer.byteLength(e),i=!1):ai(e)?(n=e.size,i=!1):(n=(e=di(e)).length,i=di.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=n>=s._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);const c={[li]:n,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:i,rsv1:o};ai(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(t,r,s,n){this._bufferedBytes+=s[li],this._state=2,t.arrayBuffer().then((t=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(_i,this,e,n)}this._bufferedBytes-=s[li];const i=di(t);r?this.dispatch(i,r,s,n):(this._state=0,this.sendFrame(e.frame(i,s),n),this.dequeue())})).catch((e=>{process.nextTick(gi,this,e,n)}))}dispatch(t,r,s,n){if(!r)return void this.sendFrame(e.frame(t,s),n);const i=this._extensions[ri.extensionName];this._bufferedBytes+=s[li],this._state=1,i.compress(t,s.fin,((t,r)=>{if(this._socket.destroyed){_i(this,new Error("The socket was closed while data was being compressed"),n)}else this._bufferedBytes-=s[li],this._state=0,s.readOnly=!1,this.sendFrame(e.frame(r,s),n),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][li],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][li],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _i(e,t,r){"function"==typeof r&&r(t);for(let r=0;r<e._queue.length;r++){const s=e._queue[r],n=s[s.length-1];"function"==typeof n&&n(t)}}function gi(e,t,r){_i(e,t,r),e.onerror(t)}const{kForOnEventAttribute:yi,kListener:vi}=hn,bi=Symbol("kCode"),wi=Symbol("kData"),ki=Symbol("kError"),xi=Symbol("kMessage"),Si=Symbol("kReason"),Ei=Symbol("kTarget"),Ti=Symbol("kType"),Ci=Symbol("kWasClean");class Oi{constructor(e){this[Ei]=null,this[Ti]=e}get target(){return this[Ei]}get type(){return this[Ti]}}Object.defineProperty(Oi.prototype,"target",{enumerable:!0}),Object.defineProperty(Oi.prototype,"type",{enumerable:!0});class Pi extends Oi{constructor(e,t={}){super(e),this[bi]=void 0===t.code?0:t.code,this[Si]=void 0===t.reason?"":t.reason,this[Ci]=void 0!==t.wasClean&&t.wasClean}get code(){return this[bi]}get reason(){return this[Si]}get wasClean(){return this[Ci]}}Object.defineProperty(Pi.prototype,"code",{enumerable:!0}),Object.defineProperty(Pi.prototype,"reason",{enumerable:!0}),Object.defineProperty(Pi.prototype,"wasClean",{enumerable:!0});class Ni extends Oi{constructor(e,t={}){super(e),this[ki]=void 0===t.error?null:t.error,this[xi]=void 0===t.message?"":t.message}get error(){return this[ki]}get message(){return this[xi]}}Object.defineProperty(Ni.prototype,"error",{enumerable:!0}),Object.defineProperty(Ni.prototype,"message",{enumerable:!0});class ji extends Oi{constructor(e,t={}){super(e),this[wi]=void 0===t.data?null:t.data}get data(){return this[wi]}}Object.defineProperty(ji.prototype,"data",{enumerable:!0});var Ri={EventTarget:{addEventListener(e,t,r={}){for(const s of this.listeners(e))if(!r[yi]&&s[vi]===t&&!s[yi])return;let s;if("message"===e)s=function(e,r){const s=new ji("message",{data:r?e:e.toString()});s[Ei]=this,Ai(t,this,s)};else if("close"===e)s=function(e,r){const s=new Pi("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Ei]=this,Ai(t,this,s)};else if("error"===e)s=function(e){const r=new Ni("error",{error:e,message:e.message});r[Ei]=this,Ai(t,this,r)};else{if("open"!==e)return;s=function(){const e=new Oi("open");e[Ei]=this,Ai(t,this,e)}}s[yi]=!!r[yi],s[vi]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[vi]===t&&!r[yi]){this.removeListener(e,r);break}}}};function Ai(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:Ii}=Un;function Zi(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var Li={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,s,n=Object.create(null),i=!1,a=!1,o=!1,c=-1,d=-1,l=-1,u=0;for(;u<e.length;u++)if(d=e.charCodeAt(u),void 0===r)if(-1===l&&1===Ii[d])-1===c&&(c=u);else if(0===u||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u);const s=e.slice(c,l);44===d?(Zi(t,s,n),n=Object.create(null)):r=s,c=l=-1}}else-1===l&&-1!==c&&(l=u);else if(void 0===s)if(-1===l&&1===Ii[d])-1===c&&(c=u);else if(32===d||9===d)-1===l&&-1!==c&&(l=u);else if(59===d||44===d){if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u),Zi(n,e.slice(c,l),!0),44===d&&(Zi(t,r,n),n=Object.create(null),r=void 0),c=l=-1}else{if(61!==d||-1===c||-1!==l)throw new SyntaxError(`Unexpected character at index ${u}`);s=e.slice(c,u),c=l=-1}else if(a){if(1!==Ii[d])throw new SyntaxError(`Unexpected character at index ${u}`);-1===c?c=u:i||(i=!0),a=!1}else if(o)if(1===Ii[d])-1===c&&(c=u);else if(34===d&&-1!==c)o=!1,l=u;else{if(92!==d)throw new SyntaxError(`Unexpected character at index ${u}`);a=!0}else if(34===d&&61===e.charCodeAt(u-1))o=!0;else if(-1===l&&1===Ii[d])-1===c&&(c=u);else if(-1===c||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u);let a=e.slice(c,l);i&&(a=a.replace(/\\/g,""),i=!1),Zi(n,s,a),44===d&&(Zi(t,r,n),n=Object.create(null),r=void 0),s=void 0,c=l=-1}}else-1===l&&(l=u);if(-1===c||o||32===d||9===d)throw new SyntaxError("Unexpected end of input");-1===l&&(l=u);const h=e.slice(c,l);return void 0===r?Zi(t,h,n):(void 0===s?Zi(n,h,!0):Zi(n,s,i?h.replace(/\\/g,""):h),Zi(t,r,n)),t}};const Mi=l,$i=u,Bi=h,Ui=p,Fi=f,{randomBytes:Di,createHash:qi}=m,{Duplex:zi,Readable:Hi}=_,{URL:Wi}=g,Vi=Rn,Gi=Qn,Ki=mi,{isBlob:Ji}=Un,{BINARY_TYPES:Yi,EMPTY_BUFFER:Xi,GUID:Qi,kForOnEventAttribute:ea,kListener:ta,kStatusCode:ra,kWebSocket:sa,NOOP:na}=hn,{EventTarget:{addEventListener:ia,removeEventListener:aa}}=Ri,{format:oa,parse:ca}=Li,{toBuffer:da}=gn,la=Symbol("kAborted"),ua=[8,13],ha=["CONNECTING","OPEN","CLOSING","CLOSED"],pa=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let fa=class e extends Mi{constructor(t,r,s){super(),this._binaryType=Yi[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==t?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===r?r=[]:Array.isArray(r)||("object"==typeof r&&null!==r?(s=r,r=[]):r=[r]),_a(this,t,r,s)):(this._autoPong=s.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yi.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,s){const n=new Gi({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new Ki(t,this._extensions,s.generateMask);this._receiver=n,this._sender=i,this._socket=t,n[sa]=this,i[sa]=this,t[sa]=this,n.on("conclude",ka),n.on("drain",xa),n.on("error",Sa),n.on("message",Ta),n.on("ping",Ca),n.on("pong",Oa),i.onerror=Na,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",Ra),t.on("data",Aa),t.on("end",Ia),t.on("error",Za),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=e.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[Vi.extensionName]&&this._extensions[Vi.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this.readyState!==e.CLOSING?(this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),ja(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";ba(this,this._req,e)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,r,s){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(s=t,t=r=void 0):"function"==typeof r&&(s=r,r=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===r&&(r=!this._isServer),this._sender.ping(t||Xi,r,s)):wa(this,t,s)}pong(t,r,s){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(s=t,t=r=void 0):"function"==typeof r&&(s=r,r=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===r&&(r=!this._isServer),this._sender.pong(t||Xi,r,s)):wa(this,t,s)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,s){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof r&&(s=r,r={}),"number"==typeof t&&(t=t.toString()),this.readyState!==e.OPEN)return void wa(this,t,s);const n={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Vi.extensionName]||(n.compress=!1),this._sender.send(t||Xi,n,s)}terminate(){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this._socket&&(this._readyState=e.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";ba(this,this._req,e)}}};Object.defineProperty(fa,"CONNECTING",{enumerable:!0,value:ha.indexOf("CONNECTING")}),Object.defineProperty(fa.prototype,"CONNECTING",{enumerable:!0,value:ha.indexOf("CONNECTING")}),Object.defineProperty(fa,"OPEN",{enumerable:!0,value:ha.indexOf("OPEN")}),Object.defineProperty(fa.prototype,"OPEN",{enumerable:!0,value:ha.indexOf("OPEN")}),Object.defineProperty(fa,"CLOSING",{enumerable:!0,value:ha.indexOf("CLOSING")}),Object.defineProperty(fa.prototype,"CLOSING",{enumerable:!0,value:ha.indexOf("CLOSING")}),Object.defineProperty(fa,"CLOSED",{enumerable:!0,value:ha.indexOf("CLOSED")}),Object.defineProperty(fa.prototype,"CLOSED",{enumerable:!0,value:ha.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(fa.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(fa.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[ea])return t[ta];return null},set(t){for(const t of this.listeners(e))if(t[ea]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[ea]:!0})}})})),fa.prototype.addEventListener=ia,fa.prototype.removeEventListener=aa;var ma=fa;function _a(e,t,r,s){const n={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:ua[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=n.autoPong,!ua.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${ua.join(", ")})`);let i;if(t instanceof Wi)i=t;else try{i=new Wi(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===i.protocol?i.protocol="ws:":"https:"===i.protocol&&(i.protocol="wss:"),e._url=i.href;const a="wss:"===i.protocol,o="ws+unix:"===i.protocol;let c;if("ws:"===i.protocol||a||o?o&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void ga(e,t)}const d=a?443:80,l=Di(16).toString("base64"),u=a?$i.request:Bi.request,h=new Set;let p,f;if(n.createConnection=n.createConnection||(a?va:ya),n.defaultPort=n.defaultPort||d,n.port=i.port||d,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(p=new Vi(!0!==n.perMessageDeflate?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=oa({[Vi.extensionName]:p.offer()})),r.length){for(const e of r){if("string"!=typeof e||!pa.test(e)||h.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(e)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),o){const e=n.path.split(":");n.socketPath=e[0],n.path=e[1]}if(n.followRedirects){if(0===e._redirects){e._originalIpc=o,e._originalSecure=a,e._originalHostOrSocketPath=o?n.socketPath:i.host;const t=s&&s.headers;if(s={...s,headers:{}},t)for(const[e,r]of Object.entries(t))s.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=o?!!e._originalIpc&&n.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!a)&&(delete n.headers.authorization,delete n.headers.cookie,t||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),f=e._req=u(n),e._redirects&&e.emit("redirect",e.url,f)}else f=e._req=u(n);n.timeout&&f.on("timeout",(()=>{ba(e,f,"Opening handshake has timed out")})),f.on("error",(t=>{null===f||f[la]||(f=e._req=null,ga(e,t))})),f.on("response",(i=>{const a=i.headers.location,o=i.statusCode;if(a&&n.followRedirects&&o>=300&&o<400){if(++e._redirects>n.maxRedirects)return void ba(e,f,"Maximum redirects exceeded");let i;f.abort();try{i=new Wi(a,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${a}`);return void ga(e,r)}_a(e,i,r,s)}else e.emit("unexpected-response",f,i)||ba(e,f,`Unexpected server response: ${i.statusCode}`)})),f.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==fa.CONNECTING)return;f=e._req=null;const i=t.headers.upgrade;if(void 0===i||"websocket"!==i.toLowerCase())return void ba(e,r,"Invalid Upgrade header");const a=qi("sha1").update(l+Qi).digest("base64");if(t.headers["sec-websocket-accept"]!==a)return void ba(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let c;if(void 0!==o?h.size?h.has(o)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":h.size&&(c="Server sent no subprotocol"),c)return void ba(e,r,c);o&&(e._protocol=o);const d=t.headers["sec-websocket-extensions"];if(void 0!==d){if(!p){return void ba(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=ca(d)}catch(t){return void ba(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==Vi.extensionName){return void ba(e,r,"Server indicated an extension that was not requested")}try{p.accept(t[Vi.extensionName])}catch(t){return void ba(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Vi.extensionName]=p}e.setSocket(r,s,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})})),n.finishRequest?n.finishRequest(f,e):f.end()}function ga(e,t){e._readyState=fa.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function ya(e){return e.path=e.socketPath,Ui.connect(e)}function va(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Ui.isIP(e.host)?"":e.host),Fi.connect(e)}function ba(e,t,r){e._readyState=fa.CLOSING;const s=new Error(r);Error.captureStackTrace(s,ba),t.setHeader?(t[la]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ga,e,s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function wa(e,t,r){if(t){const r=Ji(t)?t.size:da(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${ha[e.readyState]})`);process.nextTick(r,t)}}function ka(e,t){const r=this[sa];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[sa]&&(r._socket.removeListener("data",Aa),process.nextTick(Pa,r._socket),1005===e?r.close():r.close(e,t))}function xa(){const e=this[sa];e.isPaused||e._socket.resume()}function Sa(e){const t=this[sa];void 0!==t._socket[sa]&&(t._socket.removeListener("data",Aa),process.nextTick(Pa,t._socket),t.close(e[ra])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Ea(){this[sa].emitClose()}function Ta(e,t){this[sa].emit("message",e,t)}function Ca(e){const t=this[sa];t._autoPong&&t.pong(e,!this._isServer,na),t.emit("ping",e)}function Oa(e){this[sa].emit("pong",e)}function Pa(e){e.resume()}function Na(e){const t=this[sa];t.readyState!==fa.CLOSED&&(t.readyState===fa.OPEN&&(t._readyState=fa.CLOSING,ja(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function ja(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function Ra(){const e=this[sa];let t;this.removeListener("close",Ra),this.removeListener("data",Aa),this.removeListener("end",Ia),e._readyState=fa.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[sa]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Ea),e._receiver.on("finish",Ea))}function Aa(e){this[sa]._receiver.write(e)||this.pause()}function Ia(){const e=this[sa];e._readyState=fa.CLOSING,e._receiver.end(),this.end()}function Za(){const e=this[sa];this.removeListener("error",Za),this.on("error",na),e&&(e._readyState=fa.CLOSING,this.destroy())}const{Duplex:La}=_,{tokenChars:Ma}=Un;var $a={parse:function(e){const t=new Set;let r=-1,s=-1,n=0;for(;n<e.length;n++){const i=e.charCodeAt(n);if(-1===s&&1===Ma[i])-1===r&&(r=n);else if(0===n||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${n}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${n}`);-1===s&&(s=n);const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=s=-1}}else-1===s&&-1!==r&&(s=n)}if(-1===r||-1!==s)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const Ba=l,Ua=h,{Duplex:Fa}=_,{createHash:Da}=m,qa=Li,za=Rn,Ha=$a,Wa=ma,{GUID:Va,kWebSocket:Ga}=hn,Ka=/^[+/0-9A-Za-z]{22}==$/;function Ja(e){e._state=2,e.emit("close")}function Ya(){this.destroy()}function Xa(e,t,r,s){r=r||Ua.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${Ua.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Qa(e,t,r,s,n){if(e.listenerCount("wsClientError")){const s=new Error(n);Error.captureStackTrace(s,Qa),e.emit("wsClientError",s,r,t)}else Xa(r,s,n)}var eo=cn(class extends Ba{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wa,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=Ua.createServer(((e,t)=>{const r=Ua.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,s)=>{this.handleUpgrade(t,r,s,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(Ja,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ja,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Ja(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",Ya);const n=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Qa(this,e,t,405,"Invalid HTTP method")}if(void 0===i||"websocket"!==i.toLowerCase()){return void Qa(this,e,t,400,"Invalid Upgrade header")}if(void 0===n||!Ka.test(n)){return void Qa(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==a&&13!==a){return void Qa(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Xa(t,400);const o=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==o)try{c=Ha.parse(o)}catch(r){return void Qa(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const d=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==d){const r=new za(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=qa.parse(d);e[za.extensionName]&&(r.accept(e[za.extensionName]),l[za.extensionName]=r)}catch(r){return void Qa(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const i={origin:e.headers[""+(8===a?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(i,((i,a,o,d)=>{if(!i)return Xa(t,a||401,o,d);this.completeUpgrade(l,n,c,e,t,r,s)}));if(!this.options.verifyClient(i))return Xa(t,401)}this.completeUpgrade(l,n,c,e,t,r,s)}completeUpgrade(e,t,r,s,n,i,a){if(!n.readable||!n.writable)return n.destroy();if(n[Ga])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Xa(n,503);const o=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Da("sha1").update(t+Va).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(o.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[za.extensionName]){const t=e[za.extensionName].params,r=qa.format({[za.extensionName]:[t]});o.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",o,s),n.write(o.concat("\r\n").join("\r\n")),n.removeListener("error",Ya),c.setSocket(n,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ja,this)}))),a(c,s)}});const to=a(c(import.meta.url)),ro=o(to,"../.."),so=process.env.PORT?Number.parseInt(process.env.PORT):7898,no=[],io=[],ao={"/browser-mcp-server.js":{path:o(to,"browser-mcp-server.js"),contentType:"application/javascript"},"/browser-inject.js":{path:o(to,"browser-inject.js"),contentType:"application/javascript"},"/browser-console-mcp.js":{path:o(ro,"dist/client/browser-console-mcp.js"),contentType:"application/javascript"},"/browser-console-mcp.js.map":{path:o(ro,"dist/client/browser-console-mcp.js.map"),contentType:"application/json"}},oo=n((async(e,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept"),"OPTIONS"===e.method)return r.writeHead(204),void r.end();if("/status"===e.url)return r.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*"}),void r.end(JSON.stringify({browserCount:no.length,cursorCount:io.length}));const s=ao[e.url??""];if(s)try{const e=await t.readFile(s.path,"utf8");r.writeHead(200,{"Content-Type":s.contentType}),r.end(e)}catch{r.writeHead(500),r.end("Internal Server Error")}else r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`<!DOCTYPE html>\n<html>\n <head>\n <meta charset="utf-8">\n <title>Browser MCP Relay Server</title>\n <style>\n body { font-family: Arial, sans-serif; line-height: 1.6; max-width: 800px; margin: 0 auto; padding: 20px; }\n pre { background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto; }\n code { font-family: monospace; }\n .bookmarklet { display: inline-block; padding: 8px 12px; background-color: #f0f0f0; border-radius: 4px; text-decoration: none; color: #333; border: 1px solid #ccc; }\n </style>\n </head>\n <body>\n <h1>Browser MCP Relay Server</h1>\n <p>Server is running. Browser connections: <span id="bc">—</span> | Cursor connections: <span id="cc">—</span></p>\n\n <h2>Step 1: Inject MCP Client in Browser</h2>\n <p>Drag to bookmarks bar:</p>\n <a class="bookmarklet" href="javascript:(function(){var s=document.createElement('script');s.src='http://localhost:${so}/browser-inject.js';document.head.appendChild(s);})();">Browser MCP</a>\n <p>Or paste in browser console:</p>\n <pre><code>var s = document.createElement('script');\ns.src = 'http://localhost:${so}/browser-inject.js';\ndocument.head.appendChild(s);</code></pre>\n\n <h2>Step 2: Use MCP Tools in Cursor</h2>\n <pre><code>executeJS({ code: 'console.log(window.location.href)' })\ngetPageHTML()\ngetPageTitle()</code></pre>\n\n <script>\n setInterval(() => {\n fetch('/status').then(r => r.json()).then(d => {\n document.getElementById('bc').textContent = d.browserCount;\n document.getElementById('cc').textContent = d.cursorCount;\n }).catch(() => {});\n }, 5000);\n <\/script>\n </body>\n</html>`)}));const co=new eo({server:oo});function lo(e){return{content:[{type:"text",text:e}]}}function uo(e){return{content:[{type:"text",text:e}],isError:!0}}function ho(){return uo("Error: No browser connections. Please inject the MCP client in the browser first.")}function po(t,r={},s=5e3){return new Promise(((n,i)=>{const a=e(),o=no[0];let c=!1;function d(){clearTimeout(u),o.removeListener("message",p),o.removeListener("close",h)}function l(e){c||(c=!0,d(),i(e))}const u=setTimeout((()=>l(new Error("Request timed out. Browser did not respond."))),s);function h(){l(new Error("Browser connection closed while waiting for response."))}function p(e){let t;try{t=JSON.parse(e.toString())}catch{return}var r;t.requestId===a&&(t.error?l(new Error(String(t.error))):(r=t,c||(c=!0,d(),n(r))))}o.on("message",p),o.on("close",h),o.send(JSON.stringify({type:t,requestId:a,...r}))}))}co.on("connection",((e,t)=>{const r=new URL(t.url||"",`http://${t.headers.host}`).pathname;"/browser"===r?(no.push(e),e.send(JSON.stringify({type:"connection_status",status:"connected",message:"Connected to relay server"})),e.on("message",(e=>{for(const t of io)t.send(e.toString())})),e.on("close",(()=>{const t=no.indexOf(e);-1!==t&&no.splice(t,1)}))):"/cursor"===r&&(io.push(e),e.on("message",(e=>{for(const t of no)t.send(e.toString())})),e.on("close",(()=>{const t=io.indexOf(e);-1!==t&&io.splice(t,1),0===io.length&&setTimeout((()=>_o(!0)),2e3)})))}));const fo=new class{constructor(e=d.stdin,t=d.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new on,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}}async start(){if(this._started)throw new 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{const t=this._readBuffer.readMessage();if(null===t)break;null===(e=this.onmessage)||void 0===e||e.call(this,t)}catch(e){null===(t=this.onerror)||void 0===t||t.call(this,e)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror);0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}send(e){return new Promise((t=>{const r=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(r)?t():this._stdout.once("drain",t)}))}},mo=new class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new _s(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Vr.shape.method.value),this.server.assertCanSetRequestHandler(Jr.shape.method.value),this.server.registerCapabilities({tools:{}}),this.server.setRequestHandler(Vr,(()=>({tools:Object.entries(this._registeredTools).map((([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?Qs(t.inputSchema):sn})))}))),this.server.setRequestHandler(Jr,(async(e,t)=>{const r=this._registeredTools[e.params.name];if(!r)throw new fs(nr.InvalidParams,`Tool ${e.params.name} not found`);if(r.inputSchema){const s=await r.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new fs(nr.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);const n=s.data,i=r.callback;try{return await Promise.resolve(i(n,t))}catch(e){return{content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}}else{const e=r.callback;try{return await Promise.resolve(e(t))}catch(e){return{content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}}})),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(cs.shape.method.value),this.server.setRequestHandler(cs,(async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new fs(nr.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}})),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){const r=this._registeredPrompts[t.name];if(!r)throw new fs(nr.InvalidParams,`Prompt ${e.params.ref.name} not found`);if(!r.argsSchema)return an;const s=r.argsSchema.shape[e.params.argument.name];if(!(s instanceof tn))return an;const n=s._def;return nn(await n.complete(e.params.argument.value))}async handleResourceCompletion(e,t){const r=Object.values(this._registeredResourceTemplates).find((e=>e.resourceTemplate.uriTemplate.toString()===t.uri));if(!r){if(this._registeredResources[t.uri])return an;throw new fs(nr.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return an;return nn(await s(e.params.argument.value))}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Er.shape.method.value),this.server.assertCanSetRequestHandler(Cr.shape.method.value),this.server.assertCanSetRequestHandler(Pr.shape.method.value),this.server.registerCapabilities({resources:{}}),this.server.setRequestHandler(Er,(async(e,t)=>{const r=Object.entries(this._registeredResources).map((([e,t])=>({uri:e,name:t.name,...t.metadata}))),s=[];for(const e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;const r=await e.resourceTemplate.listCallback(t);for(const t of r.resources)s.push({...t,...e.metadata})}return{resources:[...r,...s]}})),this.server.setRequestHandler(Cr,(async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map((([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata})))}))),this.server.setRequestHandler(Pr,(async(e,t)=>{const r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s)return s.readCallback(r,t);for(const e of Object.values(this._registeredResourceTemplates)){const s=e.resourceTemplate.uriTemplate.match(r.toString());if(s)return e.readCallback(r,s,t)}throw new fs(nr.InvalidParams,`Resource ${r} not found`)})),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Mr.shape.method.value),this.server.assertCanSetRequestHandler(Br.shape.method.value),this.server.registerCapabilities({prompts:{}}),this.server.setRequestHandler(Mr,(()=>({prompts:Object.entries(this._registeredPrompts).map((([e,t])=>{return{name:e,description:t.description,arguments:t.argsSchema?(r=t.argsSchema,Object.entries(r.shape).map((([e,t])=>({name:e,description:t.description,required:!t.isOptional()})))):void 0};var r}))}))),this.server.setRequestHandler(Br,(async(e,t)=>{const r=this._registeredPrompts[e.params.name];if(!r)throw new fs(nr.InvalidParams,`Prompt ${e.params.name} not found`);if(r.argsSchema){const s=await r.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new fs(nr.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);const n=s.data,i=r.callback;return await Promise.resolve(i(n,t))}{const e=r.callback;return await Promise.resolve(e(t))}})),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;"object"==typeof r[0]&&(s=r.shift());const n=r[0];if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);this._registeredResources[t]={name:e,metadata:s,readCallback:n}}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);this._registeredResourceTemplates[e]={resourceTemplate:t,metadata:s,readCallback:n}}this.setResourceRequestHandlers()}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,s;"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(s=t.shift());const n=t[0];this._registeredTools[e]={description:r,inputSchema:void 0===s?void 0:qt.object(s),callback:n},this.setToolRequestHandlers()}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r,s;"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(s=t.shift());const n=t[0];this._registeredPrompts[e]={description:r,argsSchema:void 0===s?void 0:qt.object(s),callback:n},this.setPromptRequestHandlers()}}({name:"Browser MCP",version:"1.0.0"});function _o(e=!0){for(const e of[...no,...io])try{e.close()}catch{}co.close(),oo.close((()=>{e&&process.exit(0)}))}mo.tool("executeJS","Execute JavaScript code in the current page context",{code:qt.string().describe("JavaScript code to execute in the browser page context")},(async({code:e})=>{if(0===no.length)return ho();try{const t=await po("execute_js",{code:e});return lo(String(t.result||"Execution successful, no return value"))}catch(e){return uo(`Error: ${e.message}`)}})),mo.tool("getPageHTML","Get HTML content of the current page",{},(async()=>{if(0===no.length)return ho();try{const e=await po("get_page_html");return lo(String(e.html??""))}catch(e){return uo(`Error: ${e.message}`)}})),mo.tool("getPageTitle","Get title of the current page",{},(async()=>{if(0===no.length)return ho();try{const e=await po("get_page_title");return lo(String(e.title??""))}catch(e){return uo(`Error: ${e.message}`)}})),mo.tool("getElements","Use CSS selector to get elements on the page",{selector:qt.string().describe("CSS selector")},(async({selector:e})=>{if(0===no.length)return ho();try{const t=await po("get_elements",{selector:e});return lo(JSON.stringify(t.elements,null,2))}catch(e){return uo(`Error: ${e.message}`)}})),mo.tool("captureScreenshot","Capture screenshot of the current page (using html2canvas)",{selector:qt.string().optional().describe("Optional CSS selector for capturing a specific element")},(async({selector:e="body"})=>{if(0===no.length)return ho();try{const t=await po("capture_screenshot",{selector:e},15e3);if(!t.imageDataUrl)return uo("Error: No screenshot data received");const n=String(t.imageDataUrl).split(",");if(2!==n.length||!n[1])return uo("Error: Screenshot data format is incorrect");const a=i(),c=o(a,"Downloads","mcp-screenshots");r(c,{recursive:!0});const d=(new Date).toISOString().replace(/[:.]/g,"-"),l=o(c,`screenshot-${d}.png`);return s(l,n[1],"base64"),lo(`Screenshot saved to: ${l}\n\nTip: for better results, specify a selector like captureScreenshot({selector: ".main-content"})`)}catch(e){return uo(`Error: ${e.message}`)}})),mo.tool("getPageURL","Get URL of the current page",{},(async()=>{if(0===no.length)return ho();try{const e=await po("get_page_url");return lo(String(e.url??""))}catch(e){return uo(`Error: ${e.message}`)}})),mo.tool("clickElement","Click element on the page",{selector:qt.string().describe("CSS selector of the element to click")},(async({selector:e})=>{if(0===no.length)return ho();try{const t=await po("click_element",{selector:e});return lo(String(t.message??"Element clicked successfully"))}catch(e){return uo(`Error: ${e.message}`)}})),mo.tool("inputText","Enter text into input field",{selector:qt.string().describe("CSS selector of the input field"),text:qt.string().describe("Text to enter")},(async({selector:e,text:t})=>{if(0===no.length)return ho();try{const r=await po("input_text",{selector:e,text:t});return lo(String(r.message??"Text entered successfully"))}catch(e){return uo(`Error: ${e.message}`)}})),process.on("SIGINT",(()=>_o(!0))),process.on("SIGTERM",(()=>_o(!0))),process.on("uncaughtException",(e=>{console.error("[BCM] Uncaught exception:",e),_o(!0)})),process.on("unhandledRejection",(e=>{console.error("[BCM] Unhandled Promise rejection:",e)})),oo.listen(so,(()=>{console.log(`[BCM] Server started, listening on port ${so}`)})),mo.connect(fo).catch((e=>{console.error("[BCM] MCP server initialization failed:",e),_o(!0)}));
|
|
2
2
|
//# sourceMappingURL=index.js.map
|