@f2c/mcp 0.4.8 → 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js DELETED
@@ -1,457 +0,0 @@
1
- #!/usr/bin/env node
2
- var C1=Object.create;var{getPrototypeOf:I1,defineProperty:C3,getOwnPropertyNames:T1}=Object;var x1=Object.prototype.hasOwnProperty;var y1=($,X,Q)=>{Q=$!=null?C1(I1($)):{};let Y=X||!$||!$.__esModule?C3(Q,"default",{value:$,enumerable:!0}):Q;for(let G of T1($))if(!x1.call(Y,G))C3(Y,G,{get:()=>$[G],enumerable:!0});return Y};var t6=($,X)=>()=>(X||$((X={exports:{}}).exports,X),X.exports);var h1=($,X)=>{for(var Q in X)C3($,Q,{get:X[Q],enumerable:!0,configurable:!0,set:(Y)=>X[Q]=()=>Y})};var g=($,X)=>()=>($&&(X=$($=0)),X);var L,I3,M,t=($)=>{switch(typeof $){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN($)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":if(Array.isArray($))return M.array;if($===null)return M.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return M.promise;if(typeof Map!=="undefined"&&$ instanceof Map)return M.map;if(typeof Set!=="undefined"&&$ instanceof Set)return M.set;if(typeof Date!=="undefined"&&$ instanceof Date)return M.date;return M.object;default:return M.unknown}};var I$=g(()=>{(function($){$.assertEqual=(G)=>{};function X(G){}$.assertIs=X;function Q(G){throw new Error}$.assertNever=Q,$.arrayToEnum=(G)=>{let W={};for(let H of G)W[H]=H;return W},$.getValidEnumValues=(G)=>{let W=$.objectKeys(G).filter((B)=>typeof G[G[B]]!=="number"),H={};for(let B of W)H[B]=G[B];return $.objectValues(H)},$.objectValues=(G)=>{return $.objectKeys(G).map(function(W){return G[W]})},$.objectKeys=typeof Object.keys==="function"?(G)=>Object.keys(G):(G)=>{let W=[];for(let H in G)if(Object.prototype.hasOwnProperty.call(G,H))W.push(H);return W},$.find=(G,W)=>{for(let H of G)if(W(H))return H;return},$.isInteger=typeof Number.isInteger==="function"?(G)=>Number.isInteger(G):(G)=>typeof G==="number"&&Number.isFinite(G)&&Math.floor(G)===G;function Y(G,W=" | "){return G.map((H)=>typeof H==="string"?`'${H}'`:H).join(W)}$.joinValues=Y,$.jsonStringifyReplacer=(G,W)=>{if(typeof W==="bigint")return W.toString();return W}})(L||(L={}));(function($){$.mergeShapes=(X,Q)=>{return{...X,...Q}}})(I3||(I3={}));M=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var w,Z1=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")},h;var r$=g(()=>{I$();w=L.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"]);h=class h extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(Q)=>{this.issues=[...this.issues,Q]},this.addIssues=(Q=[])=>{this.issues=[...this.issues,...Q]};let X=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,X);else this.__proto__=X;this.name="ZodError",this.issues=$}format($){let X=$||function(G){return G.message},Q={_errors:[]},Y=(G)=>{for(let W of G.issues)if(W.code==="invalid_union")W.unionErrors.map(Y);else if(W.code==="invalid_return_type")Y(W.returnTypeError);else if(W.code==="invalid_arguments")Y(W.argumentsError);else if(W.path.length===0)Q._errors.push(X(W));else{let H=Q,B=0;while(B<W.path.length){let D=W.path[B];if(B!==W.path.length-1)H[D]=H[D]||{_errors:[]};else H[D]=H[D]||{_errors:[]},H[D]._errors.push(X(W));H=H[D],B++}}};return Y(this),Q}static assert($){if(!($ instanceof h))throw new Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(X)=>X.message){let X={},Q=[];for(let Y of this.issues)if(Y.path.length>0){let G=Y.path[0];X[G]=X[G]||[],X[G].push($(Y))}else Q.push($(Y));return{formErrors:Q,fieldErrors:X}}get formErrors(){return this.flatten()}};h.create=($)=>{return new h($)}});var g1=($,X)=>{let Q;switch($.code){case w.invalid_type:if($.received===M.undefined)Q="Required";else Q=`Expected ${$.expected}, received ${$.received}`;break;case w.invalid_literal:Q=`Invalid literal value, expected ${JSON.stringify($.expected,L.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:Q=`Unrecognized key(s) in object: ${L.joinValues($.keys,", ")}`;break;case w.invalid_union:Q="Invalid input";break;case w.invalid_union_discriminator:Q=`Invalid discriminator value. Expected ${L.joinValues($.options)}`;break;case w.invalid_enum_value:Q=`Invalid enum value. Expected ${L.joinValues($.options)}, received '${$.received}'`;break;case w.invalid_arguments:Q="Invalid function arguments";break;case w.invalid_return_type:Q="Invalid function return type";break;case w.invalid_date:Q="Invalid date";break;case w.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(Q=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")Q=`${Q} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)Q=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)Q=`Invalid input: must end with "${$.validation.endsWith}"`;else L.assertNever($.validation);else if($.validation!=="regex")Q=`Invalid ${$.validation}`;else Q="Invalid";break;case w.too_small:if($.type==="array")Q=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")Q=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")Q=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")Q=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")Q=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else Q="Invalid input";break;case w.too_big:if($.type==="array")Q=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")Q=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")Q=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")Q=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")Q=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else Q="Invalid input";break;case w.custom:Q="Invalid input";break;case w.invalid_intersection_types:Q="Intersection results could not be merged";break;case w.not_multiple_of:Q=`Number must be a multiple of ${$.multipleOf}`;break;case w.not_finite:Q="Number must be finite";break;default:Q=X.defaultError,L.assertNever($)}return{message:Q}},Q$;var T3=g(()=>{r$();I$();Q$=g1});function l1($){J0=$}function b$(){return J0}var J0;var t$=g(()=>{T3();J0=Q$});function N($,X){let Q=b$(),Y=T$({issueData:X,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,Q,Q===Q$?void 0:Q$].filter((G)=>!!G)});$.common.issues.push(Y)}class f{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,X){let Q=[];for(let Y of X){if(Y.status==="aborted")return A;if(Y.status==="dirty")$.dirty();Q.push(Y.value)}return{status:$.value,value:Q}}static async mergeObjectAsync($,X){let Q=[];for(let Y of X){let G=await Y.key,W=await Y.value;Q.push({key:G,value:W})}return f.mergeObjectSync($,Q)}static mergeObjectSync($,X){let Q={};for(let Y of X){let{key:G,value:W}=Y;if(G.status==="aborted")return A;if(W.status==="aborted")return A;if(G.status==="dirty")$.dirty();if(W.status==="dirty")$.dirty();if(G.value!=="__proto__"&&(typeof W.value!=="undefined"||Y.alwaysSet))Q[G.value]=W.value}return{status:$.value,value:Q}}}var T$=($)=>{let{data:X,path:Q,errorMaps:Y,issueData:G}=$,W=[...Q,...G.path||[]],H={...G,path:W};if(G.message!==void 0)return{...G,path:W,message:G.message};let B="",D=Y.filter((V)=>!!V).slice().reverse();for(let V of D)B=V(H,{data:X,defaultError:B}).message;return{...G,path:W,message:B}},m1,A,V$=($)=>({status:"dirty",value:$}),C=($)=>({status:"valid",value:$}),s$=($)=>$.status==="aborted",e$=($)=>$.status==="dirty",W$=($)=>$.status==="valid",U$=($)=>typeof Promise!=="undefined"&&$ instanceof Promise;var x3=g(()=>{t$();T3();m1=[];A=Object.freeze({status:"aborted"})});var W0=()=>{};var O;var H0=g(()=>{(function($){$.errToObj=(X)=>typeof X==="string"?{message:X}:X||{},$.toString=(X)=>typeof X==="string"?X:X?.message})(O||(O={}))});class n{constructor($,X,Q,Y){this._cachedPath=[],this.parent=$,this.data=X,this._path=Q,this._key=Y}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function U($){if(!$)return{};let{errorMap:X,invalid_type_error:Q,required_error:Y,description:G}=$;if(X&&(Q||Y))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(X)return{errorMap:X,description:G};return{errorMap:(H,B)=>{let{message:D}=$;if(H.code==="invalid_enum_value")return{message:D??B.defaultError};if(typeof B.data==="undefined")return{message:D??Y??B.defaultError};if(H.code!=="invalid_type")return{message:B.defaultError};return{message:D??Q??B.defaultError}},description:G}}class q{get description(){return this._def.description}_getType($){return t($.data)}_getOrReturnCtx($,X){return X||{common:$.parent.common,data:$.data,parsedType:t($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new f,ctx:{common:$.parent.common,data:$.data,parsedType:t($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let X=this._parse($);if(U$(X))throw new Error("Synchronous parse encountered promise.");return X}_parseAsync($){let X=this._parse($);return Promise.resolve(X)}parse($,X){let Q=this.safeParse($,X);if(Q.success)return Q.data;throw Q.error}safeParse($,X){let Q={common:{issues:[],async:X?.async??!1,contextualErrorMap:X?.errorMap},path:X?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:t($)},Y=this._parseSync({data:$,path:Q.path,parent:Q});return B0(Q,Y)}"~validate"($){let X={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:t($)};if(!this["~standard"].async)try{let Q=this._parseSync({data:$,path:[],parent:X});return W$(Q)?{value:Q.value}:{issues:X.common.issues}}catch(Q){if(Q?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;X.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:X}).then((Q)=>W$(Q)?{value:Q.value}:{issues:X.common.issues})}async parseAsync($,X){let Q=await this.safeParseAsync($,X);if(Q.success)return Q.data;throw Q.error}async safeParseAsync($,X){let Q={common:{issues:[],contextualErrorMap:X?.errorMap,async:!0},path:X?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:t($)},Y=this._parse({data:$,path:Q.path,parent:Q}),G=await(U$(Y)?Y:Promise.resolve(Y));return B0(Q,G)}refine($,X){let Q=(Y)=>{if(typeof X==="string"||typeof X==="undefined")return{message:X};else if(typeof X==="function")return X(Y);else return X};return this._refinement((Y,G)=>{let W=$(Y),H=()=>G.addIssue({code:w.custom,...Q(Y)});if(typeof Promise!=="undefined"&&W instanceof Promise)return W.then((B)=>{if(!B)return H(),!1;else return!0});if(!W)return H(),!1;else return!0})}refinement($,X){return this._refinement((Q,Y)=>{if(!$(Q))return Y.addIssue(typeof X==="function"?X(Q,Y):X),!1;else return!0})}_refinement($){return new p({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,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:(X)=>this["~validate"](X)}}optional(){return c.create(this,this._def)}nullable(){return G$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return u.create(this)}promise(){return A$.create(this,this._def)}or($){return F$.create([this,$],this._def)}and($){return z$.create(this,$,this._def)}transform($){return new p({...U(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:$}})}default($){let X=typeof $==="function"?$:()=>$;return new f$({...U(this._def),innerType:this,defaultValue:X,typeName:_.ZodDefault})}brand(){return new X3({typeName:_.ZodBranded,type:this,...U(this._def)})}catch($){let X=typeof $==="function"?$:()=>$;return new P$({...U(this._def),innerType:this,catchValue:X,typeName:_.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return l$.create(this,$)}readonly(){return C$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function _0($){let X="[0-5]\\d";if($.precision)X=`${X}\\.\\d{${$.precision}}`;else if($.precision==null)X=`${X}(\\.\\d+)?`;let Q=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${X})${Q}`}function G2($){return new RegExp(`^${_0($)}$`)}function M0($){let X=`${w0}T${_0($)}`,Q=[];if(Q.push($.local?"Z?":"Z"),$.offset)Q.push("([+-]\\d{2}:?\\d{2})");return X=`${X}(${Q.join("|")})`,new RegExp(`^${X}$`)}function J2($,X){if((X==="v4"||!X)&&t1.test($))return!0;if((X==="v6"||!X)&&e1.test($))return!0;return!1}function W2($,X){if(!d1.test($))return!1;try{let[Q]=$.split(".");if(!Q)return!1;let Y=Q.replace(/-/g,"+").replace(/_/g,"/").padEnd(Q.length+(4-Q.length%4)%4,"="),G=JSON.parse(atob(Y));if(typeof G!=="object"||G===null)return!1;if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(X&&G.alg!==X)return!1;return!0}catch{return!1}}function H2($,X){if((X==="v4"||!X)&&s1.test($))return!0;if((X==="v6"||!X)&&$2.test($))return!0;return!1}function B2($,X){let Q=($.toString().split(".")[1]||"").length,Y=(X.toString().split(".")[1]||"").length,G=Q>Y?Q:Y,W=Number.parseInt($.toFixed(G).replace(".","")),H=Number.parseInt(X.toFixed(G).replace(".",""));return W%H/10**G}function q$($){if($ instanceof F){let X={};for(let Q in $.shape){let Y=$.shape[Q];X[Q]=c.create(q$(Y))}return new F({...$._def,shape:()=>X})}else if($ instanceof u)return new u({...$._def,type:q$($.element)});else if($ instanceof c)return c.create(q$($.unwrap()));else if($ instanceof G$)return G$.create(q$($.unwrap()));else if($ instanceof e)return e.create($.items.map((X)=>q$(X)));else return $}function h3($,X){let Q=t($),Y=t(X);if($===X)return{valid:!0,data:$};else if(Q===M.object&&Y===M.object){let G=L.objectKeys(X),W=L.objectKeys($).filter((B)=>G.indexOf(B)!==-1),H={...$,...X};for(let B of W){let D=h3($[B],X[B]);if(!D.valid)return{valid:!1};H[B]=D.data}return{valid:!0,data:H}}else if(Q===M.array&&Y===M.array){if($.length!==X.length)return{valid:!1};let G=[];for(let W=0;W<$.length;W++){let H=$[W],B=X[W],D=h3(H,B);if(!D.valid)return{valid:!1};G.push(D.data)}return{valid:!0,data:G}}else if(Q===M.date&&Y===M.date&&+$===+X)return{valid:!0,data:$};else return{valid:!1}}function V0($,X){return new w$({values:$,typeName:_.ZodEnum,...U(X)})}function D0($,X){let Q=typeof $==="function"?$(X):typeof $==="string"?{message:$}:$;return typeof Q==="string"?{message:Q}:Q}function N0($,X={},Q){if($)return O$.create().superRefine((Y,G)=>{let W=$(Y);if(W instanceof Promise)return W.then((H)=>{if(!H){let B=D0(X,Y),D=B.fatal??Q??!0;G.addIssue({code:"custom",...B,fatal:D})}});if(!W){let H=D0(X,Y),B=H.fatal??Q??!0;G.addIssue({code:"custom",...H,fatal:B})}return});return O$.create()}var B0=($,X)=>{if(W$(X))return{success:!0,data:X.value};else{if(!$.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let Q=new h($.common.issues);return this._error=Q,this._error}}}},u1,c1,n1,p1,i1,d1,o1,a1,r1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",y3,t1,s1,e1,$2,X2,Q2,w0="((\\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])))",Y2,m,B$,D$,L$,N$,x$,E$,S$,O$,H$,s,y$,u,F,F$,Y$=($)=>{if($ instanceof R$)return Y$($.schema);else if($ instanceof p)return Y$($.innerType());else if($ instanceof v$)return[$.value];else if($ instanceof w$)return $.options;else if($ instanceof k$)return L.objectValues($.enum);else if($ instanceof f$)return Y$($._def.innerType);else if($ instanceof E$)return[void 0];else if($ instanceof S$)return[null];else if($ instanceof c)return[void 0,...Y$($.unwrap())];else if($ instanceof G$)return[null,...Y$($.unwrap())];else if($ instanceof X3)return Y$($.unwrap());else if($ instanceof C$)return Y$($.unwrap());else if($ instanceof P$)return Y$($._def.innerType);else return[]},$3,z$,e,h$,Z$,j$,K$,R$,v$,w$,k$,A$,p,c,G$,f$,P$,g$,D2,X3,l$,C$,w2,_,_2=($,X={message:`Input not instance of ${$.name}`})=>N0((Q)=>Q instanceof $,X),O0,j0,M2,V2,A0,N2,O2,j2,A2,b2,U2,q2,K2,L2,E2,S2,F2,z2,R2,v2,k2,f2,P2,C2,I2,T2,x2,y2,h2,Z2,g2,l2,m2,u2,c2=()=>O0().optional(),n2=()=>j0().optional(),p2=()=>A0().optional(),i2,d2;var b0=g(()=>{r$();t$();H0();x3();I$();u1=/^c[^\s-]{8,}$/i,c1=/^[0-9a-z]+$/,n1=/^[0-9A-HJKMNP-TV-Z]{26}$/i,p1=/^[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,i1=/^[a-z0-9_-]{21}$/i,d1=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,o1=/^[-+]?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)?)??$/,a1=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,t1=/^(?:(?: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])$/,s1=/^(?:(?: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])$/,e1=/^(([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]))$/,$2=/^(([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])$/,X2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Q2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Y2=new RegExp(`^${w0}$`);m=class m extends q{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==M.string){let G=this._getOrReturnCtx($);return N(G,{code:w.invalid_type,expected:M.string,received:G.parsedType}),A}let Q=new f,Y=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.length<G.value)Y=this._getOrReturnCtx($,Y),N(Y,{code:w.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),Q.dirty()}else if(G.kind==="max"){if($.data.length>G.value)Y=this._getOrReturnCtx($,Y),N(Y,{code:w.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),Q.dirty()}else if(G.kind==="length"){let W=$.data.length>G.value,H=$.data.length<G.value;if(W||H){if(Y=this._getOrReturnCtx($,Y),W)N(Y,{code:w.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(H)N(Y,{code:w.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});Q.dirty()}}else if(G.kind==="email"){if(!a1.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"email",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="emoji"){if(!y3)y3=new RegExp(r1,"u");if(!y3.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"emoji",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="uuid"){if(!p1.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"uuid",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="nanoid"){if(!i1.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"nanoid",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="cuid"){if(!u1.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"cuid",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="cuid2"){if(!c1.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"cuid2",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="ulid"){if(!n1.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"ulid",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="url")try{new URL($.data)}catch{Y=this._getOrReturnCtx($,Y),N(Y,{validation:"url",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"regex",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="trim")$.data=$.data.trim();else if(G.kind==="includes"){if(!$.data.includes(G.value,G.position))Y=this._getOrReturnCtx($,Y),N(Y,{code:w.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),Q.dirty()}else if(G.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(G.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(G.kind==="startsWith"){if(!$.data.startsWith(G.value))Y=this._getOrReturnCtx($,Y),N(Y,{code:w.invalid_string,validation:{startsWith:G.value},message:G.message}),Q.dirty()}else if(G.kind==="endsWith"){if(!$.data.endsWith(G.value))Y=this._getOrReturnCtx($,Y),N(Y,{code:w.invalid_string,validation:{endsWith:G.value},message:G.message}),Q.dirty()}else if(G.kind==="datetime"){if(!M0(G).test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{code:w.invalid_string,validation:"datetime",message:G.message}),Q.dirty()}else if(G.kind==="date"){if(!Y2.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{code:w.invalid_string,validation:"date",message:G.message}),Q.dirty()}else if(G.kind==="time"){if(!G2(G).test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{code:w.invalid_string,validation:"time",message:G.message}),Q.dirty()}else if(G.kind==="duration"){if(!o1.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"duration",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="ip"){if(!J2($.data,G.version))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"ip",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="jwt"){if(!W2($.data,G.alg))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"jwt",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="cidr"){if(!H2($.data,G.version))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"cidr",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="base64"){if(!X2.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"base64",code:w.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="base64url"){if(!Q2.test($.data))Y=this._getOrReturnCtx($,Y),N(Y,{validation:"base64url",code:w.invalid_string,message:G.message}),Q.dirty()}else L.assertNever(G);return{status:Q.value,value:$.data}}_regex($,X,Q){return this.refinement((Y)=>$.test(Y),{validation:X,code:w.invalid_string,...O.errToObj(Q)})}_addCheck($){return new m({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...O.errToObj($)})}url($){return this._addCheck({kind:"url",...O.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...O.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...O.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...O.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...O.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...O.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...O.errToObj($)})}base64($){return this._addCheck({kind:"base64",...O.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...O.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...O.errToObj($)})}ip($){return this._addCheck({kind:"ip",...O.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...O.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision==="undefined"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...O.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision==="undefined"?null:$?.precision,...O.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...O.errToObj($)})}regex($,X){return this._addCheck({kind:"regex",regex:$,...O.errToObj(X)})}includes($,X){return this._addCheck({kind:"includes",value:$,position:X?.position,...O.errToObj(X?.message)})}startsWith($,X){return this._addCheck({kind:"startsWith",value:$,...O.errToObj(X)})}endsWith($,X){return this._addCheck({kind:"endsWith",value:$,...O.errToObj(X)})}min($,X){return this._addCheck({kind:"min",value:$,...O.errToObj(X)})}max($,X){return this._addCheck({kind:"max",value:$,...O.errToObj(X)})}length($,X){return this._addCheck({kind:"length",value:$,...O.errToObj(X)})}nonempty($){return this.min(1,O.errToObj($))}trim(){return new m({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new m({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new m({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let X of this._def.checks)if(X.kind==="min"){if($===null||X.value>$)$=X.value}return $}get maxLength(){let $=null;for(let X of this._def.checks)if(X.kind==="max"){if($===null||X.value<$)$=X.value}return $}};m.create=($)=>{return new m({checks:[],typeName:_.ZodString,coerce:$?.coerce??!1,...U($)})};B$=class B$ extends q{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==M.number){let G=this._getOrReturnCtx($);return N(G,{code:w.invalid_type,expected:M.number,received:G.parsedType}),A}let Q=void 0,Y=new f;for(let G of this._def.checks)if(G.kind==="int"){if(!L.isInteger($.data))Q=this._getOrReturnCtx($,Q),N(Q,{code:w.invalid_type,expected:"integer",received:"float",message:G.message}),Y.dirty()}else if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)Q=this._getOrReturnCtx($,Q),N(Q,{code:w.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),Y.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)Q=this._getOrReturnCtx($,Q),N(Q,{code:w.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),Y.dirty()}else if(G.kind==="multipleOf"){if(B2($.data,G.value)!==0)Q=this._getOrReturnCtx($,Q),N(Q,{code:w.not_multiple_of,multipleOf:G.value,message:G.message}),Y.dirty()}else if(G.kind==="finite"){if(!Number.isFinite($.data))Q=this._getOrReturnCtx($,Q),N(Q,{code:w.not_finite,message:G.message}),Y.dirty()}else L.assertNever(G);return{status:Y.value,value:$.data}}gte($,X){return this.setLimit("min",$,!0,O.toString(X))}gt($,X){return this.setLimit("min",$,!1,O.toString(X))}lte($,X){return this.setLimit("max",$,!0,O.toString(X))}lt($,X){return this.setLimit("max",$,!1,O.toString(X))}setLimit($,X,Q,Y){return new B$({...this._def,checks:[...this._def.checks,{kind:$,value:X,inclusive:Q,message:O.toString(Y)}]})}_addCheck($){return new B$({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:O.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString($)})}multipleOf($,X){return this._addCheck({kind:"multipleOf",value:$,message:O.toString(X)})}finite($){return this._addCheck({kind:"finite",message:O.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString($)})}get minValue(){let $=null;for(let X of this._def.checks)if(X.kind==="min"){if($===null||X.value>$)$=X.value}return $}get maxValue(){let $=null;for(let X of this._def.checks)if(X.kind==="max"){if($===null||X.value<$)$=X.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&L.isInteger($.value))}get isFinite(){let $=null,X=null;for(let Q of this._def.checks)if(Q.kind==="finite"||Q.kind==="int"||Q.kind==="multipleOf")return!0;else if(Q.kind==="min"){if(X===null||Q.value>X)X=Q.value}else if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return Number.isFinite(X)&&Number.isFinite($)}};B$.create=($)=>{return new B$({checks:[],typeName:_.ZodNumber,coerce:$?.coerce||!1,...U($)})};D$=class D$ extends q{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==M.bigint)return this._getInvalidInput($);let Q=void 0,Y=new f;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)Q=this._getOrReturnCtx($,Q),N(Q,{code:w.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),Y.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)Q=this._getOrReturnCtx($,Q),N(Q,{code:w.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),Y.dirty()}else if(G.kind==="multipleOf"){if($.data%G.value!==BigInt(0))Q=this._getOrReturnCtx($,Q),N(Q,{code:w.not_multiple_of,multipleOf:G.value,message:G.message}),Y.dirty()}else L.assertNever(G);return{status:Y.value,value:$.data}}_getInvalidInput($){let X=this._getOrReturnCtx($);return N(X,{code:w.invalid_type,expected:M.bigint,received:X.parsedType}),A}gte($,X){return this.setLimit("min",$,!0,O.toString(X))}gt($,X){return this.setLimit("min",$,!1,O.toString(X))}lte($,X){return this.setLimit("max",$,!0,O.toString(X))}lt($,X){return this.setLimit("max",$,!1,O.toString(X))}setLimit($,X,Q,Y){return new D$({...this._def,checks:[...this._def.checks,{kind:$,value:X,inclusive:Q,message:O.toString(Y)}]})}_addCheck($){return new D$({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString($)})}multipleOf($,X){return this._addCheck({kind:"multipleOf",value:$,message:O.toString(X)})}get minValue(){let $=null;for(let X of this._def.checks)if(X.kind==="min"){if($===null||X.value>$)$=X.value}return $}get maxValue(){let $=null;for(let X of this._def.checks)if(X.kind==="max"){if($===null||X.value<$)$=X.value}return $}};D$.create=($)=>{return new D$({checks:[],typeName:_.ZodBigInt,coerce:$?.coerce??!1,...U($)})};L$=class L$ extends q{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==M.boolean){let Q=this._getOrReturnCtx($);return N(Q,{code:w.invalid_type,expected:M.boolean,received:Q.parsedType}),A}return C($.data)}};L$.create=($)=>{return new L$({typeName:_.ZodBoolean,coerce:$?.coerce||!1,...U($)})};N$=class N$ extends q{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==M.date){let G=this._getOrReturnCtx($);return N(G,{code:w.invalid_type,expected:M.date,received:G.parsedType}),A}if(Number.isNaN($.data.getTime())){let G=this._getOrReturnCtx($);return N(G,{code:w.invalid_date}),A}let Q=new f,Y=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.getTime()<G.value)Y=this._getOrReturnCtx($,Y),N(Y,{code:w.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),Q.dirty()}else if(G.kind==="max"){if($.data.getTime()>G.value)Y=this._getOrReturnCtx($,Y),N(Y,{code:w.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),Q.dirty()}else L.assertNever(G);return{status:Q.value,value:new Date($.data.getTime())}}_addCheck($){return new N$({...this._def,checks:[...this._def.checks,$]})}min($,X){return this._addCheck({kind:"min",value:$.getTime(),message:O.toString(X)})}max($,X){return this._addCheck({kind:"max",value:$.getTime(),message:O.toString(X)})}get minDate(){let $=null;for(let X of this._def.checks)if(X.kind==="min"){if($===null||X.value>$)$=X.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let X of this._def.checks)if(X.kind==="max"){if($===null||X.value<$)$=X.value}return $!=null?new Date($):null}};N$.create=($)=>{return new N$({checks:[],coerce:$?.coerce||!1,typeName:_.ZodDate,...U($)})};x$=class x$ extends q{_parse($){if(this._getType($)!==M.symbol){let Q=this._getOrReturnCtx($);return N(Q,{code:w.invalid_type,expected:M.symbol,received:Q.parsedType}),A}return C($.data)}};x$.create=($)=>{return new x$({typeName:_.ZodSymbol,...U($)})};E$=class E$ extends q{_parse($){if(this._getType($)!==M.undefined){let Q=this._getOrReturnCtx($);return N(Q,{code:w.invalid_type,expected:M.undefined,received:Q.parsedType}),A}return C($.data)}};E$.create=($)=>{return new E$({typeName:_.ZodUndefined,...U($)})};S$=class S$ extends q{_parse($){if(this._getType($)!==M.null){let Q=this._getOrReturnCtx($);return N(Q,{code:w.invalid_type,expected:M.null,received:Q.parsedType}),A}return C($.data)}};S$.create=($)=>{return new S$({typeName:_.ZodNull,...U($)})};O$=class O$ extends q{constructor(){super(...arguments);this._any=!0}_parse($){return C($.data)}};O$.create=($)=>{return new O$({typeName:_.ZodAny,...U($)})};H$=class H$ extends q{constructor(){super(...arguments);this._unknown=!0}_parse($){return C($.data)}};H$.create=($)=>{return new H$({typeName:_.ZodUnknown,...U($)})};s=class s extends q{_parse($){let X=this._getOrReturnCtx($);return N(X,{code:w.invalid_type,expected:M.never,received:X.parsedType}),A}};s.create=($)=>{return new s({typeName:_.ZodNever,...U($)})};y$=class y$ extends q{_parse($){if(this._getType($)!==M.undefined){let Q=this._getOrReturnCtx($);return N(Q,{code:w.invalid_type,expected:M.void,received:Q.parsedType}),A}return C($.data)}};y$.create=($)=>{return new y$({typeName:_.ZodVoid,...U($)})};u=class u extends q{_parse($){let{ctx:X,status:Q}=this._processInputParams($),Y=this._def;if(X.parsedType!==M.array)return N(X,{code:w.invalid_type,expected:M.array,received:X.parsedType}),A;if(Y.exactLength!==null){let W=X.data.length>Y.exactLength.value,H=X.data.length<Y.exactLength.value;if(W||H)N(X,{code:W?w.too_big:w.too_small,minimum:H?Y.exactLength.value:void 0,maximum:W?Y.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Y.exactLength.message}),Q.dirty()}if(Y.minLength!==null){if(X.data.length<Y.minLength.value)N(X,{code:w.too_small,minimum:Y.minLength.value,type:"array",inclusive:!0,exact:!1,message:Y.minLength.message}),Q.dirty()}if(Y.maxLength!==null){if(X.data.length>Y.maxLength.value)N(X,{code:w.too_big,maximum:Y.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Y.maxLength.message}),Q.dirty()}if(X.common.async)return Promise.all([...X.data].map((W,H)=>{return Y.type._parseAsync(new n(X,W,X.path,H))})).then((W)=>{return f.mergeArray(Q,W)});let G=[...X.data].map((W,H)=>{return Y.type._parseSync(new n(X,W,X.path,H))});return f.mergeArray(Q,G)}get element(){return this._def.type}min($,X){return new u({...this._def,minLength:{value:$,message:O.toString(X)}})}max($,X){return new u({...this._def,maxLength:{value:$,message:O.toString(X)}})}length($,X){return new u({...this._def,exactLength:{value:$,message:O.toString(X)}})}nonempty($){return this.min(1,$)}};u.create=($,X)=>{return new u({type:$,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...U(X)})};F=class F extends q{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),X=L.objectKeys($);return this._cached={shape:$,keys:X},this._cached}_parse($){if(this._getType($)!==M.object){let D=this._getOrReturnCtx($);return N(D,{code:w.invalid_type,expected:M.object,received:D.parsedType}),A}let{status:Q,ctx:Y}=this._processInputParams($),{shape:G,keys:W}=this._getCached(),H=[];if(!(this._def.catchall instanceof s&&this._def.unknownKeys==="strip")){for(let D in Y.data)if(!W.includes(D))H.push(D)}let B=[];for(let D of W){let V=G[D],j=Y.data[D];B.push({key:{status:"valid",value:D},value:V._parse(new n(Y,j,Y.path,D)),alwaysSet:D in Y.data})}if(this._def.catchall instanceof s){let D=this._def.unknownKeys;if(D==="passthrough")for(let V of H)B.push({key:{status:"valid",value:V},value:{status:"valid",value:Y.data[V]}});else if(D==="strict"){if(H.length>0)N(Y,{code:w.unrecognized_keys,keys:H}),Q.dirty()}else if(D==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let D=this._def.catchall;for(let V of H){let j=Y.data[V];B.push({key:{status:"valid",value:V},value:D._parse(new n(Y,j,Y.path,V)),alwaysSet:V in Y.data})}}if(Y.common.async)return Promise.resolve().then(async()=>{let D=[];for(let V of B){let j=await V.key,P=await V.value;D.push({key:j,value:P,alwaysSet:V.alwaysSet})}return D}).then((D)=>{return f.mergeObjectSync(Q,D)});else return f.mergeObjectSync(Q,B)}get shape(){return this._def.shape()}strict($){return O.errToObj,new F({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(X,Q)=>{let Y=this._def.errorMap?.(X,Q).message??Q.defaultError;if(X.code==="unrecognized_keys")return{message:O.errToObj($).message??Y};return{message:Y}}}:{}})}strip(){return new F({...this._def,unknownKeys:"strip"})}passthrough(){return new F({...this._def,unknownKeys:"passthrough"})}extend($){return new F({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new F({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:_.ZodObject})}setKey($,X){return this.augment({[$]:X})}catchall($){return new F({...this._def,catchall:$})}pick($){let X={};for(let Q of L.objectKeys($))if($[Q]&&this.shape[Q])X[Q]=this.shape[Q];return new F({...this._def,shape:()=>X})}omit($){let X={};for(let Q of L.objectKeys(this.shape))if(!$[Q])X[Q]=this.shape[Q];return new F({...this._def,shape:()=>X})}deepPartial(){return q$(this)}partial($){let X={};for(let Q of L.objectKeys(this.shape)){let Y=this.shape[Q];if($&&!$[Q])X[Q]=Y;else X[Q]=Y.optional()}return new F({...this._def,shape:()=>X})}required($){let X={};for(let Q of L.objectKeys(this.shape))if($&&!$[Q])X[Q]=this.shape[Q];else{let G=this.shape[Q];while(G instanceof c)G=G._def.innerType;X[Q]=G}return new F({...this._def,shape:()=>X})}keyof(){return V0(L.objectKeys(this.shape))}};F.create=($,X)=>{return new F({shape:()=>$,unknownKeys:"strip",catchall:s.create(),typeName:_.ZodObject,...U(X)})};F.strictCreate=($,X)=>{return new F({shape:()=>$,unknownKeys:"strict",catchall:s.create(),typeName:_.ZodObject,...U(X)})};F.lazycreate=($,X)=>{return new F({shape:$,unknownKeys:"strip",catchall:s.create(),typeName:_.ZodObject,...U(X)})};F$=class F$ extends q{_parse($){let{ctx:X}=this._processInputParams($),Q=this._def.options;function Y(G){for(let H of G)if(H.result.status==="valid")return H.result;for(let H of G)if(H.result.status==="dirty")return X.common.issues.push(...H.ctx.common.issues),H.result;let W=G.map((H)=>new h(H.ctx.common.issues));return N(X,{code:w.invalid_union,unionErrors:W}),A}if(X.common.async)return Promise.all(Q.map(async(G)=>{let W={...X,common:{...X.common,issues:[]},parent:null};return{result:await G._parseAsync({data:X.data,path:X.path,parent:W}),ctx:W}})).then(Y);else{let G=void 0,W=[];for(let B of Q){let D={...X,common:{...X.common,issues:[]},parent:null},V=B._parseSync({data:X.data,path:X.path,parent:D});if(V.status==="valid")return V;else if(V.status==="dirty"&&!G)G={result:V,ctx:D};if(D.common.issues.length)W.push(D.common.issues)}if(G)return X.common.issues.push(...G.ctx.common.issues),G.result;let H=W.map((B)=>new h(B));return N(X,{code:w.invalid_union,unionErrors:H}),A}}get options(){return this._def.options}};F$.create=($,X)=>{return new F$({options:$,typeName:_.ZodUnion,...U(X)})};$3=class $3 extends q{_parse($){let{ctx:X}=this._processInputParams($);if(X.parsedType!==M.object)return N(X,{code:w.invalid_type,expected:M.object,received:X.parsedType}),A;let Q=this.discriminator,Y=X.data[Q],G=this.optionsMap.get(Y);if(!G)return N(X,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Q]}),A;if(X.common.async)return G._parseAsync({data:X.data,path:X.path,parent:X});else return G._parseSync({data:X.data,path:X.path,parent:X})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,X,Q){let Y=new Map;for(let G of X){let W=Y$(G.shape[$]);if(!W.length)throw new Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let H of W){if(Y.has(H))throw new Error(`Discriminator property ${String($)} has duplicate value ${String(H)}`);Y.set(H,G)}}return new $3({typeName:_.ZodDiscriminatedUnion,discriminator:$,options:X,optionsMap:Y,...U(Q)})}};z$=class z$ extends q{_parse($){let{status:X,ctx:Q}=this._processInputParams($),Y=(G,W)=>{if(s$(G)||s$(W))return A;let H=h3(G.value,W.value);if(!H.valid)return N(Q,{code:w.invalid_intersection_types}),A;if(e$(G)||e$(W))X.dirty();return{status:X.value,value:H.data}};if(Q.common.async)return Promise.all([this._def.left._parseAsync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseAsync({data:Q.data,path:Q.path,parent:Q})]).then(([G,W])=>Y(G,W));else return Y(this._def.left._parseSync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseSync({data:Q.data,path:Q.path,parent:Q}))}};z$.create=($,X,Q)=>{return new z$({left:$,right:X,typeName:_.ZodIntersection,...U(Q)})};e=class e extends q{_parse($){let{status:X,ctx:Q}=this._processInputParams($);if(Q.parsedType!==M.array)return N(Q,{code:w.invalid_type,expected:M.array,received:Q.parsedType}),A;if(Q.data.length<this._def.items.length)return N(Q,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),A;if(!this._def.rest&&Q.data.length>this._def.items.length)N(Q,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X.dirty();let G=[...Q.data].map((W,H)=>{let B=this._def.items[H]||this._def.rest;if(!B)return null;return B._parse(new n(Q,W,Q.path,H))}).filter((W)=>!!W);if(Q.common.async)return Promise.all(G).then((W)=>{return f.mergeArray(X,W)});else return f.mergeArray(X,G)}get items(){return this._def.items}rest($){return new e({...this._def,rest:$})}};e.create=($,X)=>{if(!Array.isArray($))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new e({items:$,typeName:_.ZodTuple,rest:null,...U(X)})};h$=class h$ extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:X,ctx:Q}=this._processInputParams($);if(Q.parsedType!==M.object)return N(Q,{code:w.invalid_type,expected:M.object,received:Q.parsedType}),A;let Y=[],G=this._def.keyType,W=this._def.valueType;for(let H in Q.data)Y.push({key:G._parse(new n(Q,H,Q.path,H)),value:W._parse(new n(Q,Q.data[H],Q.path,H)),alwaysSet:H in Q.data});if(Q.common.async)return f.mergeObjectAsync(X,Y);else return f.mergeObjectSync(X,Y)}get element(){return this._def.valueType}static create($,X,Q){if(X instanceof q)return new h$({keyType:$,valueType:X,typeName:_.ZodRecord,...U(Q)});return new h$({keyType:m.create(),valueType:$,typeName:_.ZodRecord,...U(X)})}};Z$=class Z$ extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:X,ctx:Q}=this._processInputParams($);if(Q.parsedType!==M.map)return N(Q,{code:w.invalid_type,expected:M.map,received:Q.parsedType}),A;let Y=this._def.keyType,G=this._def.valueType,W=[...Q.data.entries()].map(([H,B],D)=>{return{key:Y._parse(new n(Q,H,Q.path,[D,"key"])),value:G._parse(new n(Q,B,Q.path,[D,"value"]))}});if(Q.common.async){let H=new Map;return Promise.resolve().then(async()=>{for(let B of W){let D=await B.key,V=await B.value;if(D.status==="aborted"||V.status==="aborted")return A;if(D.status==="dirty"||V.status==="dirty")X.dirty();H.set(D.value,V.value)}return{status:X.value,value:H}})}else{let H=new Map;for(let B of W){let{key:D,value:V}=B;if(D.status==="aborted"||V.status==="aborted")return A;if(D.status==="dirty"||V.status==="dirty")X.dirty();H.set(D.value,V.value)}return{status:X.value,value:H}}}};Z$.create=($,X,Q)=>{return new Z$({valueType:X,keyType:$,typeName:_.ZodMap,...U(Q)})};j$=class j$ extends q{_parse($){let{status:X,ctx:Q}=this._processInputParams($);if(Q.parsedType!==M.set)return N(Q,{code:w.invalid_type,expected:M.set,received:Q.parsedType}),A;let Y=this._def;if(Y.minSize!==null){if(Q.data.size<Y.minSize.value)N(Q,{code:w.too_small,minimum:Y.minSize.value,type:"set",inclusive:!0,exact:!1,message:Y.minSize.message}),X.dirty()}if(Y.maxSize!==null){if(Q.data.size>Y.maxSize.value)N(Q,{code:w.too_big,maximum:Y.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Y.maxSize.message}),X.dirty()}let G=this._def.valueType;function W(B){let D=new Set;for(let V of B){if(V.status==="aborted")return A;if(V.status==="dirty")X.dirty();D.add(V.value)}return{status:X.value,value:D}}let H=[...Q.data.values()].map((B,D)=>G._parse(new n(Q,B,Q.path,D)));if(Q.common.async)return Promise.all(H).then((B)=>W(B));else return W(H)}min($,X){return new j$({...this._def,minSize:{value:$,message:O.toString(X)}})}max($,X){return new j$({...this._def,maxSize:{value:$,message:O.toString(X)}})}size($,X){return this.min($,X).max($,X)}nonempty($){return this.min(1,$)}};j$.create=($,X)=>{return new j$({valueType:$,minSize:null,maxSize:null,typeName:_.ZodSet,...U(X)})};K$=class K$ extends q{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:X}=this._processInputParams($);if(X.parsedType!==M.function)return N(X,{code:w.invalid_type,expected:M.function,received:X.parsedType}),A;function Q(H,B){return T$({data:H,path:X.path,errorMaps:[X.common.contextualErrorMap,X.schemaErrorMap,b$(),Q$].filter((D)=>!!D),issueData:{code:w.invalid_arguments,argumentsError:B}})}function Y(H,B){return T$({data:H,path:X.path,errorMaps:[X.common.contextualErrorMap,X.schemaErrorMap,b$(),Q$].filter((D)=>!!D),issueData:{code:w.invalid_return_type,returnTypeError:B}})}let G={errorMap:X.common.contextualErrorMap},W=X.data;if(this._def.returns instanceof A$){let H=this;return C(async function(...B){let D=new h([]),V=await H._def.args.parseAsync(B,G).catch((I)=>{throw D.addIssue(Q(B,I)),D}),j=await Reflect.apply(W,this,V);return await H._def.returns._def.type.parseAsync(j,G).catch((I)=>{throw D.addIssue(Y(j,I)),D})})}else{let H=this;return C(function(...B){let D=H._def.args.safeParse(B,G);if(!D.success)throw new h([Q(B,D.error)]);let V=Reflect.apply(W,this,D.data),j=H._def.returns.safeParse(V,G);if(!j.success)throw new h([Y(V,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new K$({...this._def,args:e.create($).rest(H$.create())})}returns($){return new K$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,X,Q){return new K$({args:$?$:e.create([]).rest(H$.create()),returns:X||H$.create(),typeName:_.ZodFunction,...U(Q)})}};R$=class R$ extends q{get schema(){return this._def.getter()}_parse($){let{ctx:X}=this._processInputParams($);return this._def.getter()._parse({data:X.data,path:X.path,parent:X})}};R$.create=($,X)=>{return new R$({getter:$,typeName:_.ZodLazy,...U(X)})};v$=class v$ extends q{_parse($){if($.data!==this._def.value){let X=this._getOrReturnCtx($);return N(X,{received:X.data,code:w.invalid_literal,expected:this._def.value}),A}return{status:"valid",value:$.data}}get value(){return this._def.value}};v$.create=($,X)=>{return new v$({value:$,typeName:_.ZodLiteral,...U(X)})};w$=class w$ extends q{_parse($){if(typeof $.data!=="string"){let X=this._getOrReturnCtx($),Q=this._def.values;return N(X,{expected:L.joinValues(Q),received:X.parsedType,code:w.invalid_type}),A}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let X=this._getOrReturnCtx($),Q=this._def.values;return N(X,{received:X.data,code:w.invalid_enum_value,options:Q}),A}return C($.data)}get options(){return this._def.values}get enum(){let $={};for(let X of this._def.values)$[X]=X;return $}get Values(){let $={};for(let X of this._def.values)$[X]=X;return $}get Enum(){let $={};for(let X of this._def.values)$[X]=X;return $}extract($,X=this._def){return w$.create($,{...this._def,...X})}exclude($,X=this._def){return w$.create(this.options.filter((Q)=>!$.includes(Q)),{...this._def,...X})}};w$.create=V0;k$=class k$ extends q{_parse($){let X=L.getValidEnumValues(this._def.values),Q=this._getOrReturnCtx($);if(Q.parsedType!==M.string&&Q.parsedType!==M.number){let Y=L.objectValues(X);return N(Q,{expected:L.joinValues(Y),received:Q.parsedType,code:w.invalid_type}),A}if(!this._cache)this._cache=new Set(L.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let Y=L.objectValues(X);return N(Q,{received:Q.data,code:w.invalid_enum_value,options:Y}),A}return C($.data)}get enum(){return this._def.values}};k$.create=($,X)=>{return new k$({values:$,typeName:_.ZodNativeEnum,...U(X)})};A$=class A$ extends q{unwrap(){return this._def.type}_parse($){let{ctx:X}=this._processInputParams($);if(X.parsedType!==M.promise&&X.common.async===!1)return N(X,{code:w.invalid_type,expected:M.promise,received:X.parsedType}),A;let Q=X.parsedType===M.promise?X.data:Promise.resolve(X.data);return C(Q.then((Y)=>{return this._def.type.parseAsync(Y,{path:X.path,errorMap:X.common.contextualErrorMap})}))}};A$.create=($,X)=>{return new A$({type:$,typeName:_.ZodPromise,...U(X)})};p=class p extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:X,ctx:Q}=this._processInputParams($),Y=this._def.effect||null,G={addIssue:(W)=>{if(N(Q,W),W.fatal)X.abort();else X.dirty()},get path(){return Q.path}};if(G.addIssue=G.addIssue.bind(G),Y.type==="preprocess"){let W=Y.transform(Q.data,G);if(Q.common.async)return Promise.resolve(W).then(async(H)=>{if(X.value==="aborted")return A;let B=await this._def.schema._parseAsync({data:H,path:Q.path,parent:Q});if(B.status==="aborted")return A;if(B.status==="dirty")return V$(B.value);if(X.value==="dirty")return V$(B.value);return B});else{if(X.value==="aborted")return A;let H=this._def.schema._parseSync({data:W,path:Q.path,parent:Q});if(H.status==="aborted")return A;if(H.status==="dirty")return V$(H.value);if(X.value==="dirty")return V$(H.value);return H}}if(Y.type==="refinement"){let W=(H)=>{let B=Y.refinement(H,G);if(Q.common.async)return Promise.resolve(B);if(B instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return H};if(Q.common.async===!1){let H=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(H.status==="aborted")return A;if(H.status==="dirty")X.dirty();return W(H.value),{status:X.value,value:H.value}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((H)=>{if(H.status==="aborted")return A;if(H.status==="dirty")X.dirty();return W(H.value).then(()=>{return{status:X.value,value:H.value}})})}if(Y.type==="transform")if(Q.common.async===!1){let W=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(!W$(W))return A;let H=Y.transform(W.value,G);if(H instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:X.value,value:H}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((W)=>{if(!W$(W))return A;return Promise.resolve(Y.transform(W.value,G)).then((H)=>({status:X.value,value:H}))});L.assertNever(Y)}};p.create=($,X,Q)=>{return new p({schema:$,typeName:_.ZodEffects,effect:X,...U(Q)})};p.createWithPreprocess=($,X,Q)=>{return new p({schema:X,effect:{type:"preprocess",transform:$},typeName:_.ZodEffects,...U(Q)})};c=class c extends q{_parse($){if(this._getType($)===M.undefined)return C(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};c.create=($,X)=>{return new c({innerType:$,typeName:_.ZodOptional,...U(X)})};G$=class G$ extends q{_parse($){if(this._getType($)===M.null)return C(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};G$.create=($,X)=>{return new G$({innerType:$,typeName:_.ZodNullable,...U(X)})};f$=class f$ extends q{_parse($){let{ctx:X}=this._processInputParams($),Q=X.data;if(X.parsedType===M.undefined)Q=this._def.defaultValue();return this._def.innerType._parse({data:Q,path:X.path,parent:X})}removeDefault(){return this._def.innerType}};f$.create=($,X)=>{return new f$({innerType:$,typeName:_.ZodDefault,defaultValue:typeof X.default==="function"?X.default:()=>X.default,...U(X)})};P$=class P$ extends q{_parse($){let{ctx:X}=this._processInputParams($),Q={...X,common:{...X.common,issues:[]}},Y=this._def.innerType._parse({data:Q.data,path:Q.path,parent:{...Q}});if(U$(Y))return Y.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new h(Q.common.issues)},input:Q.data})}});else return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new h(Q.common.issues)},input:Q.data})}}removeCatch(){return this._def.innerType}};P$.create=($,X)=>{return new P$({innerType:$,typeName:_.ZodCatch,catchValue:typeof X.catch==="function"?X.catch:()=>X.catch,...U(X)})};g$=class g$ extends q{_parse($){if(this._getType($)!==M.nan){let Q=this._getOrReturnCtx($);return N(Q,{code:w.invalid_type,expected:M.nan,received:Q.parsedType}),A}return{status:"valid",value:$.data}}};g$.create=($)=>{return new g$({typeName:_.ZodNaN,...U($)})};D2=Symbol("zod_brand");X3=class X3 extends q{_parse($){let{ctx:X}=this._processInputParams($),Q=X.data;return this._def.type._parse({data:Q,path:X.path,parent:X})}unwrap(){return this._def.type}};l$=class l$ extends q{_parse($){let{status:X,ctx:Q}=this._processInputParams($);if(Q.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:Q.data,path:Q.path,parent:Q});if(G.status==="aborted")return A;if(G.status==="dirty")return X.dirty(),V$(G.value);else return this._def.out._parseAsync({data:G.value,path:Q.path,parent:Q})})();else{let Y=this._def.in._parseSync({data:Q.data,path:Q.path,parent:Q});if(Y.status==="aborted")return A;if(Y.status==="dirty")return X.dirty(),{status:"dirty",value:Y.value};else return this._def.out._parseSync({data:Y.value,path:Q.path,parent:Q})}}static create($,X){return new l$({in:$,out:X,typeName:_.ZodPipeline})}};C$=class C$ extends q{_parse($){let X=this._def.innerType._parse($),Q=(Y)=>{if(W$(Y))Y.value=Object.freeze(Y.value);return Y};return U$(X)?X.then((Y)=>Q(Y)):Q(X)}unwrap(){return this._def.innerType}};C$.create=($,X)=>{return new C$({innerType:$,typeName:_.ZodReadonly,...U(X)})};w2={object:F.lazycreate};(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(_||(_={}));O0=m.create,j0=B$.create,M2=g$.create,V2=D$.create,A0=L$.create,N2=N$.create,O2=x$.create,j2=E$.create,A2=S$.create,b2=O$.create,U2=H$.create,q2=s.create,K2=y$.create,L2=u.create,E2=F.create,S2=F.strictCreate,F2=F$.create,z2=$3.create,R2=z$.create,v2=e.create,k2=h$.create,f2=Z$.create,P2=j$.create,C2=K$.create,I2=R$.create,T2=v$.create,x2=w$.create,y2=k$.create,h2=A$.create,Z2=p.create,g2=c.create,l2=G$.create,m2=p.createWithPreprocess,u2=l$.create,i2={string:($)=>m.create({...$,coerce:!0}),number:($)=>B$.create({...$,coerce:!0}),boolean:($)=>L$.create({...$,coerce:!0}),bigint:($)=>D$.create({...$,coerce:!0}),date:($)=>N$.create({...$,coerce:!0})},d2=A});var J={};h1(J,{void:()=>K2,util:()=>L,unknown:()=>U2,union:()=>F2,undefined:()=>j2,tuple:()=>v2,transformer:()=>Z2,symbol:()=>O2,string:()=>O0,strictObject:()=>S2,setErrorMap:()=>l1,set:()=>P2,record:()=>k2,quotelessJson:()=>Z1,promise:()=>h2,preprocess:()=>m2,pipeline:()=>u2,ostring:()=>c2,optional:()=>g2,onumber:()=>n2,oboolean:()=>p2,objectUtil:()=>I3,object:()=>E2,number:()=>j0,nullable:()=>l2,null:()=>A2,never:()=>q2,nativeEnum:()=>y2,nan:()=>M2,map:()=>f2,makeIssue:()=>T$,literal:()=>T2,lazy:()=>I2,late:()=>w2,isValid:()=>W$,isDirty:()=>e$,isAsync:()=>U$,isAborted:()=>s$,intersection:()=>R2,instanceof:()=>_2,getParsedType:()=>t,getErrorMap:()=>b$,function:()=>C2,enum:()=>x2,effect:()=>Z2,discriminatedUnion:()=>z2,defaultErrorMap:()=>Q$,datetimeRegex:()=>M0,date:()=>N2,custom:()=>N0,coerce:()=>i2,boolean:()=>A0,bigint:()=>V2,array:()=>L2,any:()=>b2,addIssueToContext:()=>N,ZodVoid:()=>y$,ZodUnknown:()=>H$,ZodUnion:()=>F$,ZodUndefined:()=>E$,ZodType:()=>q,ZodTuple:()=>e,ZodTransformer:()=>p,ZodSymbol:()=>x$,ZodString:()=>m,ZodSet:()=>j$,ZodSchema:()=>q,ZodRecord:()=>h$,ZodReadonly:()=>C$,ZodPromise:()=>A$,ZodPipeline:()=>l$,ZodParsedType:()=>M,ZodOptional:()=>c,ZodObject:()=>F,ZodNumber:()=>B$,ZodNullable:()=>G$,ZodNull:()=>S$,ZodNever:()=>s,ZodNativeEnum:()=>k$,ZodNaN:()=>g$,ZodMap:()=>Z$,ZodLiteral:()=>v$,ZodLazy:()=>R$,ZodIssueCode:()=>w,ZodIntersection:()=>z$,ZodFunction:()=>K$,ZodFirstPartyTypeKind:()=>_,ZodError:()=>h,ZodEnum:()=>w$,ZodEffects:()=>p,ZodDiscriminatedUnion:()=>$3,ZodDefault:()=>f$,ZodDate:()=>N$,ZodCatch:()=>P$,ZodBranded:()=>X3,ZodBoolean:()=>L$,ZodBigInt:()=>D$,ZodArray:()=>u,ZodAny:()=>O$,Schema:()=>q,ParseStatus:()=>f,OK:()=>C,NEVER:()=>d2,INVALID:()=>A,EMPTY_PATH:()=>m1,DIRTY:()=>V$,BRAND:()=>D2});var Z3=g(()=>{t$();x3();W0();I$();b0();r$()});var _$=g(()=>{Z3();Z3()});var g3="2025-03-26",U0,Q3="2.0",q0,K0,o2,i,Z,m$,$$,d,Y3,L0,E0=($)=>L0.safeParse($).success,S0,F0=($)=>S0.safeParse($).success,z0,l3=($)=>z0.safeParse($).success,z,R0,v0=($)=>R0.safeParse($).success,k0,G3,J3,f0,a2,W3,zX=($)=>W3.safeParse($).success,r2,t2,m3,H3,s2,B3,D3,w3,P0,C0,I0,e2,$6,_3,X6,M3,Q6,V3,Y6,G6,J6,W6,H6,B6,D6,N3,w6,O3,j3,A3,b3,T0,_6,M6,V6,N6,O6,U3,j6,x0,RX,q3,A6,y0,b6,U6,q6,K6,L6,E6,u3,S6,F6,K3,z6,R6,v6,c3,k6,vX,kX,fX,PX,CX,IX,v;var u$=g(()=>{_$();U0=[g3,"2024-11-05","2024-10-07"],q0=J.union([J.string(),J.number().int()]),K0=J.string(),o2=J.object({progressToken:J.optional(q0)}).passthrough(),i=J.object({_meta:J.optional(o2)}).passthrough(),Z=J.object({method:J.string(),params:J.optional(i)}),m$=J.object({_meta:J.optional(J.object({}).passthrough())}).passthrough(),$$=J.object({method:J.string(),params:J.optional(m$)}),d=J.object({_meta:J.optional(J.object({}).passthrough())}).passthrough(),Y3=J.union([J.string(),J.number().int()]),L0=J.object({jsonrpc:J.literal(Q3),id:Y3}).merge(Z).strict(),S0=J.object({jsonrpc:J.literal(Q3)}).merge($$).strict(),z0=J.object({jsonrpc:J.literal(Q3),id:Y3,result:d}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError"})(z||(z={}));R0=J.object({jsonrpc:J.literal(Q3),id:Y3,error:J.object({code:J.number().int(),message:J.string(),data:J.optional(J.unknown())})}).strict(),k0=J.union([L0,S0,z0,R0]),G3=d.strict(),J3=$$.extend({method:J.literal("notifications/cancelled"),params:m$.extend({requestId:Y3,reason:J.string().optional()})}),f0=J.object({name:J.string(),version:J.string()}).passthrough(),a2=J.object({experimental:J.optional(J.object({}).passthrough()),sampling:J.optional(J.object({}).passthrough()),roots:J.optional(J.object({listChanged:J.optional(J.boolean())}).passthrough())}).passthrough(),W3=Z.extend({method:J.literal("initialize"),params:i.extend({protocolVersion:J.string(),capabilities:a2,clientInfo:f0})}),r2=J.object({experimental:J.optional(J.object({}).passthrough()),logging:J.optional(J.object({}).passthrough()),completions:J.optional(J.object({}).passthrough()),prompts:J.optional(J.object({listChanged:J.optional(J.boolean())}).passthrough()),resources:J.optional(J.object({subscribe:J.optional(J.boolean()),listChanged:J.optional(J.boolean())}).passthrough()),tools:J.optional(J.object({listChanged:J.optional(J.boolean())}).passthrough())}).passthrough(),t2=d.extend({protocolVersion:J.string(),capabilities:r2,serverInfo:f0,instructions:J.optional(J.string())}),m3=$$.extend({method:J.literal("notifications/initialized")}),H3=Z.extend({method:J.literal("ping")}),s2=J.object({progress:J.number(),total:J.optional(J.number()),message:J.optional(J.string())}).passthrough(),B3=$$.extend({method:J.literal("notifications/progress"),params:m$.merge(s2).extend({progressToken:q0})}),D3=Z.extend({params:i.extend({cursor:J.optional(K0)}).optional()}),w3=d.extend({nextCursor:J.optional(K0)}),P0=J.object({uri:J.string(),mimeType:J.optional(J.string())}).passthrough(),C0=P0.extend({text:J.string()}),I0=P0.extend({blob:J.string().base64()}),e2=J.object({uri:J.string(),name:J.string(),description:J.optional(J.string()),mimeType:J.optional(J.string())}).passthrough(),$6=J.object({uriTemplate:J.string(),name:J.string(),description:J.optional(J.string()),mimeType:J.optional(J.string())}).passthrough(),_3=D3.extend({method:J.literal("resources/list")}),X6=w3.extend({resources:J.array(e2)}),M3=D3.extend({method:J.literal("resources/templates/list")}),Q6=w3.extend({resourceTemplates:J.array($6)}),V3=Z.extend({method:J.literal("resources/read"),params:i.extend({uri:J.string()})}),Y6=d.extend({contents:J.array(J.union([C0,I0]))}),G6=$$.extend({method:J.literal("notifications/resources/list_changed")}),J6=Z.extend({method:J.literal("resources/subscribe"),params:i.extend({uri:J.string()})}),W6=Z.extend({method:J.literal("resources/unsubscribe"),params:i.extend({uri:J.string()})}),H6=$$.extend({method:J.literal("notifications/resources/updated"),params:m$.extend({uri:J.string()})}),B6=J.object({name:J.string(),description:J.optional(J.string()),required:J.optional(J.boolean())}).passthrough(),D6=J.object({name:J.string(),description:J.optional(J.string()),arguments:J.optional(J.array(B6))}).passthrough(),N3=D3.extend({method:J.literal("prompts/list")}),w6=w3.extend({prompts:J.array(D6)}),O3=Z.extend({method:J.literal("prompts/get"),params:i.extend({name:J.string(),arguments:J.optional(J.record(J.string()))})}),j3=J.object({type:J.literal("text"),text:J.string()}).passthrough(),A3=J.object({type:J.literal("image"),data:J.string().base64(),mimeType:J.string()}).passthrough(),b3=J.object({type:J.literal("audio"),data:J.string().base64(),mimeType:J.string()}).passthrough(),T0=J.object({type:J.literal("resource"),resource:J.union([C0,I0])}).passthrough(),_6=J.object({role:J.enum(["user","assistant"]),content:J.union([j3,A3,b3,T0])}).passthrough(),M6=d.extend({description:J.optional(J.string()),messages:J.array(_6)}),V6=$$.extend({method:J.literal("notifications/prompts/list_changed")}),N6=J.object({title:J.optional(J.string()),readOnlyHint:J.optional(J.boolean()),destructiveHint:J.optional(J.boolean()),idempotentHint:J.optional(J.boolean()),openWorldHint:J.optional(J.boolean())}).passthrough(),O6=J.object({name:J.string(),description:J.optional(J.string()),inputSchema:J.object({type:J.literal("object"),properties:J.optional(J.object({}).passthrough()),required:J.optional(J.array(J.string()))}).passthrough(),outputSchema:J.optional(J.object({type:J.literal("object"),properties:J.optional(J.object({}).passthrough()),required:J.optional(J.array(J.string()))}).passthrough()),annotations:J.optional(N6)}).passthrough(),U3=D3.extend({method:J.literal("tools/list")}),j6=w3.extend({tools:J.array(O6)}),x0=d.extend({content:J.array(J.union([j3,A3,b3,T0])).default([]),structuredContent:J.object({}).passthrough().optional(),isError:J.optional(J.boolean())}),RX=x0.or(d.extend({toolResult:J.unknown()})),q3=Z.extend({method:J.literal("tools/call"),params:i.extend({name:J.string(),arguments:J.optional(J.record(J.unknown()))})}),A6=$$.extend({method:J.literal("notifications/tools/list_changed")}),y0=J.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),b6=Z.extend({method:J.literal("logging/setLevel"),params:i.extend({level:y0})}),U6=$$.extend({method:J.literal("notifications/message"),params:m$.extend({level:y0,logger:J.optional(J.string()),data:J.unknown()})}),q6=J.object({name:J.string().optional()}).passthrough(),K6=J.object({hints:J.optional(J.array(q6)),costPriority:J.optional(J.number().min(0).max(1)),speedPriority:J.optional(J.number().min(0).max(1)),intelligencePriority:J.optional(J.number().min(0).max(1))}).passthrough(),L6=J.object({role:J.enum(["user","assistant"]),content:J.union([j3,A3,b3])}).passthrough(),E6=Z.extend({method:J.literal("sampling/createMessage"),params:i.extend({messages:J.array(L6),systemPrompt:J.optional(J.string()),includeContext:J.optional(J.enum(["none","thisServer","allServers"])),temperature:J.optional(J.number()),maxTokens:J.number().int(),stopSequences:J.optional(J.array(J.string())),metadata:J.optional(J.object({}).passthrough()),modelPreferences:J.optional(K6)})}),u3=d.extend({model:J.string(),stopReason:J.optional(J.enum(["endTurn","stopSequence","maxTokens"]).or(J.string())),role:J.enum(["user","assistant"]),content:J.discriminatedUnion("type",[j3,A3,b3])}),S6=J.object({type:J.literal("ref/resource"),uri:J.string()}).passthrough(),F6=J.object({type:J.literal("ref/prompt"),name:J.string()}).passthrough(),K3=Z.extend({method:J.literal("completion/complete"),params:i.extend({ref:J.union([F6,S6]),argument:J.object({name:J.string(),value:J.string()}).passthrough()})}),z6=d.extend({completion:J.object({values:J.array(J.string()).max(100),total:J.optional(J.number().int()),hasMore:J.optional(J.boolean())}).passthrough()}),R6=J.object({uri:J.string().startsWith("file://"),name:J.optional(J.string())}).passthrough(),v6=Z.extend({method:J.literal("roots/list")}),c3=d.extend({roots:J.array(R6)}),k6=$$.extend({method:J.literal("notifications/roots/list_changed")}),vX=J.union([H3,W3,K3,b6,O3,N3,_3,M3,V3,J6,W6,q3,U3]),kX=J.union([J3,B3,m3,k6]),fX=J.union([G3,u3,c3]),PX=J.union([H3,E6,v6]),CX=J.union([J3,B3,U6,H6,G6,A6,V6]),IX=J.union([G3,t2,z6,M6,w6,X6,Q6,Y6,x0,j6]);v=class v extends Error{constructor($,X,Q){super(`MCP error ${$}: ${X}`);this.code=$,this.data=Q,this.name="McpError"}}});function c6(){let $=process.argv.join(" ");return $.includes("streamable-http.js")||$.includes("streamable-http.ts")}class q1{context;level;constructor($,X=1){this.context=$,this.level=X}setLevel($){this.level=$}log(...$){if(U1)console.log(...$);else console.error(...$)}logWarn(...$){if(U1)console.warn(...$);else console.error(...$)}debug(...$){if(this.level<=0)this.log(`[DEBUG] [${this.context}]`,...$)}info(...$){if(this.level<=1)this.log(`[INFO] [${this.context}]`,...$)}warn(...$){if(this.level<=2)this.logWarn(`[WARN] [${this.context}]`,...$)}error(...$){if(this.level<=3)console.error(`[ERROR] [${this.context}]`,...$)}}var U1,M$=($,X=1)=>new q1($,X);var p$=g(()=>{U1=c6()});u$();var f6=60000;class n3{constructor($){this._options=$,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this.setNotificationHandler(J3,(X)=>{let Q=this._requestHandlerAbortControllers.get(X.params.requestId);Q===null||Q===void 0||Q.abort(X.params.reason)}),this.setNotificationHandler(B3,(X)=>{this._onprogress(X)}),this.setRequestHandler(H3,(X)=>({}))}_setupTimeout($,X,Q,Y,G=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(Y,X),startTime:Date.now(),timeout:X,maxTotalTimeout:Q,resetTimeoutOnProgress:G,onTimeout:Y})}_resetTimeout($){let X=this._timeoutInfo.get($);if(!X)return!1;let Q=Date.now()-X.startTime;if(X.maxTotalTimeout&&Q>=X.maxTotalTimeout)throw this._timeoutInfo.delete($),new v(z.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:X.maxTotalTimeout,totalElapsed:Q});return clearTimeout(X.timeoutId),X.timeoutId=setTimeout(X.onTimeout,X.timeout),!0}_cleanupTimeout($){let X=this._timeoutInfo.get($);if(X)clearTimeout(X.timeoutId),this._timeoutInfo.delete($)}async connect($){this._transport=$,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=(X)=>{this._onerror(X)},this._transport.onmessage=(X,Q)=>{if(l3(X)||v0(X))this._onresponse(X);else if(E0(X))this._onrequest(X,Q);else if(F0(X))this._onnotification(X);else this._onerror(new Error(`Unknown message type: ${JSON.stringify(X)}`))},await this._transport.start()}_onclose(){var $;let X=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,($=this.onclose)===null||$===void 0||$.call(this);let Q=new v(z.ConnectionClosed,"Connection closed");for(let Y of X.values())Y(Q)}_onerror($){var X;(X=this.onerror)===null||X===void 0||X.call(this,$)}_onnotification($){var X;let Q=(X=this._notificationHandlers.get($.method))!==null&&X!==void 0?X:this.fallbackNotificationHandler;if(Q===void 0)return;Promise.resolve().then(()=>Q($)).catch((Y)=>this._onerror(new Error(`Uncaught error in notification handler: ${Y}`)))}_onrequest($,X){var Q,Y,G,W;let H=(Q=this._requestHandlers.get($.method))!==null&&Q!==void 0?Q:this.fallbackRequestHandler;if(H===void 0){(Y=this._transport)===null||Y===void 0||Y.send({jsonrpc:"2.0",id:$.id,error:{code:z.MethodNotFound,message:"Method not found"}}).catch((V)=>this._onerror(new Error(`Failed to send an error response: ${V}`)));return}let B=new AbortController;this._requestHandlerAbortControllers.set($.id,B);let D={signal:B.signal,sessionId:(G=this._transport)===null||G===void 0?void 0:G.sessionId,_meta:(W=$.params)===null||W===void 0?void 0:W._meta,sendNotification:(V)=>this.notification(V,{relatedRequestId:$.id}),sendRequest:(V,j,P)=>this.request(V,j,{...P,relatedRequestId:$.id}),authInfo:X===null||X===void 0?void 0:X.authInfo,requestId:$.id};Promise.resolve().then(()=>H($,D)).then((V)=>{var j;if(B.signal.aborted)return;return(j=this._transport)===null||j===void 0?void 0:j.send({result:V,jsonrpc:"2.0",id:$.id})},(V)=>{var j,P;if(B.signal.aborted)return;return(j=this._transport)===null||j===void 0?void 0:j.send({jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(V.code)?V.code:z.InternalError,message:(P=V.message)!==null&&P!==void 0?P:"Internal error"}})}).catch((V)=>this._onerror(new Error(`Failed to send response: ${V}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:X,...Q}=$.params,Y=Number(X),G=this._progressHandlers.get(Y);if(!G){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let W=this._responseHandlers.get(Y),H=this._timeoutInfo.get(Y);if(H&&W&&H.resetTimeoutOnProgress)try{this._resetTimeout(Y)}catch(B){W(B);return}G(Q)}_onresponse($){let X=Number($.id),Q=this._responseHandlers.get(X);if(Q===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}if(this._responseHandlers.delete(X),this._progressHandlers.delete(X),this._cleanupTimeout(X),l3($))Q($);else{let Y=new v($.error.code,$.error.message,$.error.data);Q(Y)}}get transport(){return this._transport}async close(){var $;await(($=this._transport)===null||$===void 0?void 0:$.close())}request($,X,Q){let{relatedRequestId:Y,resumptionToken:G,onresumptiontoken:W}=Q!==null&&Q!==void 0?Q:{};return new Promise((H,B)=>{var D,V,j,P,I,l;if(!this._transport){B(new Error("Not connected"));return}if(((D=this._options)===null||D===void 0?void 0:D.enforceStrictCapabilities)===!0)this.assertCapabilityForMethod($.method);(V=Q===null||Q===void 0?void 0:Q.signal)===null||V===void 0||V.throwIfAborted();let R=this._requestMessageId++,d$={...$,jsonrpc:"2.0",id:R};if(Q===null||Q===void 0?void 0:Q.onprogress)this._progressHandlers.set(R,Q.onprogress),d$.params={...$.params,_meta:{...((j=$.params)===null||j===void 0?void 0:j._meta)||{},progressToken:R}};let o$=(y)=>{var X$;this._responseHandlers.delete(R),this._progressHandlers.delete(R),this._cleanupTimeout(R),(X$=this._transport)===null||X$===void 0||X$.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:R,reason:String(y)}},{relatedRequestId:Y,resumptionToken:G,onresumptiontoken:W}).catch((r)=>this._onerror(new Error(`Failed to send cancellation: ${r}`))),B(y)};this._responseHandlers.set(R,(y)=>{var X$;if((X$=Q===null||Q===void 0?void 0:Q.signal)===null||X$===void 0?void 0:X$.aborted)return;if(y instanceof Error)return B(y);try{let r=X.parse(y.result);H(r)}catch(r){B(r)}}),(P=Q===null||Q===void 0?void 0:Q.signal)===null||P===void 0||P.addEventListener("abort",()=>{var y;o$((y=Q===null||Q===void 0?void 0:Q.signal)===null||y===void 0?void 0:y.reason)});let a$=(I=Q===null||Q===void 0?void 0:Q.timeout)!==null&&I!==void 0?I:f6,P3=()=>o$(new v(z.RequestTimeout,"Request timed out",{timeout:a$}));this._setupTimeout(R,a$,Q===null||Q===void 0?void 0:Q.maxTotalTimeout,P3,(l=Q===null||Q===void 0?void 0:Q.resetTimeoutOnProgress)!==null&&l!==void 0?l:!1),this._transport.send(d$,{relatedRequestId:Y,resumptionToken:G,onresumptiontoken:W}).catch((y)=>{this._cleanupTimeout(R),B(y)})})}async notification($,X){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability($.method);let Q={...$,jsonrpc:"2.0"};await this._transport.send(Q,X)}setRequestHandler($,X){let Q=$.shape.method.value;this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(Y,G)=>{return Promise.resolve(X($.parse(Y),G))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw new Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,X){this._notificationHandlers.set($.shape.method.value,(Q)=>Promise.resolve(X($.parse(Q))))}removeNotificationHandler($){this._notificationHandlers.delete($)}}function h0($,X){return Object.entries(X).reduce((Q,[Y,G])=>{if(G&&typeof G==="object")Q[Y]=Q[Y]?{...Q[Y],...G}:G;else Q[Y]=G;return Q},{...$})}u$();class p3 extends n3{constructor($,X){var Q;super(X);this._serverInfo=$,this._capabilities=(Q=X===null||X===void 0?void 0:X.capabilities)!==null&&Q!==void 0?Q:{},this._instructions=X===null||X===void 0?void 0:X.instructions,this.setRequestHandler(W3,(Y)=>this._oninitialize(Y)),this.setNotificationHandler(m3,()=>{var Y;return(Y=this.oninitialized)===null||Y===void 0?void 0:Y.call(this)})}registerCapabilities($){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=h0(this._capabilities,$)}assertCapabilityForMethod($){var X,Q;switch($){case"sampling/createMessage":if(!((X=this._clientCapabilities)===null||X===void 0?void 0:X.sampling))throw new Error(`Client does not support sampling (required for ${$})`);break;case"roots/list":if(!((Q=this._clientCapabilities)===null||Q===void 0?void 0:Q.roots))throw new Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${$})`);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 ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){switch($){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${$})`);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 ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${$})`);break;case"ping":case"initialize":break}}async _oninitialize($){let X=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:U0.includes(X)?X:g3,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"},G3)}async createMessage($,X){return this.request({method:"sampling/createMessage",params:$},u3,X)}async listRoots($,X){return this.request({method:"roots/list",params:$},c3,X)}async sendLoggingMessage($){return this.notification({method:"notifications/message",params:$})}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}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"})}}var g0=Symbol("Let zodToJsonSchema decide on which parser to use");var Z0={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",openAiAnyTypeName:"OpenAiAnyType"},l0=($)=>typeof $==="string"?{...Z0,name:$}:{...Z0,...$};var m0=($)=>{let X=l0($),Q=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,flags:{hasReferencedOpenAiAnyType:!1},currentPath:Q,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Y,G])=>[G._def,{def:G._def,path:[...X.basePath,X.definitionPath,Y],jsonSchema:void 0}]))}};function i3($,X,Q,Y){if(!Y?.errorMessages)return;if(Q)$.errorMessage={...$.errorMessage,[X]:Q}}function E($,X,Q,Y,G){$[X]=Q,i3($,X,Y,G)}var L3=($,X)=>{let Q=0;for(;Q<$.length&&Q<X.length;Q++)if($[Q]!==X[Q])break;return[($.length-Q).toString(),...X.slice(Q)].join("/")};_$();function S($){if($.target!=="openAi")return{};let X=[...$.basePath,$.definitionPath,$.openAiAnyTypeName];return $.flags.hasReferencedOpenAiAnyType=!0,{$ref:$.$refStrategy==="relative"?L3(X,$.currentPath):X.join("/")}}_$();function u0($,X){let Q={type:"array"};if($.type?._def&&$.type?._def?.typeName!==_.ZodAny)Q.items=b($.type._def,{...X,currentPath:[...X.currentPath,"items"]});if($.minLength)E(Q,"minItems",$.minLength.value,$.minLength.message,X);if($.maxLength)E(Q,"maxItems",$.maxLength.value,$.maxLength.message,X);if($.exactLength)E(Q,"minItems",$.exactLength.value,$.exactLength.message,X),E(Q,"maxItems",$.exactLength.value,$.exactLength.message,X);return Q}function c0($,X){let Q={type:"integer",format:"int64"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"min":if(X.target==="jsonSchema7")if(Y.inclusive)E(Q,"minimum",Y.value,Y.message,X);else E(Q,"exclusiveMinimum",Y.value,Y.message,X);else{if(!Y.inclusive)Q.exclusiveMinimum=!0;E(Q,"minimum",Y.value,Y.message,X)}break;case"max":if(X.target==="jsonSchema7")if(Y.inclusive)E(Q,"maximum",Y.value,Y.message,X);else E(Q,"exclusiveMaximum",Y.value,Y.message,X);else{if(!Y.inclusive)Q.exclusiveMaximum=!0;E(Q,"maximum",Y.value,Y.message,X)}break;case"multipleOf":E(Q,"multipleOf",Y.value,Y.message,X);break}return Q}function n0(){return{type:"boolean"}}function E3($,X){return b($.type._def,X)}var p0=($,X)=>{return b($.innerType._def,X)};function d3($,X,Q){let Y=Q??X.dateStrategy;if(Array.isArray(Y))return{anyOf:Y.map((G,W)=>d3($,X,G))};switch(Y){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return P6($,X)}}var P6=($,X)=>{let Q={type:"integer",format:"unix-time"};if(X.target==="openApi3")return Q;for(let Y of $.checks)switch(Y.kind){case"min":E(Q,"minimum",Y.value,Y.message,X);break;case"max":E(Q,"maximum",Y.value,Y.message,X);break}return Q};function i0($,X){return{...b($.innerType._def,X),default:$.defaultValue()}}function d0($,X){return X.effectStrategy==="input"?b($.schema._def,X):S(X)}function o0($){return{type:"string",enum:Array.from($.values)}}var C6=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};function a0($,X){let Q=[b($.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),b($.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((W)=>!!W),Y=X.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,G=[];return Q.forEach((W)=>{if(C6(W)){if(G.push(...W.allOf),W.unevaluatedProperties===void 0)Y=void 0}else{let H=W;if("additionalProperties"in W&&W.additionalProperties===!1){let{additionalProperties:B,...D}=W;H=D}else Y=void 0;G.push(H)}}),G.length?{allOf:G,...Y}:void 0}function r0($,X){let Q=typeof $.value;if(Q!=="bigint"&&Q!=="number"&&Q!=="boolean"&&Q!=="string")return{type:Array.isArray($.value)?"array":"object"};if(X.target==="openApi3")return{type:Q==="bigint"?"integer":Q,enum:[$.value]};return{type:Q==="bigint"?"integer":Q,const:$.value}}_$();var o3=void 0,o={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(o3===void 0)o3=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return o3},uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function S3($,X){let Q={type:"string"};if($.checks)for(let Y of $.checks)switch(Y.kind){case"min":E(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,Y.value):Y.value,Y.message,X);break;case"max":E(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,Y.value):Y.value,Y.message,X);break;case"email":switch(X.emailStrategy){case"format:email":a(Q,"email",Y.message,X);break;case"format:idn-email":a(Q,"idn-email",Y.message,X);break;case"pattern:zod":T(Q,o.email,Y.message,X);break}break;case"url":a(Q,"uri",Y.message,X);break;case"uuid":a(Q,"uuid",Y.message,X);break;case"regex":T(Q,Y.regex,Y.message,X);break;case"cuid":T(Q,o.cuid,Y.message,X);break;case"cuid2":T(Q,o.cuid2,Y.message,X);break;case"startsWith":T(Q,RegExp(`^${a3(Y.value,X)}`),Y.message,X);break;case"endsWith":T(Q,RegExp(`${a3(Y.value,X)}$`),Y.message,X);break;case"datetime":a(Q,"date-time",Y.message,X);break;case"date":a(Q,"date",Y.message,X);break;case"time":a(Q,"time",Y.message,X);break;case"duration":a(Q,"duration",Y.message,X);break;case"length":E(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,Y.value):Y.value,Y.message,X),E(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,Y.value):Y.value,Y.message,X);break;case"includes":{T(Q,RegExp(a3(Y.value,X)),Y.message,X);break}case"ip":{if(Y.version!=="v6")a(Q,"ipv4",Y.message,X);if(Y.version!=="v4")a(Q,"ipv6",Y.message,X);break}case"base64url":T(Q,o.base64url,Y.message,X);break;case"jwt":T(Q,o.jwt,Y.message,X);break;case"cidr":{if(Y.version!=="v6")T(Q,o.ipv4Cidr,Y.message,X);if(Y.version!=="v4")T(Q,o.ipv6Cidr,Y.message,X);break}case"emoji":T(Q,o.emoji(),Y.message,X);break;case"ulid":{T(Q,o.ulid,Y.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{a(Q,"binary",Y.message,X);break}case"contentEncoding:base64":{E(Q,"contentEncoding","base64",Y.message,X);break}case"pattern:zod":{T(Q,o.base64,Y.message,X);break}}break}case"nanoid":T(Q,o.nanoid,Y.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:((G)=>{})(Y)}return Q}function a3($,X){return X.patternStrategy==="escape"?T6($):$}var I6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function T6($){let X="";for(let Q=0;Q<$.length;Q++){if(!I6.has($[Q]))X+="\\";X+=$[Q]}return X}function a($,X,Q,Y){if($.format||$.anyOf?.some((G)=>G.format)){if(!$.anyOf)$.anyOf=[];if($.format){if($.anyOf.push({format:$.format,...$.errorMessage&&Y.errorMessages&&{errorMessage:{format:$.errorMessage.format}}}),delete $.format,$.errorMessage){if(delete $.errorMessage.format,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.anyOf.push({format:X,...Q&&Y.errorMessages&&{errorMessage:{format:Q}}})}else E($,"format",X,Q,Y)}function T($,X,Q,Y){if($.pattern||$.allOf?.some((G)=>G.pattern)){if(!$.allOf)$.allOf=[];if($.pattern){if($.allOf.push({pattern:$.pattern,...$.errorMessage&&Y.errorMessages&&{errorMessage:{pattern:$.errorMessage.pattern}}}),delete $.pattern,$.errorMessage){if(delete $.errorMessage.pattern,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.allOf.push({pattern:t0(X,Y),...Q&&Y.errorMessages&&{errorMessage:{pattern:Q}}})}else E($,"pattern",t0(X,Y),Q,Y)}function t0($,X){if(!X.applyRegexFlags||!$.flags)return $.source;let Q={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},Y=Q.i?$.source.toLowerCase():$.source,G="",W=!1,H=!1,B=!1;for(let D=0;D<Y.length;D++){if(W){G+=Y[D],W=!1;continue}if(Q.i){if(H){if(Y[D].match(/[a-z]/)){if(B)G+=Y[D],G+=`${Y[D-2]}-${Y[D]}`.toUpperCase(),B=!1;else if(Y[D+1]==="-"&&Y[D+2]?.match(/[a-z]/))G+=Y[D],B=!0;else G+=`${Y[D]}${Y[D].toUpperCase()}`;continue}}else if(Y[D].match(/[a-z]/)){G+=`[${Y[D]}${Y[D].toUpperCase()}]`;continue}}if(Q.m){if(Y[D]==="^"){G+=`(^|(?<=[\r
3
- ]))`;continue}else if(Y[D]==="$"){G+=`($|(?=[\r
4
- ]))`;continue}}if(Q.s&&Y[D]==="."){G+=H?`${Y[D]}\r
5
- `:`[${Y[D]}\r
6
- ]`;continue}if(G+=Y[D],Y[D]==="\\")W=!0;else if(H&&Y[D]==="]")H=!1;else if(!H&&Y[D]==="[")H=!0}try{new RegExp(G)}catch{return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return G}function F3($,X){if(X.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(X.target==="openApi3"&&$.keyType?._def.typeName===_.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((Y,G)=>({...Y,[G]:b($.valueType._def,{...X,currentPath:[...X.currentPath,"properties",G]})??S(X)}),{}),additionalProperties:X.rejectedAdditionalProperties};let Q={type:"object",additionalProperties:b($.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]})??X.allowedAdditionalProperties};if(X.target==="openApi3")return Q;if($.keyType?._def.typeName===_.ZodString&&$.keyType._def.checks?.length){let{type:Y,...G}=S3($.keyType._def,X);return{...Q,propertyNames:G}}else if($.keyType?._def.typeName===_.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===_.ZodBranded&&$.keyType._def.type._def.typeName===_.ZodString&&$.keyType._def.type._def.checks?.length){let{type:Y,...G}=E3($.keyType._def,X);return{...Q,propertyNames:G}}return Q}function s0($,X){if(X.mapStrategy==="record")return F3($,X);let Q=b($.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||S(X),Y=b($.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||S(X);return{type:"array",maxItems:125,items:{type:"array",items:[Q,Y],minItems:2,maxItems:2}}}function e0($){let X=$.values,Y=Object.keys($.values).filter((W)=>{return typeof X[X[W]]!=="number"}).map((W)=>X[W]),G=Array.from(new Set(Y.map((W)=>typeof W)));return{type:G.length===1?G[0]==="string"?"string":"number":["string","number"],enum:Y}}function $1($){return $.target==="openAi"?void 0:{not:S({...$,currentPath:[...$.currentPath,"not"]})}}function X1($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var c$={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Y1($,X){if(X.target==="openApi3")return Q1($,X);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((Y)=>(Y._def.typeName in c$)&&(!Y._def.checks||!Y._def.checks.length))){let Y=Q.reduce((G,W)=>{let H=c$[W._def.typeName];return H&&!G.includes(H)?[...G,H]:G},[]);return{type:Y.length>1?Y:Y[0]}}else if(Q.every((Y)=>Y._def.typeName==="ZodLiteral"&&!Y.description)){let Y=Q.reduce((G,W)=>{let H=typeof W._def.value;switch(H){case"string":case"number":case"boolean":return[...G,H];case"bigint":return[...G,"integer"];case"object":if(W._def.value===null)return[...G,"null"];case"symbol":case"undefined":case"function":default:return G}},[]);if(Y.length===Q.length){let G=Y.filter((W,H,B)=>B.indexOf(W)===H);return{type:G.length>1?G:G[0],enum:Q.reduce((W,H)=>{return W.includes(H._def.value)?W:[...W,H._def.value]},[])}}}else if(Q.every((Y)=>Y._def.typeName==="ZodEnum"))return{type:"string",enum:Q.reduce((Y,G)=>[...Y,...G._def.values.filter((W)=>!Y.includes(W))],[])};return Q1($,X)}var Q1=($,X)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((Y,G)=>b(Y._def,{...X,currentPath:[...X.currentPath,"anyOf",`${G}`]})).filter((Y)=>!!Y&&(!X.strictUnions||typeof Y==="object"&&Object.keys(Y).length>0));return Q.length?{anyOf:Q}:void 0};function G1($,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(X.target==="openApi3")return{type:c$[$.innerType._def.typeName],nullable:!0};return{type:[c$[$.innerType._def.typeName],"null"]}}if(X.target==="openApi3"){let Y=b($.innerType._def,{...X,currentPath:[...X.currentPath]});if(Y&&"$ref"in Y)return{allOf:[Y],nullable:!0};return Y&&{...Y,nullable:!0}}let Q=b($.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return Q&&{anyOf:[Q,{type:"null"}]}}function J1($,X){let Q={type:"number"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"int":Q.type="integer",i3(Q,"type",Y.message,X);break;case"min":if(X.target==="jsonSchema7")if(Y.inclusive)E(Q,"minimum",Y.value,Y.message,X);else E(Q,"exclusiveMinimum",Y.value,Y.message,X);else{if(!Y.inclusive)Q.exclusiveMinimum=!0;E(Q,"minimum",Y.value,Y.message,X)}break;case"max":if(X.target==="jsonSchema7")if(Y.inclusive)E(Q,"maximum",Y.value,Y.message,X);else E(Q,"exclusiveMaximum",Y.value,Y.message,X);else{if(!Y.inclusive)Q.exclusiveMaximum=!0;E(Q,"maximum",Y.value,Y.message,X)}break;case"multipleOf":E(Q,"multipleOf",Y.value,Y.message,X);break}return Q}function W1($,X){let Q=X.target==="openAi",Y={type:"object",properties:{}},G=[],W=$.shape();for(let B in W){let D=W[B];if(D===void 0||D._def===void 0)continue;let V=y6(D);if(V&&Q){if(D._def.typeName==="ZodOptional")D=D._def.innerType;if(!D.isNullable())D=D.nullable();V=!1}let j=b(D._def,{...X,currentPath:[...X.currentPath,"properties",B],propertyPath:[...X.currentPath,"properties",B]});if(j===void 0)continue;if(Y.properties[B]=j,!V)G.push(B)}if(G.length)Y.required=G;let H=x6($,X);if(H!==void 0)Y.additionalProperties=H;return Y}function x6($,X){if($.catchall._def.typeName!=="ZodNever")return b($.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch($.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function y6($){try{return $.isOptional()}catch{return!0}}var H1=($,X)=>{if(X.currentPath.toString()===X.propertyPath?.toString())return b($.innerType._def,X);let Q=b($.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:S(X)},Q]}:S(X)};var B1=($,X)=>{if(X.pipeStrategy==="input")return b($.in._def,X);else if(X.pipeStrategy==="output")return b($.out._def,X);let Q=b($.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Y=b($.out._def,{...X,currentPath:[...X.currentPath,"allOf",Q?"1":"0"]});return{allOf:[Q,Y].filter((G)=>G!==void 0)}};function D1($,X){return b($.type._def,X)}function w1($,X){let Y={type:"array",uniqueItems:!0,items:b($.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if($.minSize)E(Y,"minItems",$.minSize.value,$.minSize.message,X);if($.maxSize)E(Y,"maxItems",$.maxSize.value,$.maxSize.message,X);return Y}function _1($,X){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((Q,Y)=>b(Q._def,{...X,currentPath:[...X.currentPath,"items",`${Y}`]})).reduce((Q,Y)=>Y===void 0?Q:[...Q,Y],[]),additionalItems:b($.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((Q,Y)=>b(Q._def,{...X,currentPath:[...X.currentPath,"items",`${Y}`]})).reduce((Q,Y)=>Y===void 0?Q:[...Q,Y],[])}}function M1($){return{not:S($)}}function V1($){return S($)}var N1=($,X)=>{return b($.innerType._def,X)};var O1=($,X,Q)=>{switch(X){case _.ZodString:return S3($,Q);case _.ZodNumber:return J1($,Q);case _.ZodObject:return W1($,Q);case _.ZodBigInt:return c0($,Q);case _.ZodBoolean:return n0();case _.ZodDate:return d3($,Q);case _.ZodUndefined:return M1(Q);case _.ZodNull:return X1(Q);case _.ZodArray:return u0($,Q);case _.ZodUnion:case _.ZodDiscriminatedUnion:return Y1($,Q);case _.ZodIntersection:return a0($,Q);case _.ZodTuple:return _1($,Q);case _.ZodRecord:return F3($,Q);case _.ZodLiteral:return r0($,Q);case _.ZodEnum:return o0($);case _.ZodNativeEnum:return e0($);case _.ZodNullable:return G1($,Q);case _.ZodOptional:return H1($,Q);case _.ZodMap:return s0($,Q);case _.ZodSet:return w1($,Q);case _.ZodLazy:return()=>$.getter()._def;case _.ZodPromise:return D1($,Q);case _.ZodNaN:case _.ZodNever:return $1(Q);case _.ZodEffects:return d0($,Q);case _.ZodAny:return S(Q);case _.ZodUnknown:return V1(Q);case _.ZodDefault:return i0($,Q);case _.ZodBranded:return E3($,Q);case _.ZodReadonly:return N1($,Q);case _.ZodCatch:return p0($,Q);case _.ZodPipeline:return B1($,Q);case _.ZodFunction:case _.ZodVoid:case _.ZodSymbol:return;default:return((Y)=>{return})(X)}};function b($,X,Q=!1){let Y=X.seen.get($);if(X.override){let B=X.override?.($,X,Y,Q);if(B!==g0)return B}if(Y&&!Q){let B=h6(Y,X);if(B!==void 0)return B}let G={def:$,path:X.currentPath,jsonSchema:void 0};X.seen.set($,G);let W=O1($,$.typeName,X),H=typeof W==="function"?b(W(),X):W;if(H)Z6($,X,H);if(X.postProcess){let B=X.postProcess(H,$,X);return G.jsonSchema=H,B}return G.jsonSchema=H,H}var h6=($,X)=>{switch(X.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:L3(X.currentPath,$.path)};case"none":case"seen":{if($.path.length<X.currentPath.length&&$.path.every((Q,Y)=>X.currentPath[Y]===Q))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),S(X);return X.$refStrategy==="seen"?S(X):void 0}}},Z6=($,X,Q)=>{if($.description){if(Q.description=$.description,X.markdownDescription)Q.markdownDescription=$.description}return Q};var z3=($,X)=>{let Q=m0(X),Y=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((D,[V,j])=>({...D,[V]:b(j._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,V]},!0)??S(Q)}),{}):void 0,G=typeof X==="string"?X:X?.nameStrategy==="title"?void 0:X?.name,W=b($._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1)??S(Q),H=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(H!==void 0)W.title=H;if(Q.flags.hasReferencedOpenAiAnyType){if(!Y)Y={};if(!Y[Q.openAiAnyTypeName])Y[Q.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Q.$refStrategy==="relative"?"1":[...Q.basePath,Q.definitionPath,Q.openAiAnyTypeName].join("/")}}}let B=G===void 0?Y?{...W,[Q.definitionPath]:Y}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...Y,[G]:W}};if(Q.target==="jsonSchema7")B.$schema="http://json-schema.org/draft-07/schema#";else if(Q.target==="jsonSchema2019-09"||Q.target==="openAi")B.$schema="https://json-schema.org/draft/2019-09/schema#";if(Q.target==="openAi"&&(("anyOf"in B)||("oneOf"in B)||("allOf"in B)||("type"in B)&&Array.isArray(B.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return B};_$();u$();_$();var r3;(function($){$.Completable="McpCompletable"})(r3||(r3={}));class n$ extends q{_parse($){let{ctx:X}=this._processInputParams($),Q=X.data;return this._def.type._parse({data:Q,path:X.path,parent:X})}unwrap(){return this._def.type}}n$.create=($,X)=>{return new n$({type:$,typeName:r3.Completable,complete:X.complete,...g6(X)})};function g6($){if(!$)return{};let{errorMap:X,invalid_type_error:Q,required_error:Y,description:G}=$;if(X&&(Q||Y))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(X)return{errorMap:X,description:G};return{errorMap:(H,B)=>{var D,V;let{message:j}=$;if(H.code==="invalid_enum_value")return{message:j!==null&&j!==void 0?j:B.defaultError};if(typeof B.data==="undefined")return{message:(D=j!==null&&j!==void 0?j:Y)!==null&&D!==void 0?D:B.defaultError};if(H.code!=="invalid_type")return{message:B.defaultError};return{message:(V=j!==null&&j!==void 0?j:Q)!==null&&V!==void 0?V:B.defaultError}},description:G}}class t3{constructor($,X){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new p3($,X)}async connect($){return await this.server.connect($)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(U3.shape.method.value),this.server.assertCanSetRequestHandler(q3.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(U3,()=>({tools:Object.entries(this._registeredTools).filter(([,$])=>$.enabled).map(([$,X])=>{let Q={name:$,description:X.description,inputSchema:X.inputSchema?z3(X.inputSchema,{strictUnions:!0}):l6,annotations:X.annotations};if(X.outputSchema)Q.outputSchema=z3(X.outputSchema,{strictUnions:!0});return Q})})),this.server.setRequestHandler(q3,async($,X)=>{let Q=this._registeredTools[$.params.name];if(!Q)throw new v(z.InvalidParams,`Tool ${$.params.name} not found`);if(!Q.enabled)throw new v(z.InvalidParams,`Tool ${$.params.name} disabled`);let Y;if(Q.inputSchema){let G=await Q.inputSchema.safeParseAsync($.params.arguments);if(!G.success)throw new v(z.InvalidParams,`Invalid arguments for tool ${$.params.name}: ${G.error.message}`);let W=G.data,H=Q.callback;try{Y=await Promise.resolve(H(W,X))}catch(B){Y={content:[{type:"text",text:B instanceof Error?B.message:String(B)}],isError:!0}}}else{let G=Q.callback;try{Y=await Promise.resolve(G(X))}catch(W){Y={content:[{type:"text",text:W instanceof Error?W.message:String(W)}],isError:!0}}}if(Q.outputSchema){if(!Y.structuredContent)throw new v(z.InvalidParams,`Tool ${$.params.name} has an output schema but no structured content was provided`);let G=await Q.outputSchema.safeParseAsync(Y.structuredContent);if(!G.success)throw new v(z.InvalidParams,`Invalid structured content for tool ${$.params.name}: ${G.error.message}`)}return Y}),this._toolHandlersInitialized=!0}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(K3.shape.method.value),this.server.setRequestHandler(K3,async($)=>{switch($.params.ref.type){case"ref/prompt":return this.handlePromptCompletion($,$.params.ref);case"ref/resource":return this.handleResourceCompletion($,$.params.ref);default:throw new v(z.InvalidParams,`Invalid completion reference: ${$.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion($,X){let Q=this._registeredPrompts[X.name];if(!Q)throw new v(z.InvalidParams,`Prompt ${X.name} not found`);if(!Q.enabled)throw new v(z.InvalidParams,`Prompt ${X.name} disabled`);if(!Q.argsSchema)return R3;let Y=Q.argsSchema.shape[$.params.argument.name];if(!(Y instanceof n$))return R3;let W=await Y._def.complete($.params.argument.value);return A1(W)}async handleResourceCompletion($,X){let Q=Object.values(this._registeredResourceTemplates).find((W)=>W.resourceTemplate.uriTemplate.toString()===X.uri);if(!Q){if(this._registeredResources[X.uri])return R3;throw new v(z.InvalidParams,`Resource template ${$.params.ref.uri} not found`)}let Y=Q.resourceTemplate.completeCallback($.params.argument.name);if(!Y)return R3;let G=await Y($.params.argument.value);return A1(G)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(_3.shape.method.value),this.server.assertCanSetRequestHandler(M3.shape.method.value),this.server.assertCanSetRequestHandler(V3.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_3,async($,X)=>{let Q=Object.entries(this._registeredResources).filter(([G,W])=>W.enabled).map(([G,W])=>({uri:G,name:W.name,...W.metadata})),Y=[];for(let G of Object.values(this._registeredResourceTemplates)){if(!G.resourceTemplate.listCallback)continue;let W=await G.resourceTemplate.listCallback(X);for(let H of W.resources)Y.push({...H,...G.metadata})}return{resources:[...Q,...Y]}}),this.server.setRequestHandler(M3,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,Q])=>({name:X,uriTemplate:Q.resourceTemplate.uriTemplate.toString(),...Q.metadata}))}}),this.server.setRequestHandler(V3,async($,X)=>{let Q=new URL($.params.uri),Y=this._registeredResources[Q.toString()];if(Y){if(!Y.enabled)throw new v(z.InvalidParams,`Resource ${Q} disabled`);return Y.readCallback(Q,X)}for(let G of Object.values(this._registeredResourceTemplates)){let W=G.resourceTemplate.uriTemplate.match(Q.toString());if(W)return G.readCallback(Q,W,X)}throw new v(z.InvalidParams,`Resource ${Q} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(N3.shape.method.value),this.server.assertCanSetRequestHandler(O3.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(N3,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,$])=>$.enabled).map(([$,X])=>{return{name:$,description:X.description,arguments:X.argsSchema?u6(X.argsSchema):void 0}})})),this.server.setRequestHandler(O3,async($,X)=>{let Q=this._registeredPrompts[$.params.name];if(!Q)throw new v(z.InvalidParams,`Prompt ${$.params.name} not found`);if(!Q.enabled)throw new v(z.InvalidParams,`Prompt ${$.params.name} disabled`);if(Q.argsSchema){let Y=await Q.argsSchema.safeParseAsync($.params.arguments);if(!Y.success)throw new v(z.InvalidParams,`Invalid arguments for prompt ${$.params.name}: ${Y.error.message}`);let G=Y.data,W=Q.callback;return await Promise.resolve(W(G,X))}else{let Y=Q.callback;return await Promise.resolve(Y(X))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0}resource($,X,...Q){let Y;if(typeof Q[0]==="object")Y=Q.shift();let G=Q[0];if(typeof X==="string"){if(this._registeredResources[X])throw new Error(`Resource ${X} is already registered`);let W={name:$,metadata:Y,readCallback:G,enabled:!0,disable:()=>W.update({enabled:!1}),enable:()=>W.update({enabled:!0}),remove:()=>W.update({uri:null}),update:(H)=>{if(typeof H.uri!=="undefined"&&H.uri!==X){if(delete this._registeredResources[X],H.uri)this._registeredResources[H.uri]=W}if(typeof H.name!=="undefined")W.name=H.name;if(typeof H.metadata!=="undefined")W.metadata=H.metadata;if(typeof H.callback!=="undefined")W.readCallback=H.callback;if(typeof H.enabled!=="undefined")W.enabled=H.enabled;this.sendResourceListChanged()}};return this._registeredResources[X]=W,this.setResourceRequestHandlers(),this.sendResourceListChanged(),W}else{if(this._registeredResourceTemplates[$])throw new Error(`Resource template ${$} is already registered`);let W={resourceTemplate:X,metadata:Y,readCallback:G,enabled:!0,disable:()=>W.update({enabled:!1}),enable:()=>W.update({enabled:!0}),remove:()=>W.update({name:null}),update:(H)=>{if(typeof H.name!=="undefined"&&H.name!==$){if(delete this._registeredResourceTemplates[$],H.name)this._registeredResourceTemplates[H.name]=W}if(typeof H.template!=="undefined")W.resourceTemplate=H.template;if(typeof H.metadata!=="undefined")W.metadata=H.metadata;if(typeof H.callback!=="undefined")W.readCallback=H.callback;if(typeof H.enabled!=="undefined")W.enabled=H.enabled;this.sendResourceListChanged()}};return this._registeredResourceTemplates[$]=W,this.setResourceRequestHandlers(),this.sendResourceListChanged(),W}}_createRegisteredTool($,X,Q,Y,G,W){let H={description:X,inputSchema:Q===void 0?void 0:J.object(Q),outputSchema:Y===void 0?void 0:J.object(Y),annotations:G,callback:W,enabled:!0,disable:()=>H.update({enabled:!1}),enable:()=>H.update({enabled:!0}),remove:()=>H.update({name:null}),update:(B)=>{if(typeof B.name!=="undefined"&&B.name!==$){if(delete this._registeredTools[$],B.name)this._registeredTools[B.name]=H}if(typeof B.description!=="undefined")H.description=B.description;if(typeof B.paramsSchema!=="undefined")H.inputSchema=J.object(B.paramsSchema);if(typeof B.callback!=="undefined")H.callback=B.callback;if(typeof B.annotations!=="undefined")H.annotations=B.annotations;if(typeof B.enabled!=="undefined")H.enabled=B.enabled;this.sendToolListChanged()}};return this._registeredTools[$]=H,this.setToolRequestHandlers(),this.sendToolListChanged(),H}tool($,...X){if(this._registeredTools[$])throw new Error(`Tool ${$} is already registered`);let Q,Y,G,W;if(typeof X[0]==="string")Q=X.shift();if(X.length>1){let B=X[0];if(j1(B)){if(Y=X.shift(),X.length>1&&typeof X[0]==="object"&&X[0]!==null&&!j1(X[0]))W=X.shift()}else if(typeof B==="object"&&B!==null)W=X.shift()}let H=X[0];return this._createRegisteredTool($,Q,Y,G,W,H)}registerTool($,X,Q){if(this._registeredTools[$])throw new Error(`Tool ${$} is already registered`);let{description:Y,inputSchema:G,outputSchema:W,annotations:H}=X;return this._createRegisteredTool($,Y,G,W,H,Q)}prompt($,...X){if(this._registeredPrompts[$])throw new Error(`Prompt ${$} is already registered`);let Q;if(typeof X[0]==="string")Q=X.shift();let Y;if(X.length>1)Y=X.shift();let G=X[0],W={description:Q,argsSchema:Y===void 0?void 0:J.object(Y),callback:G,enabled:!0,disable:()=>W.update({enabled:!1}),enable:()=>W.update({enabled:!0}),remove:()=>W.update({name:null}),update:(H)=>{if(typeof H.name!=="undefined"&&H.name!==$){if(delete this._registeredPrompts[$],H.name)this._registeredPrompts[H.name]=W}if(typeof H.description!=="undefined")W.description=H.description;if(typeof H.argsSchema!=="undefined")W.argsSchema=J.object(H.argsSchema);if(typeof H.callback!=="undefined")W.callback=H.callback;if(typeof H.enabled!=="undefined")W.enabled=H.enabled;this.sendPromptListChanged()}};return this._registeredPrompts[$]=W,this.setPromptRequestHandlers(),this.sendPromptListChanged(),W}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var l6={type:"object"};function j1($){if(typeof $!=="object"||$===null)return!1;return Object.keys($).length===0||Object.values($).some(m6)}function m6($){return $!==null&&typeof $==="object"&&"parse"in $&&typeof $.parse==="function"&&"safeParse"in $&&typeof $.safeParse==="function"}function u6($){return Object.entries($.shape).map(([X,Q])=>({name:X,description:Q.description,required:!Q.isOptional()}))}function A1($){return{completion:{values:$.slice(0,100),total:$.length,hasMore:$.length>100}}}var R3={completion:{values:[],hasMore:!1}};function b1($,X){let Q=process.argv,Y=`--${$}=`;for(let G of Q)if(G.startsWith(Y))return G.substring(Y.length);return X}p$();var n6=M$("FigmaConfig",1),p6=b1("figma-api-key")||process.env.FIGMA_API_KEY||"",K1="F2C MCP",L1=process.env.FIGMA_VERSION||"0.0.1";n6.debug("DEFAULT_PERSONAL_TOKEN",p6);_$();p$();var z1=require("node:crypto");p$();var k=M$("ptdTool"),x=null,i$=0,E1=10,i6=1000,k3=null,d6=process.argv.slice(2),S1=d6.find(($)=>$.startsWith("--server=")),v3=S1?S1.split("=")[1]:"localhost",F1=v3==="localhost"?`ws://${v3}`:`wss://${v3}`,J$=new Map;function s3($=3055){if(x&&x.readyState===WebSocket.OPEN){k.info("Already connected to Figma");return}let X=v3==="localhost"?`${F1}:${$}`:F1;k.info(`Connecting to Figma socket server at ${X}...`),x=new WebSocket(X),k.info("Connecting",x.readyState,WebSocket.OPEN),x.onopen=()=>{k.info("Successfully connected to Figma socket server"),k3=null,i$=0},x.onmessage=(Q)=>{try{let Y=JSON.parse(Q.data);if(k.log("onmessage"+JSON.stringify(Y)),Y.type==="ping"){x?.send(JSON.stringify({type:"pong"}));return}let G=Y.message;if(G.id&&J$.has(G.id)&&G.result){let W=J$.get(G.id);if(clearTimeout(W.timeout),G.error)k.error(`Error from Figma: ${G.error}`),W.reject(new Error(G.error));else if(G.result)W.resolve(G.result);J$.delete(G.id)}else k.info(`Received broadcast message: ${JSON.stringify(G)}`)}catch(Y){k.error(`Error parsing message: ${Y instanceof Error?Y.message:String(Y)}`)}},x.onerror=(Q)=>{k.error(`Socket error: ${Q instanceof Error?Q.message:String(Q)}`,Q)},x.onclose=(Q)=>{k.info(`Disconnected from Figma socket server, Code: ${Q.code}, Reason: ${Q.reason}`),x=null;for(let[Y,G]of J$.entries())clearTimeout(G.timeout),G.reject(new Error("Connection closed")),J$.delete(Y);if(i$<E1){let Y=i6*Math.pow(2,i$);k.info(`Attempting to reconnect in ${Y/1000} seconds... (Attempt ${i$+1}/${E1})`),setTimeout(()=>s3($),Y),i$++}else k.error("Max reconnection attempts reached. Will not try again.")}}async function R1(){try{console.log("FigmaMCP server starting...");let $=process.env.PORT?parseInt(process.env.PORT,10):3055;s3($)}catch($){k.warn(`Could not connect to Figma initially: ${$ instanceof Error?$.message:String($)}`),k.warn("Will try to connect when the first command is sent")}k.info("FigmaMCP server running on stdio")}async function v1($){if(!x||x.readyState!==WebSocket.OPEN)throw new Error("Not connected to Figma");try{await K("join",{channel:$}),k3=$,k.info(`Joined channel: ${$}`)}catch(X){throw k.error(`Failed to join channel: ${X instanceof Error?X.message:String(X)}`),X}}function K($,X={},Q=30000){return new Promise((Y,G)=>{if(!x||x.readyState!==WebSocket.OPEN){s3(),G(new Error("Not connected to Figma. Attempting to connect..."));return}if($!=="join"&&!k3){G(new Error("Must join a channel before sending commands"));return}let H=z1.randomUUID(),B={id:H,type:$==="join"?"join":"message",...$==="join"?{channel:X.channel}:{channel:k3},message:{id:H,command:$,params:{...X,commandId:H}}};k.info(`Sending command to Figma: ${JSON.stringify(B)}`);let D=setTimeout(()=>{if(J$.has(H)){let{reject:V,...j}=J$.get(H);k.error(`Request to Figma timed out after ${Q/1000} seconds. Request details: ${JSON.stringify(j)}`),J$.delete(H),G(new Error("Request to Figma timed out"))}},Q);J$.set(H,{resolve:Y,reject:G,timeout:D,lastActivity:Date.now()}),k.info(`Sending command to Figma: ${$}`),k.debug(`Request details: ${JSON.stringify(B)}`),x.send(JSON.stringify(B))})}function e3($){if($.startsWith("#"))return $;let X=Math.round($.r*255),Q=Math.round($.g*255),Y=Math.round($.b*255),G=Math.round($.a*255);return`#${X.toString(16).padStart(2,"0")}${Q.toString(16).padStart(2,"0")}${Y.toString(16).padStart(2,"0")}${G===255?"":G.toString(16).padStart(2,"0")}`}function f3($){if($.type==="VECTOR")return null;let X={id:$.id,name:$.name,type:$.type};if($.fills&&$.fills.length>0)X.fills=$.fills.map((Q)=>{let Y={...Q};if(delete Y.boundVariables,delete Y.imageRef,Y.gradientStops)Y.gradientStops=Y.gradientStops.map((G)=>{let W={...G};if(W.color)W.color=e3(W.color);return delete W.boundVariables,W});if(Y.color)Y.color=e3(Y.color);return Y});if($.strokes&&$.strokes.length>0)X.strokes=$.strokes.map((Q)=>{let Y={...Q};if(delete Y.boundVariables,Y.color)Y.color=e3(Y.color);return Y});if($.cornerRadius!==void 0)X.cornerRadius=$.cornerRadius;if($.absoluteBoundingBox)X.absoluteBoundingBox=$.absoluteBoundingBox;if($.characters)X.characters=$.characters;if($.style)X.style={fontFamily:$.style.fontFamily,fontStyle:$.style.fontStyle,fontWeight:$.style.fontWeight,fontSize:$.style.fontSize,textAlignHorizontal:$.style.textAlignHorizontal,letterSpacing:$.style.letterSpacing,lineHeightPx:$.style.lineHeightPx};if($.children)X.children=$.children.map((Q)=>f3(Q)).filter((Q)=>Q!==null);return X}var o6=M$("ptdTool");function k1($){$.tool("get_document_info","Get detailed information about the current Figma document",{},async()=>{try{let X=await K("get_document_info");return{content:[{type:"text",text:JSON.stringify(X)}]}}catch(X){return{content:[{type:"text",text:`Error getting document info: ${X instanceof Error?X.message:String(X)}`}]}}}),$.tool("get_selection","Get information about the current selection in Figma",{},async()=>{try{let X=await K("get_selection");return{content:[{type:"text",text:JSON.stringify(X)}]}}catch(X){return{content:[{type:"text",text:`Error getting selection: ${X instanceof Error?X.message:String(X)}`}]}}}),$.tool("get_node_info","Get detailed information about a specific node in Figma",{nodeId:J.string().describe("The ID of the node to get information about")},async({nodeId:X})=>{try{let Q=await K("get_node_info",{nodeId:X});return{content:[{type:"text",text:JSON.stringify(f3(Q))}]}}catch(Q){return{content:[{type:"text",text:`Error getting node info: ${Q instanceof Error?Q.message:String(Q)}`}]}}}),$.tool("get_nodes_info","Get detailed information about multiple nodes in Figma",{nodeIds:J.array(J.string()).describe("Array of node IDs to get information about")},async({nodeIds:X})=>{try{let Q=await Promise.all(X.map(async(Y)=>{let G=await K("get_node_info",{nodeId:Y});return{nodeId:Y,info:G}}));return{content:[{type:"text",text:JSON.stringify(Q.map((Y)=>f3(Y.info)))}]}}catch(Q){return{content:[{type:"text",text:`Error getting nodes info: ${Q instanceof Error?Q.message:String(Q)}`}]}}}),$.tool("create_rectangle","Create a new rectangle in Figma",{x:J.number().describe("X position"),y:J.number().describe("Y position"),width:J.number().describe("Width of the rectangle"),height:J.number().describe("Height of the rectangle"),name:J.string().optional().describe("Optional name for the rectangle"),parentId:J.string().optional().describe("Optional parent node ID to append the rectangle to")},async({x:X,y:Q,width:Y,height:G,name:W,parentId:H})=>{try{let B=await K("create_rectangle",{x:X,y:Q,width:Y,height:G,name:W||"Rectangle",parentId:H});return{content:[{type:"text",text:`Created rectangle "${JSON.stringify(B)}"`}]}}catch(B){return{content:[{type:"text",text:`Error creating rectangle: ${B instanceof Error?B.message:String(B)}`}]}}}),$.tool("create_frame","Create a new frame in Figma",{x:J.number().describe("X position"),y:J.number().describe("Y position"),width:J.number().describe("Width of the frame"),height:J.number().describe("Height of the frame"),name:J.string().optional().describe("Optional name for the frame"),parentId:J.string().optional().describe("Optional parent node ID to append the frame to"),fillColor:J.object({r:J.number().min(0).max(1).describe("Red component (0-1)"),g:J.number().min(0).max(1).describe("Green component (0-1)"),b:J.number().min(0).max(1).describe("Blue component (0-1)"),a:J.number().min(0).max(1).optional().describe("Alpha component (0-1)")}).optional().describe("Fill color in RGBA format"),strokeColor:J.object({r:J.number().min(0).max(1).describe("Red component (0-1)"),g:J.number().min(0).max(1).describe("Green component (0-1)"),b:J.number().min(0).max(1).describe("Blue component (0-1)"),a:J.number().min(0).max(1).optional().describe("Alpha component (0-1)")}).optional().describe("Stroke color in RGBA format"),strokeWeight:J.number().positive().optional().describe("Stroke weight"),layoutMode:J.enum(["NONE","HORIZONTAL","VERTICAL"]).optional().describe("Auto-layout mode for the frame"),layoutWrap:J.enum(["NO_WRAP","WRAP"]).optional().describe("Whether the auto-layout frame wraps its children"),paddingTop:J.number().optional().describe("Top padding for auto-layout frame"),paddingRight:J.number().optional().describe("Right padding for auto-layout frame"),paddingBottom:J.number().optional().describe("Bottom padding for auto-layout frame"),paddingLeft:J.number().optional().describe("Left padding for auto-layout frame"),primaryAxisAlignItems:J.enum(["MIN","MAX","CENTER","SPACE_BETWEEN"]).optional().describe("Primary axis alignment for auto-layout frame. Note: When set to SPACE_BETWEEN, itemSpacing will be ignored as children will be evenly spaced."),counterAxisAlignItems:J.enum(["MIN","MAX","CENTER","BASELINE"]).optional().describe("Counter axis alignment for auto-layout frame"),layoutSizingHorizontal:J.enum(["FIXED","HUG","FILL"]).optional().describe("Horizontal sizing mode for auto-layout frame"),layoutSizingVertical:J.enum(["FIXED","HUG","FILL"]).optional().describe("Vertical sizing mode for auto-layout frame"),itemSpacing:J.number().optional().describe("Distance between children in auto-layout frame. Note: This value will be ignored if primaryAxisAlignItems is set to SPACE_BETWEEN.")},async({x:X,y:Q,width:Y,height:G,name:W,parentId:H,fillColor:B,strokeColor:D,strokeWeight:V,layoutMode:j,layoutWrap:P,paddingTop:I,paddingRight:l,paddingBottom:R,paddingLeft:d$,primaryAxisAlignItems:o$,counterAxisAlignItems:a$,layoutSizingHorizontal:P3,layoutSizingVertical:y,itemSpacing:X$})=>{try{let G0=await K("create_frame",{x:X,y:Q,width:Y,height:G,name:W||"Frame",parentId:H,fillColor:B||{r:1,g:1,b:1,a:1},strokeColor:D,strokeWeight:V,layoutMode:j,layoutWrap:P,paddingTop:I,paddingRight:l,paddingBottom:R,paddingLeft:d$,primaryAxisAlignItems:o$,counterAxisAlignItems:a$,layoutSizingHorizontal:P3,layoutSizingVertical:y,itemSpacing:X$});return{content:[{type:"text",text:`Created frame "${G0.name}" with ID: ${G0.id}. Use the ID as the parentId to appendChild inside this frame.`}]}}catch(r){return{content:[{type:"text",text:`Error creating frame: ${r instanceof Error?r.message:String(r)}`}]}}}),$.tool("create_text","Create a new text element in Figma",{x:J.number().describe("X position"),y:J.number().describe("Y position"),text:J.string().describe("Text content"),fontSize:J.number().optional().describe("Font size (default: 14)"),fontWeight:J.number().optional().describe("Font weight (e.g., 400 for Regular, 700 for Bold)"),fontColor:J.object({r:J.number().min(0).max(1).describe("Red component (0-1)"),g:J.number().min(0).max(1).describe("Green component (0-1)"),b:J.number().min(0).max(1).describe("Blue component (0-1)"),a:J.number().min(0).max(1).optional().describe("Alpha component (0-1)")}).optional().describe("Font color in RGBA format"),name:J.string().optional().describe("Semantic layer name for the text node"),parentId:J.string().optional().describe("Optional parent node ID to append the text to")},async({x:X,y:Q,text:Y,fontSize:G,fontWeight:W,fontColor:H,name:B,parentId:D})=>{try{let j=await K("create_text",{x:X,y:Q,text:Y,fontSize:G||14,fontWeight:W||400,fontColor:H||{r:0,g:0,b:0,a:1},name:B||"Text",parentId:D});return{content:[{type:"text",text:`Created text "${j.name}" with ID: ${j.id}`}]}}catch(V){return{content:[{type:"text",text:`Error creating text: ${V instanceof Error?V.message:String(V)}`}]}}}),$.tool("set_fill_color","Set the fill color of a node in Figma can be TextNode or FrameNode",{nodeId:J.string().describe("The ID of the node to modify"),r:J.number().min(0).max(1).describe("Red component (0-1)"),g:J.number().min(0).max(1).describe("Green component (0-1)"),b:J.number().min(0).max(1).describe("Blue component (0-1)"),a:J.number().min(0).max(1).optional().describe("Alpha component (0-1)")},async({nodeId:X,r:Q,g:Y,b:G,a:W})=>{try{return{content:[{type:"text",text:`Set fill color of node "${(await K("set_fill_color",{nodeId:X,color:{r:Q,g:Y,b:G,a:W||1}})).name}" to RGBA(${Q}, ${Y}, ${G}, ${W||1})`}]}}catch(H){return{content:[{type:"text",text:`Error setting fill color: ${H instanceof Error?H.message:String(H)}`}]}}}),$.tool("set_stroke_color","Set the stroke color of a node in Figma",{nodeId:J.string().describe("The ID of the node to modify"),r:J.number().min(0).max(1).describe("Red component (0-1)"),g:J.number().min(0).max(1).describe("Green component (0-1)"),b:J.number().min(0).max(1).describe("Blue component (0-1)"),a:J.number().min(0).max(1).optional().describe("Alpha component (0-1)"),weight:J.number().positive().optional().describe("Stroke weight")},async({nodeId:X,r:Q,g:Y,b:G,a:W,weight:H})=>{try{return{content:[{type:"text",text:`Set stroke color of node "${(await K("set_stroke_color",{nodeId:X,color:{r:Q,g:Y,b:G,a:W||1},weight:H||1})).name}" to RGBA(${Q}, ${Y}, ${G}, ${W||1}) with weight ${H||1}`}]}}catch(B){return{content:[{type:"text",text:`Error setting stroke color: ${B instanceof Error?B.message:String(B)}`}]}}}),$.tool("move_node","Move a node to a new position in Figma",{nodeId:J.string().describe("The ID of the node to move"),x:J.number().describe("New X position"),y:J.number().describe("New Y position")},async({nodeId:X,x:Q,y:Y})=>{try{return{content:[{type:"text",text:`Moved node "${(await K("move_node",{nodeId:X,x:Q,y:Y})).name}" to position (${Q}, ${Y})`}]}}catch(G){return{content:[{type:"text",text:`Error moving node: ${G instanceof Error?G.message:String(G)}`}]}}}),$.tool("clone_node","Clone an existing node in Figma",{nodeId:J.string().describe("The ID of the node to clone"),x:J.number().optional().describe("New X position for the clone"),y:J.number().optional().describe("New Y position for the clone")},async({nodeId:X,x:Q,y:Y})=>{try{let W=await K("clone_node",{nodeId:X,x:Q,y:Y});return{content:[{type:"text",text:`Cloned node "${W.name}" with new ID: ${W.id}${Q!==void 0&&Y!==void 0?` at position (${Q}, ${Y})`:""}`}]}}catch(G){return{content:[{type:"text",text:`Error cloning node: ${G instanceof Error?G.message:String(G)}`}]}}}),$.tool("resize_node","Resize a node in Figma",{nodeId:J.string().describe("The ID of the node to resize"),width:J.number().positive().describe("New width"),height:J.number().positive().describe("New height")},async({nodeId:X,width:Q,height:Y})=>{try{return{content:[{type:"text",text:`Resized node "${(await K("resize_node",{nodeId:X,width:Q,height:Y})).name}" to width ${Q} and height ${Y}`}]}}catch(G){return{content:[{type:"text",text:`Error resizing node: ${G instanceof Error?G.message:String(G)}`}]}}}),$.tool("delete_multiple_nodes","Delete multiple nodes from Figma at once",{nodeIds:J.array(J.string()).describe("Array of node IDs to delete")},async({nodeIds:X})=>{try{let Q=await K("delete_multiple_nodes",{nodeIds:X});return{content:[{type:"text",text:JSON.stringify(Q)}]}}catch(Q){return{content:[{type:"text",text:`Error deleting multiple nodes: ${Q instanceof Error?Q.message:String(Q)}`}]}}}),$.tool("export_node_as_image","Export a node as an image from Figma",{nodeId:J.string().describe("The ID of the node to export"),format:J.enum(["PNG","JPG","SVG","PDF"]).optional().describe("Export format"),scale:J.number().positive().optional().describe("Export scale")},async({nodeId:X,format:Q,scale:Y})=>{try{let W=await K("export_node_as_image",{nodeId:X,format:Q||"PNG",scale:Y||1});return{content:[{type:"image",data:W.imageData,mimeType:W.mimeType||"image/png"}]}}catch(G){return{content:[{type:"text",text:`Error exporting node as image: ${G instanceof Error?G.message:String(G)}`}]}}}),$.tool("set_text_content","Set the text content of an existing text node in Figma",{nodeId:J.string().describe("The ID of the text node to modify"),text:J.string().describe("New text content")},async({nodeId:X,text:Q})=>{try{return{content:[{type:"text",text:`Updated text content of node "${(await K("set_text_content",{nodeId:X,text:Q})).name}" to "${Q}"`}]}}catch(Y){return{content:[{type:"text",text:`Error setting text content: ${Y instanceof Error?Y.message:String(Y)}`}]}}}),$.tool("get_styles","Get all styles from the current Figma document",{},async()=>{try{let X=await K("get_styles");return{content:[{type:"text",text:JSON.stringify(X)}]}}catch(X){return{content:[{type:"text",text:`Error getting styles: ${X instanceof Error?X.message:String(X)}`}]}}}),$.tool("get_local_components","Get all local components from the Figma document",{},async()=>{try{let X=await K("get_local_components");return{content:[{type:"text",text:JSON.stringify(X)}]}}catch(X){return{content:[{type:"text",text:`Error getting local components: ${X instanceof Error?X.message:String(X)}`}]}}}),$.tool("get_annotations","Get all annotations in the current document or specific node",{nodeId:J.string().optional().describe("Optional node ID to get annotations for specific node"),includeCategories:J.boolean().optional().default(!0).describe("Whether to include category information")},async({nodeId:X,includeCategories:Q})=>{try{let Y=await K("get_annotations",{nodeId:X,includeCategories:Q});return{content:[{type:"text",text:JSON.stringify(Y)}]}}catch(Y){return{content:[{type:"text",text:`Error getting annotations: ${Y instanceof Error?Y.message:String(Y)}`}]}}}),$.tool("set_multiple_annotations","Set multiple annotations parallelly in a node",{nodeId:J.string().describe("The ID of the node containing the elements to annotate"),annotations:J.array(J.object({nodeId:J.string().describe("The ID of the node to annotate"),labelMarkdown:J.string().describe("The annotation text in markdown format"),categoryId:J.string().optional().describe("The ID of the annotation category"),annotationId:J.string().optional().describe("The ID of the annotation to update (if updating existing annotation)"),properties:J.array(J.object({type:J.string()})).optional().describe("Additional properties for the annotation")})).describe("Array of annotations to apply")},async({nodeId:X,annotations:Q},Y)=>{try{if(!Q||Q.length===0)return{content:[{type:"text",text:"No annotations provided"}]};let G={type:"text",text:`Starting annotation process for ${Q.length} nodes. This will be processed in batches of 5...`},W=0,H=Q.length,D=await K("set_multiple_annotations",{nodeId:X,annotations:Q}),V=D.annotationsApplied&&D.annotationsApplied>0,j=`
7
- Annotation process completed:
8
- - ${D.annotationsApplied||0} of ${H} successfully applied
9
- - ${D.annotationsFailed||0} failed
10
- - Processed in ${D.completedInChunks||1} batches
11
- `,I=(D.results||[]).filter((R)=>!R.success),l="";if(I.length>0)l=`
12
-
13
- Nodes that failed:
14
- ${I.map((R)=>`- ${R.nodeId}: ${R.error||"Unknown error"}`).join(`
15
- `)}`;return{content:[G,{type:"text",text:j+l}]}}catch(G){return{content:[{type:"text",text:`Error setting multiple annotations: ${G instanceof Error?G.message:String(G)}`}]}}}),$.tool("create_component_instance","Create an instance of a component in Figma",{componentKey:J.string().describe("Key of the component to instantiate"),x:J.number().describe("X position"),y:J.number().describe("Y position")},async({componentKey:X,x:Q,y:Y})=>{try{let W=await K("create_component_instance",{componentKey:X,x:Q,y:Y});return{content:[{type:"text",text:JSON.stringify(W)}]}}catch(G){return{content:[{type:"text",text:`Error creating component instance: ${G instanceof Error?G.message:String(G)}`}]}}}),$.tool("get_instance_overrides","Get all override properties from a selected component instance. These overrides can be applied to other instances, which will swap them to match the source component.",{nodeId:J.string().optional().describe("Optional ID of the component instance to get overrides from. If not provided, currently selected instance will be used.")},async({nodeId:X})=>{try{let Y=await K("get_instance_overrides",{instanceNodeId:X||null});return{content:[{type:"text",text:Y.success?`Successfully got instance overrides: ${Y.message}`:`Failed to get instance overrides: ${Y.message}`}]}}catch(Q){return{content:[{type:"text",text:`Error copying instance overrides: ${Q instanceof Error?Q.message:String(Q)}`}]}}}),$.tool("set_instance_overrides","Apply previously copied overrides to selected component instances. Target instances will be swapped to the source component and all copied override properties will be applied.",{sourceInstanceId:J.string().describe("ID of the source component instance"),targetNodeIds:J.array(J.string()).describe("Array of target instance IDs. Currently selected instances will be used.")},async({sourceInstanceId:X,targetNodeIds:Q})=>{try{let G=await K("set_instance_overrides",{sourceInstanceId:X,targetNodeIds:Q||[]});if(G.success){let W=G.results?.filter((H)=>H.success).length||0;return{content:[{type:"text",text:`Successfully applied ${G.totalCount||0} overrides to ${W} instances.`}]}}else return{content:[{type:"text",text:`Failed to set instance overrides: ${G.message}`}]}}catch(Y){return{content:[{type:"text",text:`Error setting instance overrides: ${Y instanceof Error?Y.message:String(Y)}`}]}}}),$.tool("set_corner_radius","Set the corner radius of a node in Figma",{nodeId:J.string().describe("The ID of the node to modify"),radius:J.number().min(0).describe("Corner radius value"),corners:J.array(J.boolean()).length(4).optional().describe("Optional array of 4 booleans to specify which corners to round [topLeft, topRight, bottomRight, bottomLeft]")},async({nodeId:X,radius:Q,corners:Y})=>{try{return{content:[{type:"text",text:`Set corner radius of node "${(await K("set_corner_radius",{nodeId:X,radius:Q,corners:Y||[!0,!0,!0,!0]})).name}" to ${Q}px`}]}}catch(G){return{content:[{type:"text",text:`Error setting corner radius: ${G instanceof Error?G.message:String(G)}`}]}}}),$.prompt("design_strategy","Best practices for working with Figma designs",(X)=>{return{messages:[{role:"assistant",content:{type:"text",text:`When working with Figma designs, follow these best practices:
16
-
17
- 1. Start with Document Structure:
18
- - First use get_document_info() to understand the current document
19
- - Plan your layout hierarchy before creating elements
20
- - Create a main container frame for each screen/section
21
- - If a component library has already been provided, please prioritize creating elements using component instances
22
- 2. Naming Conventions:
23
- - Use descriptive, semantic names for all elements
24
- - Follow a consistent naming pattern (e.g., "Login Screen", "Logo Container", "Email Input")
25
- - Group related elements with meaningful names
26
-
27
- 3. Layout Hierarchy:
28
- - Create parent frames first, then add child elements
29
- - For forms/login screens:
30
- * Start with the main screen container frame
31
- * Create a logo container at the top
32
- * Group input fields in their own containers
33
- * Place action buttons (login, submit) after inputs
34
- * Add secondary elements (forgot password, signup links) last
35
-
36
- 4. Input Fields Structure:
37
- - Create a container frame for each input field
38
- - Include a label text above or inside the input
39
- - Group related inputs (e.g., username/password) together
40
-
41
- 5. Element Creation:
42
- - Use create_frame() for containers and input fields
43
- - Use create_text() for labels, buttons text, and links
44
- - Set appropriate colors and styles:
45
- * Use fillColor for backgrounds
46
- * Use strokeColor for borders
47
- * Set proper fontWeight for different text elements
48
-
49
- 6. Mofifying existing elements:
50
- - use set_text_content() to modify text content.
51
-
52
- 7. Visual Hierarchy:
53
- - Position elements in logical reading order (top to bottom)
54
- - Maintain consistent spacing between elements
55
- - Use appropriate font sizes for different text types:
56
- * Larger for headings/welcome text
57
- * Medium for input labels
58
- * Standard for button text
59
- * Smaller for helper text/links
60
-
61
- 8. Best Practices:
62
- - Verify each creation with get_node_info()
63
- - Use parentId to maintain proper hierarchy
64
- - Group related elements together in frames
65
- - Keep consistent spacing and alignment
66
-
67
- Example Login Screen Structure:
68
- - Login Screen (main frame)
69
- - Logo Container (frame)
70
- - Logo (image/text)
71
- - Welcome Text (text)
72
- - Input Container (frame)
73
- - Email Input (frame)
74
- - Email Label (text)
75
- - Email Field (frame)
76
- - Password Input (frame)
77
- - Password Label (text)
78
- - Password Field (frame)
79
- - Login Button (frame)
80
- - Button Text (text)
81
- - Helper Links (frame)
82
- - Forgot Password (text)
83
- - Don't have account (text)`}}],description:"Best practices for working with Figma designs"}}),$.prompt("read_design_strategy","Best practices for reading Figma designs",(X)=>{return{messages:[{role:"assistant",content:{type:"text",text:`When reading Figma designs, follow these best practices:
84
-
85
- 1. Start with selection:
86
- - First use read_my_design() to understand the current selection
87
- - If no selection ask user to select single or multiple nodes
88
- `}}],description:"Best practices for reading Figma designs"}}),$.tool("scan_text_nodes","Scan all text nodes in the selected Figma node",{nodeId:J.string().describe("ID of the node to scan")},async({nodeId:X})=>{try{let Q={type:"text",text:"Starting text node scanning. This may take a moment for large designs..."},Y=await K("scan_text_nodes",{nodeId:X,useChunking:!0,chunkSize:10});if(Y&&typeof Y==="object"&&"chunks"in Y){let G=Y,W=`
89
- Scan completed:
90
- - Found ${G.totalNodes} text nodes
91
- - Processed in ${G.chunks} chunks
92
- `;return{content:[Q,{type:"text",text:W},{type:"text",text:JSON.stringify(G.textNodes,null,2)}]}}return{content:[Q,{type:"text",text:JSON.stringify(Y,null,2)}]}}catch(Q){return{content:[{type:"text",text:`Error scanning text nodes: ${Q instanceof Error?Q.message:String(Q)}`}]}}}),$.tool("scan_nodes_by_types","Scan for child nodes with specific types in the selected Figma node",{nodeId:J.string().describe("ID of the node to scan"),types:J.array(J.string()).describe("Array of node types to find in the child nodes (e.g. ['COMPONENT', 'FRAME'])")},async({nodeId:X,types:Q})=>{try{let Y={type:"text",text:`Starting node type scanning for types: ${Q.join(", ")}...`},G=await K("scan_nodes_by_types",{nodeId:X,types:Q});if(G&&typeof G==="object"&&"matchingNodes"in G){let W=G,H=`Scan completed: Found ${W.count} nodes matching types: ${W.searchedTypes.join(", ")}`;return{content:[Y,{type:"text",text:H},{type:"text",text:JSON.stringify(W.matchingNodes,null,2)}]}}return{content:[Y,{type:"text",text:JSON.stringify(G,null,2)}]}}catch(Y){return{content:[{type:"text",text:`Error scanning nodes by types: ${Y instanceof Error?Y.message:String(Y)}`}]}}}),$.prompt("text_replacement_strategy","Systematic approach for replacing text in Figma designs",(X)=>{return{messages:[{role:"assistant",content:{type:"text",text:`# Intelligent Text Replacement Strategy
93
-
94
- ## 1. Analyze Design & Identify Structure
95
- - Scan text nodes to understand the overall structure of the design
96
- - Use AI pattern recognition to identify logical groupings:
97
- * Tables (rows, columns, headers, cells)
98
- * Lists (items, headers, nested lists)
99
- * Card groups (similar cards with recurring text fields)
100
- * Forms (labels, input fields, validation text)
101
- * Navigation (menu items, breadcrumbs)
102
- \`\`\`
103
- scan_text_nodes(nodeId: "node-id")
104
- get_node_info(nodeId: "node-id") // optional
105
- \`\`\`
106
-
107
- ## 2. Strategic Chunking for Complex Designs
108
- - Divide replacement tasks into logical content chunks based on design structure
109
- - Use one of these chunking strategies that best fits the design:
110
- * **Structural Chunking**: Table rows/columns, list sections, card groups
111
- * **Spatial Chunking**: Top-to-bottom, left-to-right in screen areas
112
- * **Semantic Chunking**: Content related to the same topic or functionality
113
- * **Component-Based Chunking**: Process similar component instances together
114
-
115
- ## 3. Progressive Replacement with Verification
116
- - Create a safe copy of the node for text replacement
117
- - Replace text chunk by chunk with continuous progress updates
118
- - After each chunk is processed:
119
- * Export that section as a small, manageable image
120
- * Verify text fits properly and maintain design integrity
121
- * Fix issues before proceeding to the next chunk
122
-
123
- \`\`\`
124
- // Clone the node to create a safe copy
125
- clone_node(nodeId: "selected-node-id", x: [new-x], y: [new-y])
126
-
127
- // Replace text chunk by chunk
128
- set_multiple_text_contents(
129
- nodeId: "parent-node-id",
130
- text: [
131
- { nodeId: "node-id-1", text: "New text 1" },
132
- // More nodes in this chunk...
133
- ]
134
- )
135
-
136
- // Verify chunk with small, targeted image exports
137
- export_node_as_image(nodeId: "chunk-node-id", format: "PNG", scale: 0.5)
138
- \`\`\`
139
-
140
- ## 4. Intelligent Handling for Table Data
141
- - For tabular content:
142
- * Process one row or column at a time
143
- * Maintain alignment and spacing between cells
144
- * Consider conditional formatting based on cell content
145
- * Preserve header/data relationships
146
-
147
- ## 5. Smart Text Adaptation
148
- - Adaptively handle text based on container constraints:
149
- * Auto-detect space constraints and adjust text length
150
- * Apply line breaks at appropriate linguistic points
151
- * Maintain text hierarchy and emphasis
152
- * Consider font scaling for critical content that must fit
153
-
154
- ## 6. Progressive Feedback Loop
155
- - Establish a continuous feedback loop during replacement:
156
- * Real-time progress updates (0-100%)
157
- * Small image exports after each chunk for verification
158
- * Issues identified early and resolved incrementally
159
- * Quick adjustments applied to subsequent chunks
160
-
161
- ## 7. Final Verification & Context-Aware QA
162
- - After all chunks are processed:
163
- * Export the entire design at reduced scale for final verification
164
- * Check for cross-chunk consistency issues
165
- * Verify proper text flow between different sections
166
- * Ensure design harmony across the full composition
167
-
168
- ## 8. Chunk-Specific Export Scale Guidelines
169
- - Scale exports appropriately based on chunk size:
170
- * Small chunks (1-5 elements): scale 1.0
171
- * Medium chunks (6-20 elements): scale 0.7
172
- * Large chunks (21-50 elements): scale 0.5
173
- * Very large chunks (50+ elements): scale 0.3
174
- * Full design verification: scale 0.2
175
-
176
- ## Sample Chunking Strategy for Common Design Types
177
-
178
- ### Tables
179
- - Process by logical rows (5-10 rows per chunk)
180
- - Alternative: Process by column for columnar analysis
181
- - Tip: Always include header row in first chunk for reference
182
-
183
- ### Card Lists
184
- - Group 3-5 similar cards per chunk
185
- - Process entire cards to maintain internal consistency
186
- - Verify text-to-image ratio within cards after each chunk
187
-
188
- ### Forms
189
- - Group related fields (e.g., "Personal Information", "Payment Details")
190
- - Process labels and input fields together
191
- - Ensure validation messages and hints are updated with their fields
192
-
193
- ### Navigation & Menus
194
- - Process hierarchical levels together (main menu, submenu)
195
- - Respect information architecture relationships
196
- - Verify menu fit and alignment after replacement
197
-
198
- ## Best Practices
199
- - **Preserve Design Intent**: Always prioritize design integrity
200
- - **Structural Consistency**: Maintain alignment, spacing, and hierarchy
201
- - **Visual Feedback**: Verify each chunk visually before proceeding
202
- - **Incremental Improvement**: Learn from each chunk to improve subsequent ones
203
- - **Balance Automation & Control**: Let AI handle repetitive replacements but maintain oversight
204
- - **Respect Content Relationships**: Keep related content consistent across chunks
205
-
206
- Remember that text is never just text—it's a core design element that must work harmoniously with the overall composition. This chunk-based strategy allows you to methodically transform text while maintaining design integrity.`}}],description:"Systematic approach for replacing text in Figma designs"}}),$.tool("set_multiple_text_contents","Set multiple text contents parallelly in a node",{nodeId:J.string().describe("The ID of the node containing the text nodes to replace"),text:J.array(J.object({nodeId:J.string().describe("The ID of the text node"),text:J.string().describe("The replacement text")})).describe("Array of text node IDs and their replacement texts")},async({nodeId:X,text:Q},Y)=>{try{if(!Q||Q.length===0)return{content:[{type:"text",text:"No text provided"}]};let G={type:"text",text:`Starting text replacement for ${Q.length} nodes. This will be processed in batches of 5...`},W=0,H=Q.length,D=await K("set_multiple_text_contents",{nodeId:X,text:Q}),V=D.replacementsApplied&&D.replacementsApplied>0,j=`
207
- Text replacement completed:
208
- - ${D.replacementsApplied||0} of ${H} successfully updated
209
- - ${D.replacementsFailed||0} failed
210
- - Processed in ${D.completedInChunks||1} batches
211
- `,I=(D.results||[]).filter((R)=>!R.success),l="";if(I.length>0)l=`
212
-
213
- Nodes that failed:
214
- ${I.map((R)=>`- ${R.nodeId}: ${R.error||"Unknown error"}`).join(`
215
- `)}`;return{content:[G,{type:"text",text:j+l}]}}catch(G){return{content:[{type:"text",text:`Error setting multiple text contents: ${G instanceof Error?G.message:String(G)}`}]}}}),$.tool("read_my_design","Get detailed information about the current selection in Figma, including all node details",{},async()=>{try{let X=await K("read_my_design",{});return{content:[{type:"text",text:JSON.stringify(X)}]}}catch(X){return{content:[{type:"text",text:`Error getting node info: ${X instanceof Error?X.message:String(X)}`}]}}}),$.prompt("annotation_conversion_strategy","Strategy for converting manual annotations to Figma's native annotations",(X)=>{return{messages:[{role:"assistant",content:{type:"text",text:`# Automatic Annotation Conversion
216
-
217
- ## Process Overview
218
-
219
- The process of converting manual annotations (numbered/alphabetical indicators with connected descriptions) to Figma's native annotations:
220
-
221
- 1. Get selected frame/component information
222
- 2. Scan and collect all annotation text nodes
223
- 3. Scan target UI elements (components, instances, frames)
224
- 4. Match annotations to appropriate UI elements
225
- 5. Apply native Figma annotations
226
-
227
- ## Step 1: Get Selection and Initial Setup
228
-
229
- First, get the selected frame or component that contains annotations:
230
-
231
- \`\`\`typescript
232
- // Get the selected frame/component
233
- const selection = await get_selection();
234
- const selectedNodeId = selection[0].id
235
-
236
- // Get available annotation categories for later use
237
- const annotationData = await get_annotations({
238
- nodeId: selectedNodeId,
239
- includeCategories: true
240
- });
241
- const categories = annotationData.categories;
242
- \`\`\`
243
-
244
- ## Step 2: Scan Annotation Text Nodes
245
-
246
- Scan all text nodes to identify annotations and their descriptions:
247
-
248
- \`\`\`typescript
249
- // Get all text nodes in the selection
250
- const textNodes = await scan_text_nodes({
251
- nodeId: selectedNodeId
252
- });
253
-
254
- // Filter and group annotation markers and descriptions
255
-
256
- // Markers typically have these characteristics:
257
- // - Short text content (usually single digit/letter)
258
- // - Specific font styles (often bold)
259
- // - Located in a container with "Marker" or "Dot" in the name
260
- // - Have a clear naming pattern (e.g., "1", "2", "3" or "A", "B", "C")
261
-
262
-
263
- // Identify description nodes
264
- // Usually longer text nodes near markers or with matching numbers in path
265
-
266
- \`\`\`
267
-
268
- ## Step 3: Scan Target UI Elements
269
-
270
- Get all potential target elements that annotations might refer to:
271
-
272
- \`\`\`typescript
273
- // Scan for all UI elements that could be annotation targets
274
- const targetNodes = await scan_nodes_by_types({
275
- nodeId: selectedNodeId,
276
- types: [
277
- "COMPONENT",
278
- "INSTANCE",
279
- "FRAME"
280
- ]
281
- });
282
- \`\`\`
283
-
284
- ## Step 4: Match Annotations to Targets
285
-
286
- Match each annotation to its target UI element using these strategies in order of priority:
287
-
288
- 1. **Path-Based Matching**:
289
- - Look at the marker's parent container name in the Figma layer hierarchy
290
- - Remove any "Marker:" or "Annotation:" prefixes from the parent name
291
- - Find UI elements that share the same parent name or have it in their path
292
- - This works well when markers are grouped with their target elements
293
-
294
- 2. **Name-Based Matching**:
295
- - Extract key terms from the annotation description
296
- - Look for UI elements whose names contain these key terms
297
- - Consider both exact matches and semantic similarities
298
- - Particularly effective for form fields, buttons, and labeled components
299
-
300
- 3. **Proximity-Based Matching** (fallback):
301
- - Calculate the center point of the marker
302
- - Find the closest UI element by measuring distances to element centers
303
- - Consider the marker's position relative to nearby elements
304
- - Use this method when other matching strategies fail
305
-
306
- Additional Matching Considerations:
307
- - Give higher priority to matches found through path-based matching
308
- - Consider the type of UI element when evaluating matches
309
- - Take into account the annotation's context and content
310
- - Use a combination of strategies for more accurate matching
311
-
312
- ## Step 5: Apply Native Annotations
313
-
314
- Convert matched annotations to Figma's native annotations using batch processing:
315
-
316
- \`\`\`typescript
317
- // Prepare annotations array for batch processing
318
- const annotationsToApply = Object.values(annotations).map(({ marker, description }) => {
319
- // Find target using multiple strategies
320
- const target =
321
- findTargetByPath(marker, targetNodes) ||
322
- findTargetByName(description, targetNodes) ||
323
- findTargetByProximity(marker, targetNodes);
324
-
325
- if (target) {
326
- // Determine appropriate category based on content
327
- const category = determineCategory(description.characters, categories);
328
-
329
- // Determine appropriate additional annotationProperty based on content
330
- const annotationProperty = determineProperties(description.characters, target.type);
331
-
332
- return {
333
- nodeId: target.id,
334
- labelMarkdown: description.characters,
335
- categoryId: category.id,
336
- properties: annotationProperty
337
- };
338
- }
339
- return null;
340
- }).filter(Boolean); // Remove null entries
341
-
342
- // Apply annotations in batches using set_multiple_annotations
343
- if (annotationsToApply.length > 0) {
344
- await set_multiple_annotations({
345
- nodeId: selectedNodeId,
346
- annotations: annotationsToApply
347
- });
348
- }
349
- \`\`\`
350
-
351
-
352
- This strategy focuses on practical implementation based on real-world usage patterns, emphasizing the importance of handling various UI elements as annotation targets, not just text nodes.`}}],description:"Strategy for converting manual annotations to Figma's native annotations"}}),$.prompt("swap_overrides_instances","Guide to swap instance overrides between instances",(X)=>{return{messages:[{role:"assistant",content:{type:"text",text:`# Swap Component Instance and Override Strategy
353
-
354
- ## Overview
355
- This strategy enables transferring content and property overrides from a source instance to one or more target instances in Figma, maintaining design consistency while reducing manual work.
356
-
357
- ## Step-by-Step Process
358
-
359
- ### 1. Selection Analysis
360
- - Use \`get_selection()\` to identify the parent component or selected instances
361
- - For parent components, scan for instances with \`scan_nodes_by_types({ nodeId: "parent-id", types: ["INSTANCE"] })\`
362
- - Identify custom slots by name patterns (e.g. "Custom Slot*" or "Instance Slot") or by examining text content
363
- - Determine which is the source instance (with content to copy) and which are targets (where to apply content)
364
-
365
- ### 2. Extract Source Overrides
366
- - Use \`get_instance_overrides()\` to extract customizations from the source instance
367
- - This captures text content, property values, and style overrides
368
- - Command syntax: \`get_instance_overrides({ nodeId: "source-instance-id" })\`
369
- - Look for successful response like "Got component information from [instance name]"
370
-
371
- ### 3. Apply Overrides to Targets
372
- - Apply captured overrides using \`set_instance_overrides()\`
373
- - Command syntax:
374
- \`\`\`
375
- set_instance_overrides({
376
- sourceInstanceId: "source-instance-id",
377
- targetNodeIds: ["target-id-1", "target-id-2", ...]
378
- })
379
- \`\`\`
380
-
381
- ### 4. Verification
382
- - Verify results with \`get_node_info()\` or \`read_my_design()\`
383
- - Confirm text content and style overrides have transferred successfully
384
-
385
- ## Key Tips
386
- - Always join the appropriate channel first with \`join_channel()\`
387
- - When working with multiple targets, check the full selection with \`get_selection()\`
388
- - Preserve component relationships by using instance overrides rather than direct text manipulation`}}],description:"Strategy for transferring overrides between component instances in Figma"}}),$.tool("set_layout_mode","Set the layout mode and wrap behavior of a frame in Figma",{nodeId:J.string().describe("The ID of the frame to modify"),layoutMode:J.enum(["NONE","HORIZONTAL","VERTICAL"]).describe("Layout mode for the frame"),layoutWrap:J.enum(["NO_WRAP","WRAP"]).optional().describe("Whether the auto-layout frame wraps its children")},async({nodeId:X,layoutMode:Q,layoutWrap:Y})=>{try{return{content:[{type:"text",text:`Set layout mode of frame "${(await K("set_layout_mode",{nodeId:X,layoutMode:Q,layoutWrap:Y||"NO_WRAP"})).name}" to ${Q}${Y?` with ${Y}`:""}`}]}}catch(G){return{content:[{type:"text",text:`Error setting layout mode: ${G instanceof Error?G.message:String(G)}`}]}}}),$.tool("set_annotation","Create or update an annotation",{nodeId:J.string().describe("The ID of the node to annotate"),annotationId:J.string().optional().describe("The ID of the annotation to update (if updating existing annotation)"),labelMarkdown:J.string().describe("The annotation text in markdown format"),categoryId:J.string().optional().describe("The ID of the annotation category"),properties:J.array(J.object({type:J.string()})).optional().describe("Additional properties for the annotation")},async({nodeId:X,annotationId:Q,labelMarkdown:Y,categoryId:G,properties:W})=>{try{let H=await K("set_annotation",{nodeId:X,annotationId:Q,labelMarkdown:Y,categoryId:G,properties:W});return{content:[{type:"text",text:JSON.stringify(H)}]}}catch(H){return{content:[{type:"text",text:`Error setting annotation: ${H instanceof Error?H.message:String(H)}`}]}}}),$.tool("set_padding","Set padding values for an auto-layout frame in Figma",{nodeId:J.string().describe("The ID of the frame to modify"),paddingTop:J.number().optional().describe("Top padding value"),paddingRight:J.number().optional().describe("Right padding value"),paddingBottom:J.number().optional().describe("Bottom padding value"),paddingLeft:J.number().optional().describe("Left padding value")},async({nodeId:X,paddingTop:Q,paddingRight:Y,paddingBottom:G,paddingLeft:W})=>{try{let B=await K("set_padding",{nodeId:X,paddingTop:Q,paddingRight:Y,paddingBottom:G,paddingLeft:W}),D=[];if(Q!==void 0)D.push(`top: ${Q}`);if(Y!==void 0)D.push(`right: ${Y}`);if(G!==void 0)D.push(`bottom: ${G}`);if(W!==void 0)D.push(`left: ${W}`);return{content:[{type:"text",text:`Set ${D.length>0?`padding (${D.join(", ")})`:"padding"} for frame "${B.name}"`}]}}catch(H){return{content:[{type:"text",text:`Error setting padding: ${H instanceof Error?H.message:String(H)}`}]}}}),$.tool("set_axis_align","Set primary and counter axis alignment for an auto-layout frame in Figma",{nodeId:J.string().describe("The ID of the frame to modify"),primaryAxisAlignItems:J.enum(["MIN","MAX","CENTER","SPACE_BETWEEN"]).optional().describe("Primary axis alignment (MIN/MAX = left/right in horizontal, top/bottom in vertical). Note: When set to SPACE_BETWEEN, itemSpacing will be ignored as children will be evenly spaced."),counterAxisAlignItems:J.enum(["MIN","MAX","CENTER","BASELINE"]).optional().describe("Counter axis alignment (MIN/MAX = top/bottom in horizontal, left/right in vertical)")},async({nodeId:X,primaryAxisAlignItems:Q,counterAxisAlignItems:Y})=>{try{let W=await K("set_axis_align",{nodeId:X,primaryAxisAlignItems:Q,counterAxisAlignItems:Y}),H=[];if(Q!==void 0)H.push(`primary: ${Q}`);if(Y!==void 0)H.push(`counter: ${Y}`);return{content:[{type:"text",text:`Set ${H.length>0?`axis alignment (${H.join(", ")})`:"axis alignment"} for frame "${W.name}"`}]}}catch(G){return{content:[{type:"text",text:`Error setting axis alignment: ${G instanceof Error?G.message:String(G)}`}]}}}),$.tool("set_layout_sizing","Set horizontal and vertical sizing modes for an auto-layout frame in Figma",{nodeId:J.string().describe("The ID of the frame to modify"),layoutSizingHorizontal:J.enum(["FIXED","HUG","FILL"]).optional().describe("Horizontal sizing mode (HUG for frames/text only, FILL for auto-layout children only)"),layoutSizingVertical:J.enum(["FIXED","HUG","FILL"]).optional().describe("Vertical sizing mode (HUG for frames/text only, FILL for auto-layout children only)")},async({nodeId:X,layoutSizingHorizontal:Q,layoutSizingVertical:Y})=>{try{let W=await K("set_layout_sizing",{nodeId:X,layoutSizingHorizontal:Q,layoutSizingVertical:Y}),H=[];if(Q!==void 0)H.push(`horizontal: ${Q}`);if(Y!==void 0)H.push(`vertical: ${Y}`);return{content:[{type:"text",text:`Set ${H.length>0?`layout sizing (${H.join(", ")})`:"layout sizing"} for frame "${W.name}"`}]}}catch(G){return{content:[{type:"text",text:`Error setting layout sizing: ${G instanceof Error?G.message:String(G)}`}]}}}),$.tool("set_item_spacing","Set distance between children in an auto-layout frame",{nodeId:J.string().describe("The ID of the frame to modify"),itemSpacing:J.number().describe("Distance between children. Note: This value will be ignored if primaryAxisAlignItems is set to SPACE_BETWEEN.")},async({nodeId:X,itemSpacing:Q})=>{try{let G=await K("set_item_spacing",{nodeId:X,itemSpacing:Q});return{content:[{type:"text",text:`Set item spacing to ${Q} for frame "${G.name}"`}]}}catch(Y){return{content:[{type:"text",text:`Error setting item spacing: ${Y instanceof Error?Y.message:String(Y)}`}]}}}),$.tool("get_reactions","Get Figma Prototyping Reactions from multiple nodes. CRITICAL: The output MUST be processed using the 'reaction_to_connector_strategy' prompt IMMEDIATELY to generate parameters for connector lines via the 'create_connections' tool.",{nodeIds:J.array(J.string()).describe("Array of node IDs to get reactions from")},async({nodeIds:X})=>{try{let Q=await K("get_reactions",{nodeIds:X});return{content:[{type:"text",text:JSON.stringify(Q)},{type:"text",text:"IMPORTANT: You MUST now use the reaction data above and follow the `reaction_to_connector_strategy` prompt to prepare the parameters for the `create_connections` tool call. This is a required next step."}],followUp:{type:"prompt",prompt:"reaction_to_connector_strategy"}}}catch(Q){return{content:[{type:"text",text:`Error getting reactions: ${Q instanceof Error?Q.message:String(Q)}`}]}}}),$.tool("set_default_connector","Set a copied connector node as the default connector",{connectorId:J.string().optional().describe("The ID of the connector node to set as default")},async({connectorId:X})=>{try{let Q=await K("set_default_connector",{connectorId:X});return{content:[{type:"text",text:`Default connector set: ${JSON.stringify(Q)}`}]}}catch(Q){return{content:[{type:"text",text:`Error setting default connector: ${Q instanceof Error?Q.message:String(Q)}`}]}}}),$.tool("delete_node","Delete a node from Figma",{nodeId:J.string().describe("The ID of the node to delete")},async({nodeId:X})=>{try{return await K("delete_node",{nodeId:X}),{content:[{type:"text",text:`Deleted node with ID: ${X}`}]}}catch(Q){return{content:[{type:"text",text:`Error deleting node: ${Q instanceof Error?Q.message:String(Q)}`}]}}}),$.tool("create_connections","Create connections between nodes using the default connector style",{connections:J.array(J.object({startNodeId:J.string().describe("ID of the starting node"),endNodeId:J.string().describe("ID of the ending node"),text:J.string().optional().describe("Optional text to display on the connector")})).describe("Array of node connections to create")},async({connections:X})=>{try{if(!X||X.length===0)return{content:[{type:"text",text:"No connections provided"}]};let Q=await K("create_connections",{connections:X});return{content:[{type:"text",text:`Created ${X.length} connections: ${JSON.stringify(Q)}`}]}}catch(Q){return{content:[{type:"text",text:`Error creating connections: ${Q instanceof Error?Q.message:String(Q)}`}]}}}),$.prompt("reaction_to_connector_strategy","Strategy for converting Figma prototype reactions to connector lines using the output of 'get_reactions'",(X)=>{return{messages:[{role:"assistant",content:{type:"text",text:`# Strategy: Convert Figma Prototype Reactions to Connector Lines
389
-
390
- ## Goal
391
- Process the JSON output from the \`get_reactions\` tool to generate an array of connection objects suitable for the \`create_connections\` tool. This visually represents prototype flows as connector lines on the Figma canvas.
392
-
393
- ## Input Data
394
- You will receive JSON data from the \`get_reactions\` tool. This data contains an array of nodes, each with potential reactions. A typical reaction object looks like this:
395
- \`\`\`json
396
- {
397
- "trigger": { "type": "ON_CLICK" },
398
- "action": {
399
- "type": "NAVIGATE",
400
- "destinationId": "destination-node-id",
401
- "navigationTransition": { ... },
402
- "preserveScrollPosition": false
403
- }
404
- }
405
- \`\`\`
406
-
407
- ## Step-by-Step Process
408
-
409
- ### 1. Preparation & Context Gathering
410
- - **Action:** Call \`read_my_design\` on the relevant node(s) to get context about the nodes involved (names, types, etc.). This helps in generating meaningful connector labels later.
411
- - **Action:** Call \`set_default_connector\` **without** the \`connectorId\` parameter.
412
- - **Check Result:** Analyze the response from \`set_default_connector\`.
413
- - If it confirms a default connector is already set (e.g., "Default connector is already set"), proceed to Step 2.
414
- - If it indicates no default connector is set (e.g., "No default connector set..."), you **cannot** proceed with \`create_connections\` yet. Inform the user they need to manually copy a connector from FigJam, paste it onto the current page, select it, and then you can run \`set_default_connector({ connectorId: "SELECTED_NODE_ID" })\` before attempting \`create_connections\`. **Do not proceed to Step 2 until a default connector is confirmed.**
415
-
416
- ### 2. Filter and Transform Reactions from \`get_reactions\` Output
417
- - **Iterate:** Go through the JSON array provided by \`get_reactions\`. For each node in the array:
418
- - Iterate through its \`reactions\` array.
419
- - **Filter:** Keep only reactions where the \`action\` meets these criteria:
420
- - Has a \`type\` that implies a connection (e.g., \`NAVIGATE\`, \`OPEN_OVERLAY\`, \`SWAP_OVERLAY\`). **Ignore** types like \`CHANGE_TO\`, \`CLOSE_OVERLAY\`, etc.
421
- - Has a valid \`destinationId\` property.
422
- - **Extract:** For each valid reaction, extract the following information:
423
- - \`sourceNodeId\`: The ID of the node the reaction belongs to (from the outer loop).
424
- - \`destinationNodeId\`: The value of \`action.destinationId\`.
425
- - \`actionType\`: The value of \`action.type\`.
426
- - \`triggerType\`: The value of \`trigger.type\`.
427
-
428
- ### 3. Generate Connector Text Labels
429
- - **For each extracted connection:** Create a concise, descriptive text label string.
430
- - **Combine Information:** Use the \`actionType\`, \`triggerType\`, and potentially the names of the source/destination nodes (obtained from Step 1's \`read_my_design\` or by calling \`get_node_info\` if necessary) to generate the label.
431
- - **Example Labels:**
432
- - If \`triggerType\` is "ON_CLICK" and \`actionType\` is "NAVIGATE": "On click, navigate to [Destination Node Name]"
433
- - If \`triggerType\` is "ON_DRAG" and \`actionType\` is "OPEN_OVERLAY": "On drag, open [Destination Node Name] overlay"
434
- - **Keep it brief and informative.** Let this generated string be \`generatedText\`.
435
-
436
- ### 4. Prepare the \`connections\` Array for \`create_connections\`
437
- - **Structure:** Create a JSON array where each element is an object representing a connection.
438
- - **Format:** Each object in the array must have the following structure:
439
- \`\`\`json
440
- {
441
- "startNodeId": "sourceNodeId_from_step_2",
442
- "endNodeId": "destinationNodeId_from_step_2",
443
- "text": "generatedText_from_step_3"
444
- }
445
- \`\`\`
446
- - **Result:** This final array is the value you will pass to the \`connections\` parameter when calling the \`create_connections\` tool.
447
-
448
- ### 5. Execute Connection Creation
449
- - **Action:** Call the \`create_connections\` tool, passing the array generated in Step 4 as the \`connections\` argument.
450
- - **Verify:** Check the response from \`create_connections\` to confirm success or failure.
451
-
452
- This detailed process ensures you correctly interpret the reaction data, prepare the necessary information, and use the appropriate tools to create the connector lines.`}}],description:"Strategy for converting Figma prototype reactions to connector lines using the output of 'get_reactions'"}}),$.tool("join_channel","Join a specific channel to communicate with Figma",{channel:J.string().describe("The name of the channel to join").default("")},async({channel:X})=>{try{if(!X)return{content:[{type:"text",text:"Please provide a channel name to join:"}],followUp:{tool:"join_channel",description:"Join the specified channel"}};return await v1(X),{content:[{type:"text",text:`Successfully joined channel: ${X}`}]}}catch(Q){return{content:[{type:"text",text:`Error joining channel: ${Q instanceof Error?Q.message:String(Q)}`}]}}}),$.tool("get_file_components","Get all components from a specific Figma file",{fileKey:J.string().describe("The Figma file identifier found in the file URL"),personalToken:J.string().optional().describe("Optional personal token, will use environment token if not provided")},async({fileKey:X,personalToken:Q})=>{try{let Y=Q;if(!Y){if(Y=process.env.personalToken,!Y)return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Personal token not found. Please provide personalToken parameter or set FIGMA_API_KEY environment variable."})}]}}let G=await fetch(`https://api.figma.com/v1/files/${X}/components`,{headers:{Authorization:`Bearer ${Y}`,"X-Figma-Token":Y}});if(!G.ok){let H=await G.text();return{content:[{type:"text",text:JSON.stringify({success:!1,error:`API request failed: ${G.status} ${G.statusText}`,details:H})}]}}let W=await G.json();return{content:[{type:"text",text:JSON.stringify({success:!0,fileKey:X,components:W})}]}}catch(Y){return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Error getting file components: ${Y instanceof Error?Y.message:String(Y)}`})}]}}}),$.tool("get_component","Get detailed information about a specific component by its key",{componentKey:J.string().describe("The unique key identifier of the component"),personalToken:J.string().optional().describe("Optional personal token, will use environment token if not provided")},async({componentKey:X,personalToken:Q})=>{try{let Y=Q;if(!Y){if(Y=process.env.personalToken,!Y)return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Personal token not found. Please provide personalToken parameter or set FIGMA_API_KEY environment variable."})}]}}let G=await fetch(`https://api.figma.com/v1/components/${X}`,{headers:{Authorization:`Bearer ${Y}`,"X-Figma-Token":Y}});if(!G.ok){let H=await G.text();return{content:[{type:"text",text:JSON.stringify({success:!1,error:`API request failed: ${G.status} ${G.statusText}`,details:H})}]}}let W=await G.json();return{content:[{type:"text",text:JSON.stringify({success:!0,componentKey:X,component:W})}]}}catch(Y){return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Error getting component: ${Y instanceof Error?Y.message:String(Y)}`})}]}}})}R1().catch(($)=>{o6.error(`Error starting FigmaMCP server: ${$ instanceof Error?$.message:String($)}`),process.exit(1)});var $0=new t3({name:K1,version:L1},{capabilities:{logging:{}}});k1($0);var Q0=y1(require("node:process"));u$();class X0{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
453
- `);if($===-1)return null;let X=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),a6(X)}clear(){this._buffer=void 0}}function a6($){return k0.parse(JSON.parse($))}function f1($){return JSON.stringify($)+`
454
- `}class Y0{constructor($=Q0.default.stdin,X=Q0.default.stdout){this._stdin=$,this._stdout=X,this._readBuffer=new X0,this._started=!1,this._ondata=(Q)=>{this._readBuffer.append(Q),this.processReadBuffer()},this._onerror=(Q)=>{var Y;(Y=this.onerror)===null||Y===void 0||Y.call(this,Q)}}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(){var $,X;while(!0)try{let Q=this._readBuffer.readMessage();if(Q===null)break;($=this.onmessage)===null||$===void 0||$.call(this,Q)}catch(Q){(X=this.onerror)===null||X===void 0||X.call(this,Q)}}async close(){var $;if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),($=this.onclose)===null||$===void 0||$.call(this)}send($){return new Promise((X)=>{let Q=f1($);if(this._stdout.write(Q))X();else this._stdout.once("drain",X)})}}p$();var r6=M$("StdioTransport");async function P1($){try{let X=new Y0;await $.connect(X)}catch(X){r6.info(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32000,message:`Server startup failed: ${X.message}`}})),process.exit(1)}}P1($0);
455
-
456
- //# debugId=3EA45C7EDFB5A7C564756E2164756E21
457
- //# sourceMappingURL=cli.js.map