browser-console-mcp 1.0.4 → 1.0.6
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/bin/copy-browser-inject.js +55 -0
- package/bin/copy-html2canvas.js +19 -0
- package/dist/browser/browser-inject.js +9 -9
- package/dist/browser/index.js +1 -1
- package/package.json +3 -2
- package/dist/browser/browser-mcp-server.js +0 -718
- package/dist/static/html2canvas/dist/html2canvas.min.js +0 -20
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}),M=e=>({status:"valid",value:e}),R=e=>"aborted"===e.status,A=e=>"dirty"===e.status,Z=e=>"valid"===e.status,$=e=>"undefined"!=typeof Promise&&e instanceof Promise;function L(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 H=(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 z(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($(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 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($(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: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 ze.create(this,this._def)}or(e){return Ne.create([this,e],this._def)}and(e){return Re.create(this,e,this._def)}transform(e){return new We({...z(this._def),schema:this,typeName:it.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Je({...z(this._def),innerType:this,defaultValue:t,typeName:it.ZodDefault})}brand(){return new Qe({typeName:it.ZodBranded,type:this,...z(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ke({...z(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,...z(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,...z(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,...z(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 M(e.data)}}ye.create=e=>new ye({typeName:it.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...z(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,...z(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 M(e.data)}}be.create=e=>new be({typeName:it.ZodSymbol,...z(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 M(e.data)}}we.create=e=>new we({typeName:it.ZodUndefined,...z(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 M(e.data)}}xe.create=e=>new xe({typeName:it.ZodNull,...z(e)});class ke extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return M(e.data)}}ke.create=e=>new ke({typeName:it.ZodAny,...z(e)});class Se extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return M(e.data)}}Se.create=e=>new Se({typeName:it.ZodUnknown,...z(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,...z(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 M(e.data)}}Ce.create=e=>new Ce({typeName:it.ZodVoid,...z(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,...z(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,...z(t)}),Pe.strictCreate=(e,t)=>new Pe({shape:()=>e,unknownKeys:"strict",catchall:Ee.create(),typeName:it.ZodObject,...z(t)}),Pe.lazycreate=(e,t)=>new Pe({shape:e,unknownKeys:"strip",catchall:Ee.create(),typeName:it.ZodObject,...z(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,...z(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 He?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,...z(r)})}}function Me(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=Me(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=Me(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 Re extends W{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(R(e)||R(s))return j;const n=Me(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}))}}Re.create=(e,t,r)=>new Re({left:e,right:t,typeName:it.ZodIntersection,...z(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,...z(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,...z(r)}:{keyType:fe.create(),valueType:e,typeName:it.ZodRecord,...z(t)})}}class $e 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}}}}$e.create=(e,t,r)=>new $e({valueType:t,keyType:e,typeName:it.ZodMap,...z(r)});class Le 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 Le({...this._def,minSize:{value:e,message:q.toString(t)}})}max(e,t){return new Le({...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)}}Le.create=(e,t)=>new Le({valueType:e,minSize:null,maxSize:null,typeName:it.ZodSet,...z(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 ze){const e=this;return M((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 M((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,...z(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,...z(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,...z(t)})}Fe.create=(e,t)=>new Fe({value:e,typeName:it.ZodLiteral,...z(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(L(this,F)||B(this,F,new Set(this._def.values)),!L(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 M(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 He 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(L(this,U)||B(this,U,new Set(v.getValidEnumValues(this._def.values))),!L(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 M(e.data)}get enum(){return this._def.values}}U=new WeakMap,He.create=(e,t)=>new He({values:e,typeName:it.ZodNativeEnum,...z(t)});class ze 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 M(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}ze.create=(e,t)=>new ze({type:e,typeName:it.ZodPromise,...z(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,...z(r)}),We.createWithPreprocess=(e,t,r)=>new We({schema:t,effect:{type:"preprocess",transform:e},typeName:it.ZodEffects,...z(r)});class Ve extends W{_parse(e){return this._getType(e)===w.undefined?M(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ve.create=(e,t)=>new Ve({innerType:e,typeName:it.ZodOptional,...z(t)});class Ge extends W{_parse(e){return this._getType(e)===w.null?M(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ge.create=(e,t)=>new Ge({innerType:e,typeName:it.ZodNullable,...z(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,...z(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 $(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,...z(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,...z(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 $(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,...z(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=Re.create,Et=Ae.create,Ct=Ze.create,Tt=$e.create,Ot=Le.create,Pt=Be.create,Nt=qe.create,jt=Fe.create,It=De.create,Mt=He.create,Rt=ze.create,At=We.create,Zt=Ve.create,$t=Ge.create,Lt=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:M,isAborted:R,isDirty:A,isValid:Z,isAsync:$,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:Re,ZodTuple:Ae,ZodRecord:Ze,ZodMap:$e,ZodSet:Le,ZodFunction:Be,ZodLazy:qe,ZodLiteral:Fe,ZodEnum:De,ZodNativeEnum:He,ZodPromise:ze,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:Mt,never:_t,null:ft,nullable:$t,number:ot,object:bt,oboolean:()=>lt().optional(),onumber:()=>ot().optional(),optional:Zt,ostring:()=>at().optional(),pipeline:Bt,preprocess:Lt,promise:Rt,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",Ht=[Dt,"2024-10-07"],zt="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(zt),id:Qt}).merge(Jt).strict(),tr=Ut.object({jsonrpc:Ut.literal(zt)}).merge(Yt).strict(),rr=Ut.object({jsonrpc:Ut.literal(zt),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(zt),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()})}),Mr=Yt.extend({method:Ut.literal("notifications/resources/updated"),params:Kt.extend({uri:Ut.string()})}),Rr=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(Rr))}).passthrough(),Zr=_r.extend({method:Ut.literal("prompts/list")}),$r=yr.extend({prompts:Ut.array(Ar)}),Lr=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)}),Hr=Yt.extend({method:Ut.literal("notifications/prompts/list_changed")}),zr=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(zr)}),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,Lr,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,Mr,Nr,Kr,Hr]),Ut.union([ar,hr,cs,Dr,$r,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:Ht.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}=))?$/,Ms=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rs=/^[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(`^${$s(s.value,t)}`),s.message,t);break;case"endsWith":qs(r,RegExp(`${$s(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($s(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,Ms,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,Rs,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++)Ls.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}const Ls=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 Hs=(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 zs(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 zs(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 Hs(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 Hs(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",Rn),this._inflate.on("data",Mn)}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 Mn(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",Mn),this.reset())}function Rn(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:$n}=un;function Ln(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 $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:Ln,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?Ln(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?Ln(t):e(t)}}catch(e){}var Bn=An.exports;const{Writable:qn}=m,Fn=jn,{BINARY_TYPES:Un,EMPTY_BUFFER:Dn,kStatusCode:Hn,kWebSocket:zn}=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[zn]=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[Hn]=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:Mi}=Bn;function Ri(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===Mi[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?(Ri(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===Mi[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),Ri(n,e.slice(c,l),!0),44===d&&(Ri(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!==Mi[d])throw new SyntaxError(`Unexpected character at index ${u}`);-1===c?c=u:i||(i=!0),a=!1}else if(o)if(1===Mi[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===Mi[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),Ri(n,s,a),44===d&&(Ri(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?Ri(t,h,n):(void 0===s?Ri(n,h,!0):Ri(n,s,i?h.replace(/\\/g,""):h),Ri(t,r,n)),t}};const Zi=d,$i=l,Li=u,Bi=h,qi=p,{randomBytes:Fi,createHash:Ui}=f,{Duplex:Di,Readable:Hi}=m,{URL:zi}=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",Ma),t.on("error",Ra),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 zi)i=t;else try{i=new zi(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?$i.request:Li.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 zi(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",Ma),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 Ma(){const e=this[ra];e._readyState=pa.CLOSING,e._receiver.end(),this.end()}function Ra(){const e=this[ra];this.removeListener("error",Ra),this.on("error",sa),e&&(e._readyState=pa.CLOSING,this.destroy())}const{Duplex:Aa}=m,{tokenChars:Za}=Bn;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===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 La=d,Ba=u,{Duplex:qa}=m,{createHash:Fa}=f,Ua=Ai,Da=jn,Ha=$a,za=fa,{GUID:Wa,kWebSocket:Va}=un,Ga=/^[+/0-9A-Za-z]{22}==$/;var Ja=class extends La{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:za,...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=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 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",(()=>{console.log("[BCM] Browser connection closed");const t=no.indexOf(e);-1!==t&&no.splice(t,1)}))):"/cursor"===r&&(console.log("[BCM] New Cursor connection"),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",(()=>{console.log("[BCM] Cursor connection closed");const t=io.indexOf(e);-1!==t&&io.splice(t,1)})))}));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(Lr.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(Lr,(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){console.log("[BCM] Closing server...");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((()=>{console.log("[BCM] HTTP server closed"),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"),console.log(`[BCM] Screenshot saved to: ${u}`),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{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,$=e=>"undefined"!=typeof Promise&&e instanceof Promise;function L(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($(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($(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 $e 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}}}}$e.create=(e,t,r)=>new $e({valueType:t,keyType:e,typeName:it.ZodMap,...H(r)});class Le 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 Le({...this._def,minSize:{value:e,message:q.toString(t)}})}max(e,t){return new Le({...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)}}Le.create=(e,t)=>new Le({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(L(this,F)||B(this,F,new Set(this._def.values)),!L(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(L(this,U)||B(this,U,new Set(v.getValidEnumValues(this._def.values))),!L(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 $(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 $(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=$e.create,Ot=Le.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,$t=Ge.create,Lt=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:$,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:$e,ZodSet:Le,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:$t,number:ot,object:bt,oboolean:()=>lt().optional(),onumber:()=>ot().optional(),optional:Zt,ostring:()=>at().optional(),pipeline:Bt,preprocess:Lt,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")}),$r=yr.extend({prompts:Ut.array(Ar)}),Lr=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,Lr,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,$r,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(`^${$s(s.value,t)}`),s.message,t);break;case"endsWith":qs(r,RegExp(`${$s(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($s(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 $s(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)Ls.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}const Ls=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:$n}=un;function Ln(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 $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:Ln,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?Ln(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?Ln(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,$i=l,Li=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?$i.request:Li.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 $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===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 La=d,Ba=u,{Duplex:qa}=m,{createHash:Fa}=f,Ua=Ai,Da=jn,za=$a,Ha=fa,{GUID:Wa,kWebSocket:Va}=un,Ga=/^[+/0-9A-Za-z]{22}==$/;var Ja=class extends La{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",(()=>{console.log("[BCM] Browser connection closed");const t=no.indexOf(e);-1!==t&&no.splice(t,1)}))):"/cursor"===r&&(console.log("[BCM] New Cursor connection"),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",(()=>{console.log("[BCM] Cursor connection closed");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(Lr.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(Lr,(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"),console.log(`[BCM] Screenshot saved to: ${u}`),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)}));
|
|
2
2
|
//# sourceMappingURL=index.js.map
|