@presidio-dev/specifai-mcp-server 0.3.0 → 0.4.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/index.js CHANGED
@@ -1,25 +1,34 @@
1
1
  #!/usr/bin/env node
2
- var K;(function($){$.assertEqual=(J)=>J;function X(J){}$.assertIs=X;function Q(J){throw new Error}$.assertNever=Q,$.arrayToEnum=(J)=>{let G={};for(let Y of J)G[Y]=Y;return G},$.getValidEnumValues=(J)=>{let G=$.objectKeys(J).filter((B)=>typeof J[J[B]]!=="number"),Y={};for(let B of G)Y[B]=J[B];return $.objectValues(Y)},$.objectValues=(J)=>{return $.objectKeys(J).map(function(G){return J[G]})},$.objectKeys=typeof Object.keys==="function"?(J)=>Object.keys(J):(J)=>{let G=[];for(let Y in J)if(Object.prototype.hasOwnProperty.call(J,Y))G.push(Y);return G},$.find=(J,G)=>{for(let Y of J)if(G(Y))return Y;return},$.isInteger=typeof Number.isInteger==="function"?(J)=>Number.isInteger(J):(J)=>typeof J==="number"&&isFinite(J)&&Math.floor(J)===J;function W(J,G=" | "){return J.map((Y)=>typeof Y==="string"?`'${Y}'`:Y).join(G)}$.joinValues=W,$.jsonStringifyReplacer=(J,G)=>{if(typeof G==="bigint")return G.toString();return G}})(K||(K={}));var o0;(function($){$.mergeShapes=(X,Q)=>{return{...X,...Q}}})(o0||(o0={}));var w=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Z=($)=>{switch(typeof $){case"undefined":return w.undefined;case"string":return w.string;case"number":return isNaN($)?w.nan:w.number;case"boolean":return w.boolean;case"function":return w.function;case"bigint":return w.bigint;case"symbol":return w.symbol;case"object":if(Array.isArray($))return w.array;if($===null)return w.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return w.promise;if(typeof Map!=="undefined"&&$ instanceof Map)return w.map;if(typeof Set!=="undefined"&&$ instanceof Set)return w.set;if(typeof Date!=="undefined"&&$ instanceof Date)return w.date;return w.object;default:return w.unknown}},q=K.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"]),u1=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class S 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(J){return J.message},Q={_errors:[]},W=(J)=>{for(let G of J.issues)if(G.code==="invalid_union")G.unionErrors.map(W);else if(G.code==="invalid_return_type")W(G.returnTypeError);else if(G.code==="invalid_arguments")W(G.argumentsError);else if(G.path.length===0)Q._errors.push(X(G));else{let Y=Q,B=0;while(B<G.path.length){let M=G.path[B];if(B!==G.path.length-1)Y[M]=Y[M]||{_errors:[]};else Y[M]=Y[M]||{_errors:[]},Y[M]._errors.push(X(G));Y=Y[M],B++}}};return W(this),Q}static assert($){if(!($ instanceof S))throw new Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(X)=>X.message){let X={},Q=[];for(let W of this.issues)if(W.path.length>0)X[W.path[0]]=X[W.path[0]]||[],X[W.path[0]].push($(W));else Q.push($(W));return{formErrors:Q,fieldErrors:X}}get formErrors(){return this.flatten()}}S.create=($)=>{return new S($)};var H0=($,X)=>{let Q;switch($.code){case q.invalid_type:if($.received===w.undefined)Q="Required";else Q=`Expected ${$.expected}, received ${$.received}`;break;case q.invalid_literal:Q=`Invalid literal value, expected ${JSON.stringify($.expected,K.jsonStringifyReplacer)}`;break;case q.unrecognized_keys:Q=`Unrecognized key(s) in object: ${K.joinValues($.keys,", ")}`;break;case q.invalid_union:Q="Invalid input";break;case q.invalid_union_discriminator:Q=`Invalid discriminator value. Expected ${K.joinValues($.options)}`;break;case q.invalid_enum_value:Q=`Invalid enum value. Expected ${K.joinValues($.options)}, received '${$.received}'`;break;case q.invalid_arguments:Q="Invalid function arguments";break;case q.invalid_return_type:Q="Invalid function return type";break;case q.invalid_date:Q="Invalid date";break;case q.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 K.assertNever($.validation);else if($.validation!=="regex")Q=`Invalid ${$.validation}`;else Q="Invalid";break;case q.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==="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 q.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 q.custom:Q="Invalid input";break;case q.invalid_intersection_types:Q="Intersection results could not be merged";break;case q.not_multiple_of:Q=`Number must be a multiple of ${$.multipleOf}`;break;case q.not_finite:Q="Number must be finite";break;default:Q=X.defaultError,K.assertNever($)}return{message:Q}},R1=H0;function p1($){R1=$}function I0(){return R1}var P0=($)=>{let{data:X,path:Q,errorMaps:W,issueData:J}=$,G=[...Q,...J.path||[]],Y={...J,path:G};if(J.message!==void 0)return{...J,path:G,message:J.message};let B="",M=W.filter((V)=>!!V).slice().reverse();for(let V of M)B=V(Y,{data:X,defaultError:B}).message;return{...J,path:G,message:B}},n1=[];function z($,X){let Q=I0(),W=P0({issueData:X,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,Q,Q===H0?void 0:H0].filter((J)=>!!J)});$.common.issues.push(W)}class j{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 W of X){if(W.status==="aborted")return R;if(W.status==="dirty")$.dirty();Q.push(W.value)}return{status:$.value,value:Q}}static async mergeObjectAsync($,X){let Q=[];for(let W of X){let J=await W.key,G=await W.value;Q.push({key:J,value:G})}return j.mergeObjectSync($,Q)}static mergeObjectSync($,X){let Q={};for(let W of X){let{key:J,value:G}=W;if(J.status==="aborted")return R;if(G.status==="aborted")return R;if(J.status==="dirty")$.dirty();if(G.status==="dirty")$.dirty();if(J.value!=="__proto__"&&(typeof G.value!=="undefined"||W.alwaysSet))Q[J.value]=G.value}return{status:$.value,value:Q}}}var R=Object.freeze({status:"aborted"}),W0=($)=>({status:"dirty",value:$}),E=($)=>({status:"valid",value:$}),a0=($)=>$.status==="aborted",s0=($)=>$.status==="dirty",o=($)=>$.status==="valid",K0=($)=>typeof Promise!=="undefined"&&$ instanceof Promise;function T0($,X,Q,W){if(Q==="a"&&!W)throw new TypeError("Private accessor was defined without a getter");if(typeof X==="function"?$!==X||!W:!X.has($))throw new TypeError("Cannot read private member from an object whose class did not declare it");return Q==="m"?W:Q==="a"?W.call($):W?W.value:X.get($)}function U1($,X,Q,W,J){if(W==="m")throw new TypeError("Private method is not writable");if(W==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof X==="function"?$!==X||!J:!X.has($))throw new TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?J.call($,Q):J?J.value=Q:X.set($,Q),Q}var A;(function($){$.errToObj=(X)=>typeof X==="string"?{message:X}:X||{},$.toString=(X)=>typeof X==="string"?X:X===null||X===void 0?void 0:X.message})(A||(A={}));var U0,D0;class P{constructor($,X,Q,W){this._cachedPath=[],this.parent=$,this.data=X,this._path=Q,this._key=W}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var A1=($,X)=>{if(o(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 S($.common.issues);return this._error=Q,this._error}}}};function U($){if(!$)return{};let{errorMap:X,invalid_type_error:Q,required_error:W,description:J}=$;if(X&&(Q||W))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(X)return{errorMap:X,description:J};return{errorMap:(Y,B)=>{var M,V;let{message:F}=$;if(Y.code==="invalid_enum_value")return{message:F!==null&&F!==void 0?F:B.defaultError};if(typeof B.data==="undefined")return{message:(M=F!==null&&F!==void 0?F:W)!==null&&M!==void 0?M:B.defaultError};if(Y.code!=="invalid_type")return{message:B.defaultError};return{message:(V=F!==null&&F!==void 0?F:Q)!==null&&V!==void 0?V:B.defaultError}},description:J}}class D{get description(){return this._def.description}_getType($){return Z($.data)}_getOrReturnCtx($,X){return X||{common:$.parent.common,data:$.data,parsedType:Z($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new j,ctx:{common:$.parent.common,data:$.data,parsedType:Z($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let X=this._parse($);if(K0(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){var Q;let W={common:{issues:[],async:(Q=X===null||X===void 0?void 0:X.async)!==null&&Q!==void 0?Q:!1,contextualErrorMap:X===null||X===void 0?void 0:X.errorMap},path:(X===null||X===void 0?void 0:X.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:Z($)},J=this._parseSync({data:$,path:W.path,parent:W});return A1(W,J)}"~validate"($){var X,Q;let W={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:Z($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:W});return o(J)?{value:J.value}:{issues:W.common.issues}}catch(J){if((Q=(X=J===null||J===void 0?void 0:J.message)===null||X===void 0?void 0:X.toLowerCase())===null||Q===void 0?void 0:Q.includes("encountered"))this["~standard"].async=!0;W.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:W}).then((J)=>o(J)?{value:J.value}:{issues:W.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===null||X===void 0?void 0:X.errorMap,async:!0},path:(X===null||X===void 0?void 0:X.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:Z($)},W=this._parse({data:$,path:Q.path,parent:Q}),J=await(K0(W)?W:Promise.resolve(W));return A1(Q,J)}refine($,X){let Q=(W)=>{if(typeof X==="string"||typeof X==="undefined")return{message:X};else if(typeof X==="function")return X(W);else return X};return this._refinement((W,J)=>{let G=$(W),Y=()=>J.addIssue({code:q.custom,...Q(W)});if(typeof Promise!=="undefined"&&G instanceof Promise)return G.then((B)=>{if(!B)return Y(),!1;else return!0});if(!G)return Y(),!1;else return!0})}refinement($,X){return this._refinement((Q,W)=>{if(!$(Q))return W.addIssue(typeof X==="function"?X(Q,W):X),!1;else return!0})}_refinement($){return new C({schema:this,typeName:L.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 I.create(this,this._def)}nullable(){return c.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return k.create(this)}promise(){return e.create(this,this._def)}or($){return q0.create([this,$],this._def)}and($){return M0.create(this,$,this._def)}transform($){return new C({...U(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:$}})}default($){let X=typeof $==="function"?$:()=>$;return new A0({...U(this._def),innerType:this,defaultValue:X,typeName:L.ZodDefault})}brand(){return new g0({typeName:L.ZodBranded,type:this,...U(this._def)})}catch($){let X=typeof $==="function"?$:()=>$;return new O0({...U(this._def),innerType:this,catchValue:X,typeName:L.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return S0.create(this,$)}readonly(){return L0.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var i1=/^c[^\s-]{8,}$/i,d1=/^[0-9a-z]+$/,r1=/^[0-9A-HJKMNP-TV-Z]{26}$/i,o1=/^[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,a1=/^[a-z0-9_-]{21}$/i,s1=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,t1=/^[-+]?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)?)??$/,e1=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",r0,X2=/^(?:(?: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])$/,Q2=/^(?:(?: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])$/,W2=/^(([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]))$/,J2=/^(([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])$/,H2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,G2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,D1="((\\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=new RegExp(`^${D1}$`);function K1($){let X="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if($.precision)X=`${X}\\.\\d{${$.precision}}`;else if($.precision==null)X=`${X}(\\.\\d+)?`;return X}function B2($){return new RegExp(`^${K1($)}$`)}function F1($){let X=`${D1}T${K1($)}`,Q=[];if(Q.push($.local?"Z?":"Z"),$.offset)Q.push("([+-]\\d{2}:?\\d{2})");return X=`${X}(${Q.join("|")})`,new RegExp(`^${X}$`)}function q2($,X){if((X==="v4"||!X)&&X2.test($))return!0;if((X==="v6"||!X)&&W2.test($))return!0;return!1}function M2($,X){if(!s1.test($))return!1;try{let[Q]=$.split("."),W=Q.replace(/-/g,"+").replace(/_/g,"/").padEnd(Q.length+(4-Q.length%4)%4,"="),J=JSON.parse(atob(W));if(typeof J!=="object"||J===null)return!1;if(!J.typ||!J.alg)return!1;if(X&&J.alg!==X)return!1;return!0}catch(Q){return!1}}function z2($,X){if((X==="v4"||!X)&&Q2.test($))return!0;if((X==="v6"||!X)&&J2.test($))return!0;return!1}class f extends D{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==w.string){let J=this._getOrReturnCtx($);return z(J,{code:q.invalid_type,expected:w.string,received:J.parsedType}),R}let Q=new j,W=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.length<J.value)W=this._getOrReturnCtx($,W),z(W,{code:q.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),Q.dirty()}else if(J.kind==="max"){if($.data.length>J.value)W=this._getOrReturnCtx($,W),z(W,{code:q.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),Q.dirty()}else if(J.kind==="length"){let G=$.data.length>J.value,Y=$.data.length<J.value;if(G||Y){if(W=this._getOrReturnCtx($,W),G)z(W,{code:q.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});else if(Y)z(W,{code:q.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});Q.dirty()}}else if(J.kind==="email"){if(!e1.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"email",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="emoji"){if(!r0)r0=new RegExp($2,"u");if(!r0.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"emoji",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="uuid"){if(!o1.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"uuid",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="nanoid"){if(!a1.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"nanoid",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="cuid"){if(!i1.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"cuid",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="cuid2"){if(!d1.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"cuid2",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="ulid"){if(!r1.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"ulid",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="url")try{new URL($.data)}catch(G){W=this._getOrReturnCtx($,W),z(W,{validation:"url",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="regex"){if(J.regex.lastIndex=0,!J.regex.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"regex",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="trim")$.data=$.data.trim();else if(J.kind==="includes"){if(!$.data.includes(J.value,J.position))W=this._getOrReturnCtx($,W),z(W,{code:q.invalid_string,validation:{includes:J.value,position:J.position},message:J.message}),Q.dirty()}else if(J.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(J.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(J.kind==="startsWith"){if(!$.data.startsWith(J.value))W=this._getOrReturnCtx($,W),z(W,{code:q.invalid_string,validation:{startsWith:J.value},message:J.message}),Q.dirty()}else if(J.kind==="endsWith"){if(!$.data.endsWith(J.value))W=this._getOrReturnCtx($,W),z(W,{code:q.invalid_string,validation:{endsWith:J.value},message:J.message}),Q.dirty()}else if(J.kind==="datetime"){if(!F1(J).test($.data))W=this._getOrReturnCtx($,W),z(W,{code:q.invalid_string,validation:"datetime",message:J.message}),Q.dirty()}else if(J.kind==="date"){if(!Y2.test($.data))W=this._getOrReturnCtx($,W),z(W,{code:q.invalid_string,validation:"date",message:J.message}),Q.dirty()}else if(J.kind==="time"){if(!B2(J).test($.data))W=this._getOrReturnCtx($,W),z(W,{code:q.invalid_string,validation:"time",message:J.message}),Q.dirty()}else if(J.kind==="duration"){if(!t1.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"duration",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="ip"){if(!q2($.data,J.version))W=this._getOrReturnCtx($,W),z(W,{validation:"ip",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="jwt"){if(!M2($.data,J.alg))W=this._getOrReturnCtx($,W),z(W,{validation:"jwt",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="cidr"){if(!z2($.data,J.version))W=this._getOrReturnCtx($,W),z(W,{validation:"cidr",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="base64"){if(!H2.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"base64",code:q.invalid_string,message:J.message}),Q.dirty()}else if(J.kind==="base64url"){if(!G2.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"base64url",code:q.invalid_string,message:J.message}),Q.dirty()}else K.assertNever(J);return{status:Q.value,value:$.data}}_regex($,X,Q){return this.refinement((W)=>$.test(W),{validation:X,code:q.invalid_string,...A.errToObj(Q)})}_addCheck($){return new f({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...A.errToObj($)})}url($){return this._addCheck({kind:"url",...A.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...A.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...A.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...A.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...A.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...A.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...A.errToObj($)})}base64($){return this._addCheck({kind:"base64",...A.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...A.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...A.errToObj($)})}ip($){return this._addCheck({kind:"ip",...A.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...A.errToObj($)})}datetime($){var X,Q;if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof($===null||$===void 0?void 0:$.precision)==="undefined"?null:$===null||$===void 0?void 0:$.precision,offset:(X=$===null||$===void 0?void 0:$.offset)!==null&&X!==void 0?X:!1,local:(Q=$===null||$===void 0?void 0:$.local)!==null&&Q!==void 0?Q:!1,...A.errToObj($===null||$===void 0?void 0:$.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($===null||$===void 0?void 0:$.precision)==="undefined"?null:$===null||$===void 0?void 0:$.precision,...A.errToObj($===null||$===void 0?void 0:$.message)})}duration($){return this._addCheck({kind:"duration",...A.errToObj($)})}regex($,X){return this._addCheck({kind:"regex",regex:$,...A.errToObj(X)})}includes($,X){return this._addCheck({kind:"includes",value:$,position:X===null||X===void 0?void 0:X.position,...A.errToObj(X===null||X===void 0?void 0:X.message)})}startsWith($,X){return this._addCheck({kind:"startsWith",value:$,...A.errToObj(X)})}endsWith($,X){return this._addCheck({kind:"endsWith",value:$,...A.errToObj(X)})}min($,X){return this._addCheck({kind:"min",value:$,...A.errToObj(X)})}max($,X){return this._addCheck({kind:"max",value:$,...A.errToObj(X)})}length($,X){return this._addCheck({kind:"length",value:$,...A.errToObj(X)})}nonempty($){return this.min(1,A.errToObj($))}trim(){return new f({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new f({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new f({...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 $}}f.create=($)=>{var X;return new f({checks:[],typeName:L.ZodString,coerce:(X=$===null||$===void 0?void 0:$.coerce)!==null&&X!==void 0?X:!1,...U($)})};function w2($,X){let Q=($.toString().split(".")[1]||"").length,W=(X.toString().split(".")[1]||"").length,J=Q>W?Q:W,G=parseInt($.toFixed(J).replace(".","")),Y=parseInt(X.toFixed(J).replace(".",""));return G%Y/Math.pow(10,J)}class n extends D{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($)!==w.number){let J=this._getOrReturnCtx($);return z(J,{code:q.invalid_type,expected:w.number,received:J.parsedType}),R}let Q=void 0,W=new j;for(let J of this._def.checks)if(J.kind==="int"){if(!K.isInteger($.data))Q=this._getOrReturnCtx($,Q),z(Q,{code:q.invalid_type,expected:"integer",received:"float",message:J.message}),W.dirty()}else if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)Q=this._getOrReturnCtx($,Q),z(Q,{code:q.too_small,minimum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),W.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)Q=this._getOrReturnCtx($,Q),z(Q,{code:q.too_big,maximum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),W.dirty()}else if(J.kind==="multipleOf"){if(w2($.data,J.value)!==0)Q=this._getOrReturnCtx($,Q),z(Q,{code:q.not_multiple_of,multipleOf:J.value,message:J.message}),W.dirty()}else if(J.kind==="finite"){if(!Number.isFinite($.data))Q=this._getOrReturnCtx($,Q),z(Q,{code:q.not_finite,message:J.message}),W.dirty()}else K.assertNever(J);return{status:W.value,value:$.data}}gte($,X){return this.setLimit("min",$,!0,A.toString(X))}gt($,X){return this.setLimit("min",$,!1,A.toString(X))}lte($,X){return this.setLimit("max",$,!0,A.toString(X))}lt($,X){return this.setLimit("max",$,!1,A.toString(X))}setLimit($,X,Q,W){return new n({...this._def,checks:[...this._def.checks,{kind:$,value:X,inclusive:Q,message:A.toString(W)}]})}_addCheck($){return new n({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:A.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString($)})}multipleOf($,X){return this._addCheck({kind:"multipleOf",value:$,message:A.toString(X)})}finite($){return this._addCheck({kind:"finite",message:A.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.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"&&K.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($)}}n.create=($)=>{return new n({checks:[],typeName:L.ZodNumber,coerce:($===null||$===void 0?void 0:$.coerce)||!1,...U($)})};class i extends D{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch(J){return this._getInvalidInput($)}if(this._getType($)!==w.bigint)return this._getInvalidInput($);let Q=void 0,W=new j;for(let J of this._def.checks)if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)Q=this._getOrReturnCtx($,Q),z(Q,{code:q.too_small,type:"bigint",minimum:J.value,inclusive:J.inclusive,message:J.message}),W.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)Q=this._getOrReturnCtx($,Q),z(Q,{code:q.too_big,type:"bigint",maximum:J.value,inclusive:J.inclusive,message:J.message}),W.dirty()}else if(J.kind==="multipleOf"){if($.data%J.value!==BigInt(0))Q=this._getOrReturnCtx($,Q),z(Q,{code:q.not_multiple_of,multipleOf:J.value,message:J.message}),W.dirty()}else K.assertNever(J);return{status:W.value,value:$.data}}_getInvalidInput($){let X=this._getOrReturnCtx($);return z(X,{code:q.invalid_type,expected:w.bigint,received:X.parsedType}),R}gte($,X){return this.setLimit("min",$,!0,A.toString(X))}gt($,X){return this.setLimit("min",$,!1,A.toString(X))}lte($,X){return this.setLimit("max",$,!0,A.toString(X))}lt($,X){return this.setLimit("max",$,!1,A.toString(X))}setLimit($,X,Q,W){return new i({...this._def,checks:[...this._def.checks,{kind:$,value:X,inclusive:Q,message:A.toString(W)}]})}_addCheck($){return new i({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString($)})}multipleOf($,X){return this._addCheck({kind:"multipleOf",value:$,message:A.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 $}}i.create=($)=>{var X;return new i({checks:[],typeName:L.ZodBigInt,coerce:(X=$===null||$===void 0?void 0:$.coerce)!==null&&X!==void 0?X:!1,...U($)})};class G0 extends D{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==w.boolean){let Q=this._getOrReturnCtx($);return z(Q,{code:q.invalid_type,expected:w.boolean,received:Q.parsedType}),R}return E($.data)}}G0.create=($)=>{return new G0({typeName:L.ZodBoolean,coerce:($===null||$===void 0?void 0:$.coerce)||!1,...U($)})};class a extends D{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==w.date){let J=this._getOrReturnCtx($);return z(J,{code:q.invalid_type,expected:w.date,received:J.parsedType}),R}if(isNaN($.data.getTime())){let J=this._getOrReturnCtx($);return z(J,{code:q.invalid_date}),R}let Q=new j,W=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.getTime()<J.value)W=this._getOrReturnCtx($,W),z(W,{code:q.too_small,message:J.message,inclusive:!0,exact:!1,minimum:J.value,type:"date"}),Q.dirty()}else if(J.kind==="max"){if($.data.getTime()>J.value)W=this._getOrReturnCtx($,W),z(W,{code:q.too_big,message:J.message,inclusive:!0,exact:!1,maximum:J.value,type:"date"}),Q.dirty()}else K.assertNever(J);return{status:Q.value,value:new Date($.data.getTime())}}_addCheck($){return new a({...this._def,checks:[...this._def.checks,$]})}min($,X){return this._addCheck({kind:"min",value:$.getTime(),message:A.toString(X)})}max($,X){return this._addCheck({kind:"max",value:$.getTime(),message:A.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}}a.create=($)=>{return new a({checks:[],coerce:($===null||$===void 0?void 0:$.coerce)||!1,typeName:L.ZodDate,...U($)})};class F0 extends D{_parse($){if(this._getType($)!==w.symbol){let Q=this._getOrReturnCtx($);return z(Q,{code:q.invalid_type,expected:w.symbol,received:Q.parsedType}),R}return E($.data)}}F0.create=($)=>{return new F0({typeName:L.ZodSymbol,...U($)})};class Y0 extends D{_parse($){if(this._getType($)!==w.undefined){let Q=this._getOrReturnCtx($);return z(Q,{code:q.invalid_type,expected:w.undefined,received:Q.parsedType}),R}return E($.data)}}Y0.create=($)=>{return new Y0({typeName:L.ZodUndefined,...U($)})};class B0 extends D{_parse($){if(this._getType($)!==w.null){let Q=this._getOrReturnCtx($);return z(Q,{code:q.invalid_type,expected:w.null,received:Q.parsedType}),R}return E($.data)}}B0.create=($)=>{return new B0({typeName:L.ZodNull,...U($)})};class s extends D{constructor(){super(...arguments);this._any=!0}_parse($){return E($.data)}}s.create=($)=>{return new s({typeName:L.ZodAny,...U($)})};class p extends D{constructor(){super(...arguments);this._unknown=!0}_parse($){return E($.data)}}p.create=($)=>{return new p({typeName:L.ZodUnknown,...U($)})};class g extends D{_parse($){let X=this._getOrReturnCtx($);return z(X,{code:q.invalid_type,expected:w.never,received:X.parsedType}),R}}g.create=($)=>{return new g({typeName:L.ZodNever,...U($)})};class N0 extends D{_parse($){if(this._getType($)!==w.undefined){let Q=this._getOrReturnCtx($);return z(Q,{code:q.invalid_type,expected:w.void,received:Q.parsedType}),R}return E($.data)}}N0.create=($)=>{return new N0({typeName:L.ZodVoid,...U($)})};class k extends D{_parse($){let{ctx:X,status:Q}=this._processInputParams($),W=this._def;if(X.parsedType!==w.array)return z(X,{code:q.invalid_type,expected:w.array,received:X.parsedType}),R;if(W.exactLength!==null){let G=X.data.length>W.exactLength.value,Y=X.data.length<W.exactLength.value;if(G||Y)z(X,{code:G?q.too_big:q.too_small,minimum:Y?W.exactLength.value:void 0,maximum:G?W.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:W.exactLength.message}),Q.dirty()}if(W.minLength!==null){if(X.data.length<W.minLength.value)z(X,{code:q.too_small,minimum:W.minLength.value,type:"array",inclusive:!0,exact:!1,message:W.minLength.message}),Q.dirty()}if(W.maxLength!==null){if(X.data.length>W.maxLength.value)z(X,{code:q.too_big,maximum:W.maxLength.value,type:"array",inclusive:!0,exact:!1,message:W.maxLength.message}),Q.dirty()}if(X.common.async)return Promise.all([...X.data].map((G,Y)=>{return W.type._parseAsync(new P(X,G,X.path,Y))})).then((G)=>{return j.mergeArray(Q,G)});let J=[...X.data].map((G,Y)=>{return W.type._parseSync(new P(X,G,X.path,Y))});return j.mergeArray(Q,J)}get element(){return this._def.type}min($,X){return new k({...this._def,minLength:{value:$,message:A.toString(X)}})}max($,X){return new k({...this._def,maxLength:{value:$,message:A.toString(X)}})}length($,X){return new k({...this._def,exactLength:{value:$,message:A.toString(X)}})}nonempty($){return this.min(1,$)}}k.create=($,X)=>{return new k({type:$,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...U(X)})};function Q0($){if($ instanceof N){let X={};for(let Q in $.shape){let W=$.shape[Q];X[Q]=I.create(Q0(W))}return new N({...$._def,shape:()=>X})}else if($ instanceof k)return new k({...$._def,type:Q0($.element)});else if($ instanceof I)return I.create(Q0($.unwrap()));else if($ instanceof c)return c.create(Q0($.unwrap()));else if($ instanceof x)return x.create($.items.map((X)=>Q0(X)));else return $}class N extends D{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=K.objectKeys($);return this._cached={shape:$,keys:X}}_parse($){if(this._getType($)!==w.object){let M=this._getOrReturnCtx($);return z(M,{code:q.invalid_type,expected:w.object,received:M.parsedType}),R}let{status:Q,ctx:W}=this._processInputParams($),{shape:J,keys:G}=this._getCached(),Y=[];if(!(this._def.catchall instanceof g&&this._def.unknownKeys==="strip")){for(let M in W.data)if(!G.includes(M))Y.push(M)}let B=[];for(let M of G){let V=J[M],F=W.data[M];B.push({key:{status:"valid",value:M},value:V._parse(new P(W,F,W.path,M)),alwaysSet:M in W.data})}if(this._def.catchall instanceof g){let M=this._def.unknownKeys;if(M==="passthrough")for(let V of Y)B.push({key:{status:"valid",value:V},value:{status:"valid",value:W.data[V]}});else if(M==="strict"){if(Y.length>0)z(W,{code:q.unrecognized_keys,keys:Y}),Q.dirty()}else if(M==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let M=this._def.catchall;for(let V of Y){let F=W.data[V];B.push({key:{status:"valid",value:V},value:M._parse(new P(W,F,W.path,V)),alwaysSet:V in W.data})}}if(W.common.async)return Promise.resolve().then(async()=>{let M=[];for(let V of B){let F=await V.key,_=await V.value;M.push({key:F,value:_,alwaysSet:V.alwaysSet})}return M}).then((M)=>{return j.mergeObjectSync(Q,M)});else return j.mergeObjectSync(Q,B)}get shape(){return this._def.shape()}strict($){return A.errToObj,new N({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(X,Q)=>{var W,J,G,Y;let B=(G=(J=(W=this._def).errorMap)===null||J===void 0?void 0:J.call(W,X,Q).message)!==null&&G!==void 0?G:Q.defaultError;if(X.code==="unrecognized_keys")return{message:(Y=A.errToObj($).message)!==null&&Y!==void 0?Y:B};return{message:B}}}:{}})}strip(){return new N({...this._def,unknownKeys:"strip"})}passthrough(){return new N({...this._def,unknownKeys:"passthrough"})}extend($){return new N({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new N({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:L.ZodObject})}setKey($,X){return this.augment({[$]:X})}catchall($){return new N({...this._def,catchall:$})}pick($){let X={};return K.objectKeys($).forEach((Q)=>{if($[Q]&&this.shape[Q])X[Q]=this.shape[Q]}),new N({...this._def,shape:()=>X})}omit($){let X={};return K.objectKeys(this.shape).forEach((Q)=>{if(!$[Q])X[Q]=this.shape[Q]}),new N({...this._def,shape:()=>X})}deepPartial(){return Q0(this)}partial($){let X={};return K.objectKeys(this.shape).forEach((Q)=>{let W=this.shape[Q];if($&&!$[Q])X[Q]=W;else X[Q]=W.optional()}),new N({...this._def,shape:()=>X})}required($){let X={};return K.objectKeys(this.shape).forEach((Q)=>{if($&&!$[Q])X[Q]=this.shape[Q];else{let J=this.shape[Q];while(J instanceof I)J=J._def.innerType;X[Q]=J}}),new N({...this._def,shape:()=>X})}keyof(){return N1(K.objectKeys(this.shape))}}N.create=($,X)=>{return new N({shape:()=>$,unknownKeys:"strip",catchall:g.create(),typeName:L.ZodObject,...U(X)})};N.strictCreate=($,X)=>{return new N({shape:()=>$,unknownKeys:"strict",catchall:g.create(),typeName:L.ZodObject,...U(X)})};N.lazycreate=($,X)=>{return new N({shape:$,unknownKeys:"strip",catchall:g.create(),typeName:L.ZodObject,...U(X)})};class q0 extends D{_parse($){let{ctx:X}=this._processInputParams($),Q=this._def.options;function W(J){for(let Y of J)if(Y.result.status==="valid")return Y.result;for(let Y of J)if(Y.result.status==="dirty")return X.common.issues.push(...Y.ctx.common.issues),Y.result;let G=J.map((Y)=>new S(Y.ctx.common.issues));return z(X,{code:q.invalid_union,unionErrors:G}),R}if(X.common.async)return Promise.all(Q.map(async(J)=>{let G={...X,common:{...X.common,issues:[]},parent:null};return{result:await J._parseAsync({data:X.data,path:X.path,parent:G}),ctx:G}})).then(W);else{let J=void 0,G=[];for(let B of Q){let M={...X,common:{...X.common,issues:[]},parent:null},V=B._parseSync({data:X.data,path:X.path,parent:M});if(V.status==="valid")return V;else if(V.status==="dirty"&&!J)J={result:V,ctx:M};if(M.common.issues.length)G.push(M.common.issues)}if(J)return X.common.issues.push(...J.ctx.common.issues),J.result;let Y=G.map((B)=>new S(B));return z(X,{code:q.invalid_union,unionErrors:Y}),R}}get options(){return this._def.options}}q0.create=($,X)=>{return new q0({options:$,typeName:L.ZodUnion,...U(X)})};var l=($)=>{if($ instanceof z0)return l($.schema);else if($ instanceof C)return l($.innerType());else if($ instanceof w0)return[$.value];else if($ instanceof d)return $.options;else if($ instanceof V0)return K.objectValues($.enum);else if($ instanceof A0)return l($._def.innerType);else if($ instanceof Y0)return[void 0];else if($ instanceof B0)return[null];else if($ instanceof I)return[void 0,...l($.unwrap())];else if($ instanceof c)return[null,...l($.unwrap())];else if($ instanceof g0)return l($.unwrap());else if($ instanceof L0)return l($.unwrap());else if($ instanceof O0)return l($._def.innerType);else return[]};class h0 extends D{_parse($){let{ctx:X}=this._processInputParams($);if(X.parsedType!==w.object)return z(X,{code:q.invalid_type,expected:w.object,received:X.parsedType}),R;let Q=this.discriminator,W=X.data[Q],J=this.optionsMap.get(W);if(!J)return z(X,{code:q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Q]}),R;if(X.common.async)return J._parseAsync({data:X.data,path:X.path,parent:X});else return J._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 W=new Map;for(let J of X){let G=l(J.shape[$]);if(!G.length)throw new Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let Y of G){if(W.has(Y))throw new Error(`Discriminator property ${String($)} has duplicate value ${String(Y)}`);W.set(Y,J)}}return new h0({typeName:L.ZodDiscriminatedUnion,discriminator:$,options:X,optionsMap:W,...U(Q)})}}function t0($,X){let Q=Z($),W=Z(X);if($===X)return{valid:!0,data:$};else if(Q===w.object&&W===w.object){let J=K.objectKeys(X),G=K.objectKeys($).filter((B)=>J.indexOf(B)!==-1),Y={...$,...X};for(let B of G){let M=t0($[B],X[B]);if(!M.valid)return{valid:!1};Y[B]=M.data}return{valid:!0,data:Y}}else if(Q===w.array&&W===w.array){if($.length!==X.length)return{valid:!1};let J=[];for(let G=0;G<$.length;G++){let Y=$[G],B=X[G],M=t0(Y,B);if(!M.valid)return{valid:!1};J.push(M.data)}return{valid:!0,data:J}}else if(Q===w.date&&W===w.date&&+$===+X)return{valid:!0,data:$};else return{valid:!1}}class M0 extends D{_parse($){let{status:X,ctx:Q}=this._processInputParams($),W=(J,G)=>{if(a0(J)||a0(G))return R;let Y=t0(J.value,G.value);if(!Y.valid)return z(Q,{code:q.invalid_intersection_types}),R;if(s0(J)||s0(G))X.dirty();return{status:X.value,value:Y.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(([J,G])=>W(J,G));else return W(this._def.left._parseSync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseSync({data:Q.data,path:Q.path,parent:Q}))}}M0.create=($,X,Q)=>{return new M0({left:$,right:X,typeName:L.ZodIntersection,...U(Q)})};class x extends D{_parse($){let{status:X,ctx:Q}=this._processInputParams($);if(Q.parsedType!==w.array)return z(Q,{code:q.invalid_type,expected:w.array,received:Q.parsedType}),R;if(Q.data.length<this._def.items.length)return z(Q,{code:q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;if(!this._def.rest&&Q.data.length>this._def.items.length)z(Q,{code:q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X.dirty();let J=[...Q.data].map((G,Y)=>{let B=this._def.items[Y]||this._def.rest;if(!B)return null;return B._parse(new P(Q,G,Q.path,Y))}).filter((G)=>!!G);if(Q.common.async)return Promise.all(J).then((G)=>{return j.mergeArray(X,G)});else return j.mergeArray(X,J)}get items(){return this._def.items}rest($){return new x({...this._def,rest:$})}}x.create=($,X)=>{if(!Array.isArray($))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new x({items:$,typeName:L.ZodTuple,rest:null,...U(X)})};class j0 extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:X,ctx:Q}=this._processInputParams($);if(Q.parsedType!==w.object)return z(Q,{code:q.invalid_type,expected:w.object,received:Q.parsedType}),R;let W=[],J=this._def.keyType,G=this._def.valueType;for(let Y in Q.data)W.push({key:J._parse(new P(Q,Y,Q.path,Y)),value:G._parse(new P(Q,Q.data[Y],Q.path,Y)),alwaysSet:Y in Q.data});if(Q.common.async)return j.mergeObjectAsync(X,W);else return j.mergeObjectSync(X,W)}get element(){return this._def.valueType}static create($,X,Q){if(X instanceof D)return new j0({keyType:$,valueType:X,typeName:L.ZodRecord,...U(Q)});return new j0({keyType:f.create(),valueType:$,typeName:L.ZodRecord,...U(X)})}}class E0 extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:X,ctx:Q}=this._processInputParams($);if(Q.parsedType!==w.map)return z(Q,{code:q.invalid_type,expected:w.map,received:Q.parsedType}),R;let W=this._def.keyType,J=this._def.valueType,G=[...Q.data.entries()].map(([Y,B],M)=>{return{key:W._parse(new P(Q,Y,Q.path,[M,"key"])),value:J._parse(new P(Q,B,Q.path,[M,"value"]))}});if(Q.common.async){let Y=new Map;return Promise.resolve().then(async()=>{for(let B of G){let M=await B.key,V=await B.value;if(M.status==="aborted"||V.status==="aborted")return R;if(M.status==="dirty"||V.status==="dirty")X.dirty();Y.set(M.value,V.value)}return{status:X.value,value:Y}})}else{let Y=new Map;for(let B of G){let{key:M,value:V}=B;if(M.status==="aborted"||V.status==="aborted")return R;if(M.status==="dirty"||V.status==="dirty")X.dirty();Y.set(M.value,V.value)}return{status:X.value,value:Y}}}}E0.create=($,X,Q)=>{return new E0({valueType:X,keyType:$,typeName:L.ZodMap,...U(Q)})};class t extends D{_parse($){let{status:X,ctx:Q}=this._processInputParams($);if(Q.parsedType!==w.set)return z(Q,{code:q.invalid_type,expected:w.set,received:Q.parsedType}),R;let W=this._def;if(W.minSize!==null){if(Q.data.size<W.minSize.value)z(Q,{code:q.too_small,minimum:W.minSize.value,type:"set",inclusive:!0,exact:!1,message:W.minSize.message}),X.dirty()}if(W.maxSize!==null){if(Q.data.size>W.maxSize.value)z(Q,{code:q.too_big,maximum:W.maxSize.value,type:"set",inclusive:!0,exact:!1,message:W.maxSize.message}),X.dirty()}let J=this._def.valueType;function G(B){let M=new Set;for(let V of B){if(V.status==="aborted")return R;if(V.status==="dirty")X.dirty();M.add(V.value)}return{status:X.value,value:M}}let Y=[...Q.data.values()].map((B,M)=>J._parse(new P(Q,B,Q.path,M)));if(Q.common.async)return Promise.all(Y).then((B)=>G(B));else return G(Y)}min($,X){return new t({...this._def,minSize:{value:$,message:A.toString(X)}})}max($,X){return new t({...this._def,maxSize:{value:$,message:A.toString(X)}})}size($,X){return this.min($,X).max($,X)}nonempty($){return this.min(1,$)}}t.create=($,X)=>{return new t({valueType:$,minSize:null,maxSize:null,typeName:L.ZodSet,...U(X)})};class J0 extends D{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:X}=this._processInputParams($);if(X.parsedType!==w.function)return z(X,{code:q.invalid_type,expected:w.function,received:X.parsedType}),R;function Q(Y,B){return P0({data:Y,path:X.path,errorMaps:[X.common.contextualErrorMap,X.schemaErrorMap,I0(),H0].filter((M)=>!!M),issueData:{code:q.invalid_arguments,argumentsError:B}})}function W(Y,B){return P0({data:Y,path:X.path,errorMaps:[X.common.contextualErrorMap,X.schemaErrorMap,I0(),H0].filter((M)=>!!M),issueData:{code:q.invalid_return_type,returnTypeError:B}})}let J={errorMap:X.common.contextualErrorMap},G=X.data;if(this._def.returns instanceof e){let Y=this;return E(async function(...B){let M=new S([]),V=await Y._def.args.parseAsync(B,J).catch((u)=>{throw M.addIssue(Q(B,u)),M}),F=await Reflect.apply(G,this,V);return await Y._def.returns._def.type.parseAsync(F,J).catch((u)=>{throw M.addIssue(W(F,u)),M})})}else{let Y=this;return E(function(...B){let M=Y._def.args.safeParse(B,J);if(!M.success)throw new S([Q(B,M.error)]);let V=Reflect.apply(G,this,M.data),F=Y._def.returns.safeParse(V,J);if(!F.success)throw new S([W(V,F.error)]);return F.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new J0({...this._def,args:x.create($).rest(p.create())})}returns($){return new J0({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,X,Q){return new J0({args:$?$:x.create([]).rest(p.create()),returns:X||p.create(),typeName:L.ZodFunction,...U(Q)})}}class z0 extends D{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})}}z0.create=($,X)=>{return new z0({getter:$,typeName:L.ZodLazy,...U(X)})};class w0 extends D{_parse($){if($.data!==this._def.value){let X=this._getOrReturnCtx($);return z(X,{received:X.data,code:q.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:$.data}}get value(){return this._def.value}}w0.create=($,X)=>{return new w0({value:$,typeName:L.ZodLiteral,...U(X)})};function N1($,X){return new d({values:$,typeName:L.ZodEnum,...U(X)})}class d extends D{constructor(){super(...arguments);U0.set(this,void 0)}_parse($){if(typeof $.data!=="string"){let X=this._getOrReturnCtx($),Q=this._def.values;return z(X,{expected:K.joinValues(Q),received:X.parsedType,code:q.invalid_type}),R}if(!T0(this,U0,"f"))U1(this,U0,new Set(this._def.values),"f");if(!T0(this,U0,"f").has($.data)){let X=this._getOrReturnCtx($),Q=this._def.values;return z(X,{received:X.data,code:q.invalid_enum_value,options:Q}),R}return E($.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 d.create($,{...this._def,...X})}exclude($,X=this._def){return d.create(this.options.filter((Q)=>!$.includes(Q)),{...this._def,...X})}}U0=new WeakMap;d.create=N1;class V0 extends D{constructor(){super(...arguments);D0.set(this,void 0)}_parse($){let X=K.getValidEnumValues(this._def.values),Q=this._getOrReturnCtx($);if(Q.parsedType!==w.string&&Q.parsedType!==w.number){let W=K.objectValues(X);return z(Q,{expected:K.joinValues(W),received:Q.parsedType,code:q.invalid_type}),R}if(!T0(this,D0,"f"))U1(this,D0,new Set(K.getValidEnumValues(this._def.values)),"f");if(!T0(this,D0,"f").has($.data)){let W=K.objectValues(X);return z(Q,{received:Q.data,code:q.invalid_enum_value,options:W}),R}return E($.data)}get enum(){return this._def.values}}D0=new WeakMap;V0.create=($,X)=>{return new V0({values:$,typeName:L.ZodNativeEnum,...U(X)})};class e extends D{unwrap(){return this._def.type}_parse($){let{ctx:X}=this._processInputParams($);if(X.parsedType!==w.promise&&X.common.async===!1)return z(X,{code:q.invalid_type,expected:w.promise,received:X.parsedType}),R;let Q=X.parsedType===w.promise?X.data:Promise.resolve(X.data);return E(Q.then((W)=>{return this._def.type.parseAsync(W,{path:X.path,errorMap:X.common.contextualErrorMap})}))}}e.create=($,X)=>{return new e({type:$,typeName:L.ZodPromise,...U(X)})};class C extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:X,ctx:Q}=this._processInputParams($),W=this._def.effect||null,J={addIssue:(G)=>{if(z(Q,G),G.fatal)X.abort();else X.dirty()},get path(){return Q.path}};if(J.addIssue=J.addIssue.bind(J),W.type==="preprocess"){let G=W.transform(Q.data,J);if(Q.common.async)return Promise.resolve(G).then(async(Y)=>{if(X.value==="aborted")return R;let B=await this._def.schema._parseAsync({data:Y,path:Q.path,parent:Q});if(B.status==="aborted")return R;if(B.status==="dirty")return W0(B.value);if(X.value==="dirty")return W0(B.value);return B});else{if(X.value==="aborted")return R;let Y=this._def.schema._parseSync({data:G,path:Q.path,parent:Q});if(Y.status==="aborted")return R;if(Y.status==="dirty")return W0(Y.value);if(X.value==="dirty")return W0(Y.value);return Y}}if(W.type==="refinement"){let G=(Y)=>{let B=W.refinement(Y,J);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 Y};if(Q.common.async===!1){let Y=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(Y.status==="aborted")return R;if(Y.status==="dirty")X.dirty();return G(Y.value),{status:X.value,value:Y.value}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((Y)=>{if(Y.status==="aborted")return R;if(Y.status==="dirty")X.dirty();return G(Y.value).then(()=>{return{status:X.value,value:Y.value}})})}if(W.type==="transform")if(Q.common.async===!1){let G=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(!o(G))return G;let Y=W.transform(G.value,J);if(Y instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:X.value,value:Y}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((G)=>{if(!o(G))return G;return Promise.resolve(W.transform(G.value,J)).then((Y)=>({status:X.value,value:Y}))});K.assertNever(W)}}C.create=($,X,Q)=>{return new C({schema:$,typeName:L.ZodEffects,effect:X,...U(Q)})};C.createWithPreprocess=($,X,Q)=>{return new C({schema:X,effect:{type:"preprocess",transform:$},typeName:L.ZodEffects,...U(Q)})};class I extends D{_parse($){if(this._getType($)===w.undefined)return E(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}I.create=($,X)=>{return new I({innerType:$,typeName:L.ZodOptional,...U(X)})};class c extends D{_parse($){if(this._getType($)===w.null)return E(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}c.create=($,X)=>{return new c({innerType:$,typeName:L.ZodNullable,...U(X)})};class A0 extends D{_parse($){let{ctx:X}=this._processInputParams($),Q=X.data;if(X.parsedType===w.undefined)Q=this._def.defaultValue();return this._def.innerType._parse({data:Q,path:X.path,parent:X})}removeDefault(){return this._def.innerType}}A0.create=($,X)=>{return new A0({innerType:$,typeName:L.ZodDefault,defaultValue:typeof X.default==="function"?X.default:()=>X.default,...U(X)})};class O0 extends D{_parse($){let{ctx:X}=this._processInputParams($),Q={...X,common:{...X.common,issues:[]}},W=this._def.innerType._parse({data:Q.data,path:Q.path,parent:{...Q}});if(K0(W))return W.then((J)=>{return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new S(Q.common.issues)},input:Q.data})}});else return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new S(Q.common.issues)},input:Q.data})}}removeCatch(){return this._def.innerType}}O0.create=($,X)=>{return new O0({innerType:$,typeName:L.ZodCatch,catchValue:typeof X.catch==="function"?X.catch:()=>X.catch,...U(X)})};class _0 extends D{_parse($){if(this._getType($)!==w.nan){let Q=this._getOrReturnCtx($);return z(Q,{code:q.invalid_type,expected:w.nan,received:Q.parsedType}),R}return{status:"valid",value:$.data}}}_0.create=($)=>{return new _0({typeName:L.ZodNaN,...U($)})};var V2=Symbol("zod_brand");class g0 extends D{_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}}class S0 extends D{_parse($){let{status:X,ctx:Q}=this._processInputParams($);if(Q.common.async)return(async()=>{let J=await this._def.in._parseAsync({data:Q.data,path:Q.path,parent:Q});if(J.status==="aborted")return R;if(J.status==="dirty")return X.dirty(),W0(J.value);else return this._def.out._parseAsync({data:J.value,path:Q.path,parent:Q})})();else{let W=this._def.in._parseSync({data:Q.data,path:Q.path,parent:Q});if(W.status==="aborted")return R;if(W.status==="dirty")return X.dirty(),{status:"dirty",value:W.value};else return this._def.out._parseSync({data:W.value,path:Q.path,parent:Q})}}static create($,X){return new S0({in:$,out:X,typeName:L.ZodPipeline})}}class L0 extends D{_parse($){let X=this._def.innerType._parse($),Q=(W)=>{if(o(W))W.value=Object.freeze(W.value);return W};return K0(X)?X.then((W)=>Q(W)):Q(X)}unwrap(){return this._def.innerType}}L0.create=($,X)=>{return new L0({innerType:$,typeName:L.ZodReadonly,...U(X)})};function O1($,X){let Q=typeof $==="function"?$(X):typeof $==="string"?{message:$}:$;return typeof Q==="string"?{message:Q}:Q}function j1($,X={},Q){if($)return s.create().superRefine((W,J)=>{var G,Y;let B=$(W);if(B instanceof Promise)return B.then((M)=>{var V,F;if(!M){let _=O1(X,W),u=(F=(V=_.fatal)!==null&&V!==void 0?V:Q)!==null&&F!==void 0?F:!0;J.addIssue({code:"custom",..._,fatal:u})}});if(!B){let M=O1(X,W),V=(Y=(G=M.fatal)!==null&&G!==void 0?G:Q)!==null&&Y!==void 0?Y:!0;J.addIssue({code:"custom",...M,fatal:V})}return});return s.create()}var A2={object:N.lazycreate},L;(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"})(L||(L={}));var O2=($,X={message:`Input not instance of ${$.name}`})=>j1((Q)=>Q instanceof $,X),E1=f.create,_1=n.create,L2=_0.create,R2=i.create,S1=G0.create,U2=a.create,D2=F0.create,K2=Y0.create,F2=B0.create,N2=s.create,j2=p.create,E2=g.create,_2=N0.create,S2=k.create,$0=N.create,v2=N.strictCreate,b2=q0.create,C2=h0.create,f2=M0.create,k2=x.create,I2=j0.create,P2=E0.create,T2=t.create,h2=J0.create,g2=z0.create,x2=w0.create,y2=d.create,m2=V0.create,l2=e.create,L1=C.create,Z2=I.create,c2=c.create,u2=C.createWithPreprocess,p2=S0.create,n2=()=>E1().optional(),i2=()=>_1().optional(),d2=()=>S1().optional(),r2={string:($)=>f.create({...$,coerce:!0}),number:($)=>n.create({...$,coerce:!0}),boolean:($)=>G0.create({...$,coerce:!0}),bigint:($)=>i.create({...$,coerce:!0}),date:($)=>a.create({...$,coerce:!0})},o2=R,H=Object.freeze({__proto__:null,defaultErrorMap:H0,setErrorMap:p1,getErrorMap:I0,makeIssue:P0,EMPTY_PATH:n1,addIssueToContext:z,ParseStatus:j,INVALID:R,DIRTY:W0,OK:E,isAborted:a0,isDirty:s0,isValid:o,isAsync:K0,get util(){return K},get objectUtil(){return o0},ZodParsedType:w,getParsedType:Z,ZodType:D,datetimeRegex:F1,ZodString:f,ZodNumber:n,ZodBigInt:i,ZodBoolean:G0,ZodDate:a,ZodSymbol:F0,ZodUndefined:Y0,ZodNull:B0,ZodAny:s,ZodUnknown:p,ZodNever:g,ZodVoid:N0,ZodArray:k,ZodObject:N,ZodUnion:q0,ZodDiscriminatedUnion:h0,ZodIntersection:M0,ZodTuple:x,ZodRecord:j0,ZodMap:E0,ZodSet:t,ZodFunction:J0,ZodLazy:z0,ZodLiteral:w0,ZodEnum:d,ZodNativeEnum:V0,ZodPromise:e,ZodEffects:C,ZodTransformer:C,ZodOptional:I,ZodNullable:c,ZodDefault:A0,ZodCatch:O0,ZodNaN:_0,BRAND:V2,ZodBranded:g0,ZodPipeline:S0,ZodReadonly:L0,custom:j1,Schema:D,ZodSchema:D,late:A2,get ZodFirstPartyTypeKind(){return L},coerce:r2,any:N2,array:S2,bigint:R2,boolean:S1,date:U2,discriminatedUnion:C2,effect:L1,enum:y2,function:h2,instanceof:O2,intersection:f2,lazy:g2,literal:x2,map:P2,nan:L2,nativeEnum:m2,never:E2,null:F2,nullable:c2,number:_1,object:$0,oboolean:d2,onumber:i2,optional:Z2,ostring:n2,pipeline:p2,preprocess:u2,promise:l2,record:I2,set:T2,strictObject:v2,string:E1,symbol:D2,transformer:L1,tuple:k2,undefined:K2,union:b2,unknown:j2,void:_2,NEVER:o2,ZodIssueCode:q,quotelessJson:u1,ZodError:S});var e0="2024-11-05",v1=[e0,"2024-10-07"],x0="2.0",b1=H.union([H.string(),H.number().int()]),C1=H.string(),T=H.object({_meta:H.optional(H.object({progressToken:H.optional(b1)}).passthrough())}).passthrough(),v=H.object({method:H.string(),params:H.optional(T)}),v0=H.object({_meta:H.optional(H.object({}).passthrough())}).passthrough(),y=H.object({method:H.string(),params:H.optional(v0)}),h=H.object({_meta:H.optional(H.object({}).passthrough())}).passthrough(),y0=H.union([H.string(),H.number().int()]),a2=H.object({jsonrpc:H.literal(x0),id:y0}).merge(v).strict(),s2=H.object({jsonrpc:H.literal(x0)}).merge(y).strict(),t2=H.object({jsonrpc:H.literal(x0),id:y0,result:h}).strict(),X0;(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError"})(X0||(X0={}));var e2=H.object({jsonrpc:H.literal(x0),id:y0,error:H.object({code:H.number().int(),message:H.string(),data:H.optional(H.unknown())})}).strict(),f1=H.union([a2,s2,t2,e2]),m0=h.strict(),l0=y.extend({method:H.literal("notifications/cancelled"),params:v0.extend({requestId:y0,reason:H.string().optional()})}),k1=H.object({name:H.string(),version:H.string()}).passthrough(),$9=H.object({experimental:H.optional(H.object({}).passthrough()),sampling:H.optional(H.object({}).passthrough()),roots:H.optional(H.object({listChanged:H.optional(H.boolean())}).passthrough())}).passthrough(),$1=v.extend({method:H.literal("initialize"),params:T.extend({protocolVersion:H.string(),capabilities:$9,clientInfo:k1})}),X9=H.object({experimental:H.optional(H.object({}).passthrough()),logging:H.optional(H.object({}).passthrough()),prompts:H.optional(H.object({listChanged:H.optional(H.boolean())}).passthrough()),resources:H.optional(H.object({subscribe:H.optional(H.boolean()),listChanged:H.optional(H.boolean())}).passthrough()),tools:H.optional(H.object({listChanged:H.optional(H.boolean())}).passthrough())}).passthrough(),Q9=h.extend({protocolVersion:H.string(),capabilities:X9,serverInfo:k1,instructions:H.optional(H.string())}),X1=y.extend({method:H.literal("notifications/initialized")}),Z0=v.extend({method:H.literal("ping")}),W9=H.object({progress:H.number(),total:H.optional(H.number())}).passthrough(),c0=y.extend({method:H.literal("notifications/progress"),params:v0.merge(W9).extend({progressToken:b1})}),u0=v.extend({params:T.extend({cursor:H.optional(C1)}).optional()}),p0=h.extend({nextCursor:H.optional(C1)}),I1=H.object({uri:H.string(),mimeType:H.optional(H.string())}).passthrough(),P1=I1.extend({text:H.string()}),T1=I1.extend({blob:H.string().base64()}),J9=H.object({uri:H.string(),name:H.string(),description:H.optional(H.string()),mimeType:H.optional(H.string())}).passthrough(),H9=H.object({uriTemplate:H.string(),name:H.string(),description:H.optional(H.string()),mimeType:H.optional(H.string())}).passthrough(),G9=u0.extend({method:H.literal("resources/list")}),Y9=p0.extend({resources:H.array(J9)}),B9=u0.extend({method:H.literal("resources/templates/list")}),q9=p0.extend({resourceTemplates:H.array(H9)}),M9=v.extend({method:H.literal("resources/read"),params:T.extend({uri:H.string()})}),z9=h.extend({contents:H.array(H.union([P1,T1]))}),w9=y.extend({method:H.literal("notifications/resources/list_changed")}),V9=v.extend({method:H.literal("resources/subscribe"),params:T.extend({uri:H.string()})}),A9=v.extend({method:H.literal("resources/unsubscribe"),params:T.extend({uri:H.string()})}),O9=y.extend({method:H.literal("notifications/resources/updated"),params:v0.extend({uri:H.string()})}),L9=H.object({name:H.string(),description:H.optional(H.string()),required:H.optional(H.boolean())}).passthrough(),R9=H.object({name:H.string(),description:H.optional(H.string()),arguments:H.optional(H.array(L9))}).passthrough(),U9=u0.extend({method:H.literal("prompts/list")}),D9=p0.extend({prompts:H.array(R9)}),K9=v.extend({method:H.literal("prompts/get"),params:T.extend({name:H.string(),arguments:H.optional(H.record(H.string()))})}),n0=H.object({type:H.literal("text"),text:H.string()}).passthrough(),i0=H.object({type:H.literal("image"),data:H.string().base64(),mimeType:H.string()}).passthrough(),h1=H.object({type:H.literal("resource"),resource:H.union([P1,T1])}).passthrough(),F9=H.object({role:H.enum(["user","assistant"]),content:H.union([n0,i0,h1])}).passthrough(),N9=h.extend({description:H.optional(H.string()),messages:H.array(F9)}),j9=y.extend({method:H.literal("notifications/prompts/list_changed")}),E9=H.object({name:H.string(),description:H.optional(H.string()),inputSchema:H.object({type:H.literal("object"),properties:H.optional(H.object({}).passthrough())}).passthrough()}).passthrough(),Q1=u0.extend({method:H.literal("tools/list")}),_9=p0.extend({tools:H.array(E9)}),g1=h.extend({content:H.array(H.union([n0,i0,h1])),isError:H.boolean().default(!1).optional()}),J$=g1.or(h.extend({toolResult:H.unknown()})),W1=v.extend({method:H.literal("tools/call"),params:T.extend({name:H.string(),arguments:H.optional(H.record(H.unknown()))})}),S9=y.extend({method:H.literal("notifications/tools/list_changed")}),x1=H.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),v9=v.extend({method:H.literal("logging/setLevel"),params:T.extend({level:x1})}),b9=y.extend({method:H.literal("notifications/message"),params:v0.extend({level:x1,logger:H.optional(H.string()),data:H.unknown()})}),C9=H.object({name:H.string().optional()}).passthrough(),f9=H.object({hints:H.optional(H.array(C9)),costPriority:H.optional(H.number().min(0).max(1)),speedPriority:H.optional(H.number().min(0).max(1)),intelligencePriority:H.optional(H.number().min(0).max(1))}).passthrough(),k9=H.object({role:H.enum(["user","assistant"]),content:H.union([n0,i0])}).passthrough(),I9=v.extend({method:H.literal("sampling/createMessage"),params:T.extend({messages:H.array(k9),systemPrompt:H.optional(H.string()),includeContext:H.optional(H.enum(["none","thisServer","allServers"])),temperature:H.optional(H.number()),maxTokens:H.number().int(),stopSequences:H.optional(H.array(H.string())),metadata:H.optional(H.object({}).passthrough()),modelPreferences:H.optional(f9)})}),J1=h.extend({model:H.string(),stopReason:H.optional(H.enum(["endTurn","stopSequence","maxTokens"]).or(H.string())),role:H.enum(["user","assistant"]),content:H.discriminatedUnion("type",[n0,i0])}),P9=H.object({type:H.literal("ref/resource"),uri:H.string()}).passthrough(),T9=H.object({type:H.literal("ref/prompt"),name:H.string()}).passthrough(),h9=v.extend({method:H.literal("completion/complete"),params:T.extend({ref:H.union([T9,P9]),argument:H.object({name:H.string(),value:H.string()}).passthrough()})}),g9=h.extend({completion:H.object({values:H.array(H.string()).max(100),total:H.optional(H.number().int()),hasMore:H.optional(H.boolean())}).passthrough()}),x9=H.object({uri:H.string().startsWith("file://"),name:H.optional(H.string())}).passthrough(),y9=v.extend({method:H.literal("roots/list")}),H1=h.extend({roots:H.array(x9)}),m9=y.extend({method:H.literal("notifications/roots/list_changed")}),H$=H.union([Z0,$1,h9,v9,K9,U9,G9,B9,M9,V9,A9,W1,Q1]),G$=H.union([l0,c0,X1,m9]),Y$=H.union([m0,J1,H1]),B$=H.union([Z0,I9,y9]),q$=H.union([l0,c0,b9,O9,w9,S9,j9]),M$=H.union([m0,Q9,g9,N9,D9,Y9,q9,z9,g1,_9]);class b0 extends Error{constructor($,X,Q){super(`MCP error ${$}: ${X}`);this.code=$,this.data=Q}}var l9=60000;class G1{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.setNotificationHandler(l0,(X)=>{let Q=this._requestHandlerAbortControllers.get(X.params.requestId);Q===null||Q===void 0||Q.abort(X.params.reason)}),this.setNotificationHandler(c0,(X)=>{this._onprogress(X)}),this.setRequestHandler(Z0,(X)=>({}))}async connect($){this._transport=$,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=(X)=>{this._onerror(X)},this._transport.onmessage=(X)=>{if(!("method"in X))this._onresponse(X);else if("id"in X)this._onrequest(X);else this._onnotification(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 b0(X0.ConnectionClosed,"Connection closed");for(let W of X.values())W(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((W)=>this._onerror(new Error(`Uncaught error in notification handler: ${W}`)))}_onrequest($){var X,Q;let W=(X=this._requestHandlers.get($.method))!==null&&X!==void 0?X:this.fallbackRequestHandler;if(W===void 0){(Q=this._transport)===null||Q===void 0||Q.send({jsonrpc:"2.0",id:$.id,error:{code:X0.MethodNotFound,message:"Method not found"}}).catch((G)=>this._onerror(new Error(`Failed to send an error response: ${G}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set($.id,J),Promise.resolve().then(()=>W($,{signal:J.signal})).then((G)=>{var Y;if(J.signal.aborted)return;return(Y=this._transport)===null||Y===void 0?void 0:Y.send({result:G,jsonrpc:"2.0",id:$.id})},(G)=>{var Y,B;if(J.signal.aborted)return;return(Y=this._transport)===null||Y===void 0?void 0:Y.send({jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(G.code)?G.code:X0.InternalError,message:(B=G.message)!==null&&B!==void 0?B:"Internal error"}})}).catch((G)=>this._onerror(new Error(`Failed to send response: ${G}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:X,...Q}=$.params,W=this._progressHandlers.get(Number(X));if(W===void 0){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}W(Q)}_onresponse($){let X=$.id,Q=this._responseHandlers.get(Number(X));if(Q===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}if(this._responseHandlers.delete(Number(X)),this._progressHandlers.delete(Number(X)),"result"in $)Q($);else{let W=new b0($.error.code,$.error.message,$.error.data);Q(W)}}get transport(){return this._transport}async close(){var $;await(($=this._transport)===null||$===void 0?void 0:$.close())}request($,X,Q){return new Promise((W,J)=>{var G,Y,B,M;if(!this._transport){J(new Error("Not connected"));return}if(((G=this._options)===null||G===void 0?void 0:G.enforceStrictCapabilities)===!0)this.assertCapabilityForMethod($.method);(Y=Q===null||Q===void 0?void 0:Q.signal)===null||Y===void 0||Y.throwIfAborted();let V=this._requestMessageId++,F={...$,jsonrpc:"2.0",id:V};if(Q===null||Q===void 0?void 0:Q.onprogress)this._progressHandlers.set(V,Q.onprogress),F.params={...$.params,_meta:{progressToken:V}};let _=void 0;this._responseHandlers.set(V,(b)=>{var r;if(_!==void 0)clearTimeout(_);if((r=Q===null||Q===void 0?void 0:Q.signal)===null||r===void 0?void 0:r.aborted)return;if(b instanceof Error)return J(b);try{let R0=X.parse(b.result);W(R0)}catch(R0){J(R0)}});let u=(b)=>{var r;this._responseHandlers.delete(V),this._progressHandlers.delete(V),(r=this._transport)===null||r===void 0||r.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:V,reason:String(b)}}).catch((R0)=>this._onerror(new Error(`Failed to send cancellation: ${R0}`))),J(b)};(B=Q===null||Q===void 0?void 0:Q.signal)===null||B===void 0||B.addEventListener("abort",()=>{var b;if(_!==void 0)clearTimeout(_);u((b=Q===null||Q===void 0?void 0:Q.signal)===null||b===void 0?void 0:b.reason)});let V1=(M=Q===null||Q===void 0?void 0:Q.timeout)!==null&&M!==void 0?M:l9;_=setTimeout(()=>u(new b0(X0.RequestTimeout,"Request timed out",{timeout:V1})),V1),this._transport.send(F).catch((b)=>{if(_!==void 0)clearTimeout(_);J(b)})})}async notification($){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability($.method);let X={...$,jsonrpc:"2.0"};await this._transport.send(X)}setRequestHandler($,X){let Q=$.shape.method.value;this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(W,J)=>Promise.resolve(X($.parse(W),J)))}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 y1($,X){return Object.entries(X).reduce((Q,[W,J])=>{if(J&&typeof J==="object")Q[W]=Q[W]?{...Q[W],...J}:J;else Q[W]=J;return Q},{...$})}class Y1 extends G1{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($1,(W)=>this._oninitialize(W)),this.setNotificationHandler(X1,()=>{var W;return(W=this.oninitialized)===null||W===void 0?void 0:W.call(this)})}registerCapabilities($){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=y1(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:v1.includes(X)?X:e0,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"},m0)}async createMessage($,X){return this.request({method:"sampling/createMessage",params:$},J1,X)}async listRoots($,X){return this.request({method:"roots/list",params:$},H1,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"})}}import l1 from"node:process";class B1{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
3
- `);if($===-1)return null;let X=this._buffer.toString("utf8",0,$);return this._buffer=this._buffer.subarray($+1),Z9(X)}clear(){this._buffer=void 0}}function Z9($){return f1.parse(JSON.parse($))}function m1($){return JSON.stringify($)+`
4
- `}class q1{constructor($=l1.stdin,X=l1.stdout){this._stdin=$,this._stdout=X,this._readBuffer=new B1,this._started=!1,this._ondata=(Q)=>{this._readBuffer.append(Q),this.processReadBuffer()},this._onerror=(Q)=>{var W;(W=this.onerror)===null||W===void 0||W.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=m1($);if(this._stdout.write(Q))X();else this._stdout.once("drain",X)})}}import{join as n9}from"path";import{readFile as i9,access as d9,constants as r9}from"fs/promises";import{join as f0}from"path";import{join as u9}from"path";import{readdir as c1,readFile as p9}from"fs/promises";import d0 from"pino";import c9 from"os";var Z1=process.env.LOG_FILE_PATH||(process.env.HOME?`${process.env.HOME}/.specifai/mcp-log.log`:void 0),M1={level:process.env.LOG_LEVEL||"info",base:{version:"0.4.0",pid:process.pid,hostname:c9.hostname()}},O;if(Z1)try{let $={target:"pino/file",options:{destination:Z1,append:!0,sync:!1,mkdir:!0,silent:!0},worker:{autoEnd:!1}};O=d0(M1,d0.transport($))}catch($){O=d0({...M1,enabled:!1})}else O=d0({...M1,enabled:!1});class C0{async readAllJsonFiles($){try{let Q=(await c1($)).filter((J)=>J.endsWith(".json"));return await Promise.all(Q.map(async(J)=>{let G=u9($,J),Y=await p9(G,"utf-8");try{return{name:J,content:JSON.parse(Y)}}catch(B){return O.error({error:B,file:J},`Error parsing JSON file ${J}`),{name:J,content:null,error:"Invalid JSON"}}}))}catch(X){return O.warn({error:X},"Directory not found, returning empty array"),[]}}async isDirectory($){try{let X=await c1($);return!0}catch{return!1}}}class z1{fileService;constructor(){this.fileService=new C0}normalize($){return O.debug({count:$.length},"Normalizing documents"),$.map((X)=>({id:X.name.replace(".json","").replace("-base",""),title:X.content.title,description:X.content.requirement}))}processPRDs($){return O.debug({count:$.length},"Processing PRD files"),$.map((X)=>{if(!X.name.includes("feature")){let Q=$.find((J)=>J.name===X.name.replace("base","feature"));if(!Q)return O.warn({basePrd:X.name},"No matching feature PRD found"),null;let W=Q.content.features.map((J)=>({id:J.id,title:J.name,description:J.description,tasks:J.tasks.map((G)=>({id:G.id,title:G.list,description:G.acceptance}))}));return O.debug({prdId:X.name,userStoriesCount:W.length},"Processed PRD with user stories"),{id:X.name.replace(".json","").replace("-base",""),title:X.content.title,description:X.content.requirement,userStories:W}}return null}).filter((X)=>X!==null)}async loadSolution($){if(O.info({projectPath:$},"Loading solution"),!await this.fileService.isDirectory($))throw O.error({projectPath:$},"Invalid project path"),new Error(`Invalid project path: ${$}`);try{let[X,Q,W,J,G]=await Promise.all([this.fileService.readAllJsonFiles(f0($,"BP")),this.fileService.readAllJsonFiles(f0($,"BRD")),this.fileService.readAllJsonFiles(f0($,"PRD")),this.fileService.readAllJsonFiles(f0($,"NFR")),this.fileService.readAllJsonFiles(f0($,"UIR"))]),Y={BP:this.normalize(X),BRD:this.normalize(Q),PRD:this.processPRDs(W),NFR:this.normalize(J),UIR:this.normalize(G)};return O.info({bpsCount:Y.BP.length,brdsCount:Y.BRD.length,prdsCount:Y.PRD.length,nfrsCount:Y.NFR.length,uirsCount:Y.UIR.length},"Solution loaded successfully"),Y}catch(X){return O.warn({error:X,projectPath:$},"Some directories not found while loading solution"),{BP:[],BRD:[],PRD:[],NFR:[],UIR:[]}}}findPRD($,X){let Q=$.PRD.find((W)=>W.id===X)||null;if(!Q)O.debug({prdId:X},"PRD not found");return Q}findUserStory($,X){let Q=$.userStories.find((W)=>W.id===X)||null;if(!Q)O.debug({prdId:$.id,userStoryId:X},"User Story not found");return Q}findTask($,X){let Q=$.tasks?.find((W)=>W.id===X)||null;if(!Q)O.debug({userStoryId:$.id,taskId:X},"Task not found");return Q}}var o9=$0({prdId:H.string(),cwd:H.string()}),a9=$0({prdId:H.string(),userStoryId:H.string(),cwd:H.string()}),s9=$0({prdId:H.string(),userStoryId:H.string(),taskId:H.string(),cwd:H.string()}),k0=$0({cwd:H.string()});class w1{server;documentService;fileService;solution;projectPath;constructor($){this.solution=null,this.projectPath=$||null,this.documentService=new z1,this.fileService=new C0,this.server=new Y1({name:"specifai",version:"0.4.0"},{capabilities:{tools:{}}}),O.info("Initializing MCP server..."),this.setupRequestHandlers(),O.info("MCP server initialized")}formatDocuments($){return $.map((X)=>[`ID: ${X.id}`,`Title: ${X.title}`,`Description: ${X.description}`,"--------------"].join(`
2
+ var v;(function(X){X.assertEqual=(H)=>H;function Q(H){}X.assertIs=Q;function $(H){throw new Error}X.assertNever=$,X.arrayToEnum=(H)=>{let W={};for(let G of H)W[G]=G;return W},X.getValidEnumValues=(H)=>{let W=X.objectKeys(H).filter((B)=>typeof H[H[B]]!=="number"),G={};for(let B of W)G[B]=H[B];return X.objectValues(G)},X.objectValues=(H)=>{return X.objectKeys(H).map(function(W){return H[W]})},X.objectKeys=typeof Object.keys==="function"?(H)=>Object.keys(H):(H)=>{let W=[];for(let G in H)if(Object.prototype.hasOwnProperty.call(H,G))W.push(G);return W},X.find=(H,W)=>{for(let G of H)if(W(G))return G;return},X.isInteger=typeof Number.isInteger==="function"?(H)=>Number.isInteger(H):(H)=>typeof H==="number"&&isFinite(H)&&Math.floor(H)===H;function J(H,W=" | "){return H.map((G)=>typeof G==="string"?`'${G}'`:G).join(W)}X.joinValues=J,X.jsonStringifyReplacer=(H,W)=>{if(typeof W==="bigint")return W.toString();return W}})(v||(v={}));var B0;(function(X){X.mergeShapes=(Q,$)=>{return{...Q,...$}}})(B0||(B0={}));var z=v.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),d=(X)=>{switch(typeof X){case"undefined":return z.undefined;case"string":return z.string;case"number":return isNaN(X)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":if(Array.isArray(X))return z.array;if(X===null)return z.null;if(X.then&&typeof X.then==="function"&&X.catch&&typeof X.catch==="function")return z.promise;if(typeof Map!=="undefined"&&X instanceof Map)return z.map;if(typeof Set!=="undefined"&&X instanceof Set)return z.set;if(typeof Date!=="undefined"&&X instanceof Date)return z.date;return z.object;default:return z.unknown}},A=v.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),E9=(X)=>{return JSON.stringify(X,null,2).replace(/"([^"]+)":/g,"$1:")};class f extends Error{get errors(){return this.issues}constructor(X){super();this.issues=[],this.addIssue=($)=>{this.issues=[...this.issues,$]},this.addIssues=($=[])=>{this.issues=[...this.issues,...$]};let Q=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,Q);else this.__proto__=Q;this.name="ZodError",this.issues=X}format(X){let Q=X||function(H){return H.message},$={_errors:[]},J=(H)=>{for(let W of H.issues)if(W.code==="invalid_union")W.unionErrors.map(J);else if(W.code==="invalid_return_type")J(W.returnTypeError);else if(W.code==="invalid_arguments")J(W.argumentsError);else if(W.path.length===0)$._errors.push(Q(W));else{let G=$,B=0;while(B<W.path.length){let w=W.path[B];if(B!==W.path.length-1)G[w]=G[w]||{_errors:[]};else G[w]=G[w]||{_errors:[]},G[w]._errors.push(Q(W));G=G[w],B++}}};return J(this),$}static assert(X){if(!(X instanceof f))throw new Error(`Not a ZodError: ${X}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(X=(Q)=>Q.message){let Q={},$=[];for(let J of this.issues)if(J.path.length>0)Q[J.path[0]]=Q[J.path[0]]||[],Q[J.path[0]].push(X(J));else $.push(X(J));return{formErrors:$,fieldErrors:Q}}get formErrors(){return this.flatten()}}f.create=(X)=>{return new f(X)};var V1=(X,Q)=>{let $;switch(X.code){case A.invalid_type:if(X.received===z.undefined)$="Required";else $=`Expected ${X.expected}, received ${X.received}`;break;case A.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(X.expected,v.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:$=`Unrecognized key(s) in object: ${v.joinValues(X.keys,", ")}`;break;case A.invalid_union:$="Invalid input";break;case A.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${v.joinValues(X.options)}`;break;case A.invalid_enum_value:$=`Invalid enum value. Expected ${v.joinValues(X.options)}, received '${X.received}'`;break;case A.invalid_arguments:$="Invalid function arguments";break;case A.invalid_return_type:$="Invalid function return type";break;case A.invalid_date:$="Invalid date";break;case A.invalid_string:if(typeof X.validation==="object")if("includes"in X.validation){if($=`Invalid input: must include "${X.validation.includes}"`,typeof X.validation.position==="number")$=`${$} at one or more positions greater than or equal to ${X.validation.position}`}else if("startsWith"in X.validation)$=`Invalid input: must start with "${X.validation.startsWith}"`;else if("endsWith"in X.validation)$=`Invalid input: must end with "${X.validation.endsWith}"`;else v.assertNever(X.validation);else if(X.validation!=="regex")$=`Invalid ${X.validation}`;else $="Invalid";break;case A.too_small:if(X.type==="array")$=`Array must contain ${X.exact?"exactly":X.inclusive?"at least":"more than"} ${X.minimum} element(s)`;else if(X.type==="string")$=`String must contain ${X.exact?"exactly":X.inclusive?"at least":"over"} ${X.minimum} character(s)`;else if(X.type==="number")$=`Number must be ${X.exact?"exactly equal to ":X.inclusive?"greater than or equal to ":"greater than "}${X.minimum}`;else if(X.type==="date")$=`Date must be ${X.exact?"exactly equal to ":X.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(X.minimum))}`;else $="Invalid input";break;case A.too_big:if(X.type==="array")$=`Array must contain ${X.exact?"exactly":X.inclusive?"at most":"less than"} ${X.maximum} element(s)`;else if(X.type==="string")$=`String must contain ${X.exact?"exactly":X.inclusive?"at most":"under"} ${X.maximum} character(s)`;else if(X.type==="number")$=`Number must be ${X.exact?"exactly":X.inclusive?"less than or equal to":"less than"} ${X.maximum}`;else if(X.type==="bigint")$=`BigInt must be ${X.exact?"exactly":X.inclusive?"less than or equal to":"less than"} ${X.maximum}`;else if(X.type==="date")$=`Date must be ${X.exact?"exactly":X.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(X.maximum))}`;else $="Invalid input";break;case A.custom:$="Invalid input";break;case A.invalid_intersection_types:$="Intersection results could not be merged";break;case A.not_multiple_of:$=`Number must be a multiple of ${X.multipleOf}`;break;case A.not_finite:$="Number must be finite";break;default:$=Q.defaultError,v.assertNever(X)}return{message:$}},y0=V1;function N9(X){y0=X}function l1(){return y0}var m1=(X)=>{let{data:Q,path:$,errorMaps:J,issueData:H}=X,W=[...$,...H.path||[]],G={...H,path:W};if(H.message!==void 0)return{...H,path:W,message:H.message};let B="",w=J.filter((M)=>!!M).slice().reverse();for(let M of w)B=M(G,{data:Q,defaultError:B}).message;return{...H,path:W,message:B}},_9=[];function V(X,Q){let $=l1(),J=m1({issueData:Q,data:X.data,path:X.path,errorMaps:[X.common.contextualErrorMap,X.schemaErrorMap,$,$===V1?void 0:V1].filter((H)=>!!H)});X.common.issues.push(J)}class b{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(X,Q){let $=[];for(let J of Q){if(J.status==="aborted")return R;if(J.status==="dirty")X.dirty();$.push(J.value)}return{status:X.value,value:$}}static async mergeObjectAsync(X,Q){let $=[];for(let J of Q){let H=await J.key,W=await J.value;$.push({key:H,value:W})}return b.mergeObjectSync(X,$)}static mergeObjectSync(X,Q){let $={};for(let J of Q){let{key:H,value:W}=J;if(H.status==="aborted")return R;if(W.status==="aborted")return R;if(H.status==="dirty")X.dirty();if(W.status==="dirty")X.dirty();if(H.value!=="__proto__"&&(typeof W.value!=="undefined"||J.alwaysSet))$[H.value]=W.value}return{status:X.value,value:$}}}var R=Object.freeze({status:"aborted"}),M1=(X)=>({status:"dirty",value:X}),P=(X)=>({status:"valid",value:X}),w0=(X)=>X.status==="aborted",M0=(X)=>X.status==="dirty",$1=(X)=>X.status==="valid",S1=(X)=>typeof Promise!=="undefined"&&X instanceof Promise;function c1(X,Q,$,J){if($==="a"&&!J)throw new TypeError("Private accessor was defined without a getter");if(typeof Q==="function"?X!==Q||!J:!Q.has(X))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?J:$==="a"?J.call(X):J?J.value:Q.get(X)}function l0(X,Q,$,J,H){if(J==="m")throw new TypeError("Private method is not writable");if(J==="a"&&!H)throw new TypeError("Private accessor was defined without a setter");if(typeof Q==="function"?X!==Q||!H:!Q.has(X))throw new TypeError("Cannot write private member to an object whose class did not declare it");return J==="a"?H.call(X,$):H?H.value=$:Q.set(X,$),$}var L;(function(X){X.errToObj=(Q)=>typeof Q==="string"?{message:Q}:Q||{},X.toString=(Q)=>typeof Q==="string"?Q:Q===null||Q===void 0?void 0:Q.message})(L||(L={}));var j1,v1;class Z{constructor(X,Q,$,J){this._cachedPath=[],this.parent=X,this.data=Q,this._path=$,this._key=J}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var x0=(X,Q)=>{if($1(Q))return{success:!0,data:Q.value};else{if(!X.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let $=new f(X.common.issues);return this._error=$,this._error}}}};function _(X){if(!X)return{};let{errorMap:Q,invalid_type_error:$,required_error:J,description:H}=X;if(Q&&($||J))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(Q)return{errorMap:Q,description:H};return{errorMap:(G,B)=>{var w,M;let{message:q}=X;if(G.code==="invalid_enum_value")return{message:q!==null&&q!==void 0?q:B.defaultError};if(typeof B.data==="undefined")return{message:(w=q!==null&&q!==void 0?q:J)!==null&&w!==void 0?w:B.defaultError};if(G.code!=="invalid_type")return{message:B.defaultError};return{message:(M=q!==null&&q!==void 0?q:$)!==null&&M!==void 0?M:B.defaultError}},description:H}}class F{get description(){return this._def.description}_getType(X){return d(X.data)}_getOrReturnCtx(X,Q){return Q||{common:X.parent.common,data:X.data,parsedType:d(X.data),schemaErrorMap:this._def.errorMap,path:X.path,parent:X.parent}}_processInputParams(X){return{status:new b,ctx:{common:X.parent.common,data:X.data,parsedType:d(X.data),schemaErrorMap:this._def.errorMap,path:X.path,parent:X.parent}}}_parseSync(X){let Q=this._parse(X);if(S1(Q))throw new Error("Synchronous parse encountered promise.");return Q}_parseAsync(X){let Q=this._parse(X);return Promise.resolve(Q)}parse(X,Q){let $=this.safeParse(X,Q);if($.success)return $.data;throw $.error}safeParse(X,Q){var $;let J={common:{issues:[],async:($=Q===null||Q===void 0?void 0:Q.async)!==null&&$!==void 0?$:!1,contextualErrorMap:Q===null||Q===void 0?void 0:Q.errorMap},path:(Q===null||Q===void 0?void 0:Q.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:X,parsedType:d(X)},H=this._parseSync({data:X,path:J.path,parent:J});return x0(J,H)}"~validate"(X){var Q,$;let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:X,parsedType:d(X)};if(!this["~standard"].async)try{let H=this._parseSync({data:X,path:[],parent:J});return $1(H)?{value:H.value}:{issues:J.common.issues}}catch(H){if(($=(Q=H===null||H===void 0?void 0:H.message)===null||Q===void 0?void 0:Q.toLowerCase())===null||$===void 0?void 0:$.includes("encountered"))this["~standard"].async=!0;J.common={issues:[],async:!0}}return this._parseAsync({data:X,path:[],parent:J}).then((H)=>$1(H)?{value:H.value}:{issues:J.common.issues})}async parseAsync(X,Q){let $=await this.safeParseAsync(X,Q);if($.success)return $.data;throw $.error}async safeParseAsync(X,Q){let $={common:{issues:[],contextualErrorMap:Q===null||Q===void 0?void 0:Q.errorMap,async:!0},path:(Q===null||Q===void 0?void 0:Q.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:X,parsedType:d(X)},J=this._parse({data:X,path:$.path,parent:$}),H=await(S1(J)?J:Promise.resolve(J));return x0($,H)}refine(X,Q){let $=(J)=>{if(typeof Q==="string"||typeof Q==="undefined")return{message:Q};else if(typeof Q==="function")return Q(J);else return Q};return this._refinement((J,H)=>{let W=X(J),G=()=>H.addIssue({code:A.custom,...$(J)});if(typeof Promise!=="undefined"&&W instanceof Promise)return W.then((B)=>{if(!B)return G(),!1;else return!0});if(!W)return G(),!1;else return!0})}refinement(X,Q){return this._refinement(($,J)=>{if(!X($))return J.addIssue(typeof Q==="function"?Q($,J):Q),!1;else return!0})}_refinement(X){return new T({schema:this,typeName:O.ZodEffects,effect:{type:"refinement",refinement:X}})}superRefine(X){return this._refinement(X)}constructor(X){this.spa=this.safeParseAsync,this._def=X,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:(Q)=>this["~validate"](Q)}}optional(){return h.create(this,this._def)}nullable(){return r.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return x.create(this)}promise(){return W1.create(this,this._def)}or(X){return L1.create([this,X],this._def)}and(X){return K1.create(this,X,this._def)}transform(X){return new T({..._(this._def),schema:this,typeName:O.ZodEffects,effect:{type:"transform",transform:X}})}default(X){let Q=typeof X==="function"?X:()=>X;return new N1({..._(this._def),innerType:this,defaultValue:Q,typeName:O.ZodDefault})}brand(){return new p1({typeName:O.ZodBranded,type:this,..._(this._def)})}catch(X){let Q=typeof X==="function"?X:()=>X;return new _1({..._(this._def),innerType:this,catchValue:Q,typeName:O.ZodCatch})}describe(X){return new this.constructor({...this._def,description:X})}pipe(X){return I1.create(this,X)}readonly(){return F1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var F9=/^c[^\s-]{8,}$/i,D9=/^[0-9a-z]+$/,j9=/^[0-9A-HJKMNP-TV-Z]{26}$/i,v9=/^[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,S9=/^[a-z0-9_-]{21}$/i,C9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,b9=/^[-+]?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)?)??$/,P9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,k9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",G0,f9=/^(?:(?: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])$/,I9=/^(?:(?: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])$/,T9=/^(([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]))$/,g9=/^(([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])$/,x9=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,h9=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,m0="((\\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])))",Z9=new RegExp(`^${m0}$`);function c0(X){let Q="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(X.precision)Q=`${Q}\\.\\d{${X.precision}}`;else if(X.precision==null)Q=`${Q}(\\.\\d+)?`;return Q}function y9(X){return new RegExp(`^${c0(X)}$`)}function u0(X){let Q=`${m0}T${c0(X)}`,$=[];if($.push(X.local?"Z?":"Z"),X.offset)$.push("([+-]\\d{2}:?\\d{2})");return Q=`${Q}(${$.join("|")})`,new RegExp(`^${Q}$`)}function l9(X,Q){if((Q==="v4"||!Q)&&f9.test(X))return!0;if((Q==="v6"||!Q)&&T9.test(X))return!0;return!1}function m9(X,Q){if(!C9.test(X))return!1;try{let[$]=X.split("."),J=$.replace(/-/g,"+").replace(/_/g,"/").padEnd($.length+(4-$.length%4)%4,"="),H=JSON.parse(atob(J));if(typeof H!=="object"||H===null)return!1;if(!H.typ||!H.alg)return!1;if(Q&&H.alg!==Q)return!1;return!0}catch($){return!1}}function c9(X,Q){if((Q==="v4"||!Q)&&I9.test(X))return!0;if((Q==="v6"||!Q)&&g9.test(X))return!0;return!1}class g extends F{_parse(X){if(this._def.coerce)X.data=String(X.data);if(this._getType(X)!==z.string){let H=this._getOrReturnCtx(X);return V(H,{code:A.invalid_type,expected:z.string,received:H.parsedType}),R}let $=new b,J=void 0;for(let H of this._def.checks)if(H.kind==="min"){if(X.data.length<H.value)J=this._getOrReturnCtx(X,J),V(J,{code:A.too_small,minimum:H.value,type:"string",inclusive:!0,exact:!1,message:H.message}),$.dirty()}else if(H.kind==="max"){if(X.data.length>H.value)J=this._getOrReturnCtx(X,J),V(J,{code:A.too_big,maximum:H.value,type:"string",inclusive:!0,exact:!1,message:H.message}),$.dirty()}else if(H.kind==="length"){let W=X.data.length>H.value,G=X.data.length<H.value;if(W||G){if(J=this._getOrReturnCtx(X,J),W)V(J,{code:A.too_big,maximum:H.value,type:"string",inclusive:!0,exact:!0,message:H.message});else if(G)V(J,{code:A.too_small,minimum:H.value,type:"string",inclusive:!0,exact:!0,message:H.message});$.dirty()}}else if(H.kind==="email"){if(!P9.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"email",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="emoji"){if(!G0)G0=new RegExp(k9,"u");if(!G0.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"emoji",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="uuid"){if(!v9.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"uuid",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="nanoid"){if(!S9.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"nanoid",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="cuid"){if(!F9.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"cuid",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="cuid2"){if(!D9.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"cuid2",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="ulid"){if(!j9.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"ulid",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="url")try{new URL(X.data)}catch(W){J=this._getOrReturnCtx(X,J),V(J,{validation:"url",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="regex"){if(H.regex.lastIndex=0,!H.regex.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"regex",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="trim")X.data=X.data.trim();else if(H.kind==="includes"){if(!X.data.includes(H.value,H.position))J=this._getOrReturnCtx(X,J),V(J,{code:A.invalid_string,validation:{includes:H.value,position:H.position},message:H.message}),$.dirty()}else if(H.kind==="toLowerCase")X.data=X.data.toLowerCase();else if(H.kind==="toUpperCase")X.data=X.data.toUpperCase();else if(H.kind==="startsWith"){if(!X.data.startsWith(H.value))J=this._getOrReturnCtx(X,J),V(J,{code:A.invalid_string,validation:{startsWith:H.value},message:H.message}),$.dirty()}else if(H.kind==="endsWith"){if(!X.data.endsWith(H.value))J=this._getOrReturnCtx(X,J),V(J,{code:A.invalid_string,validation:{endsWith:H.value},message:H.message}),$.dirty()}else if(H.kind==="datetime"){if(!u0(H).test(X.data))J=this._getOrReturnCtx(X,J),V(J,{code:A.invalid_string,validation:"datetime",message:H.message}),$.dirty()}else if(H.kind==="date"){if(!Z9.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{code:A.invalid_string,validation:"date",message:H.message}),$.dirty()}else if(H.kind==="time"){if(!y9(H).test(X.data))J=this._getOrReturnCtx(X,J),V(J,{code:A.invalid_string,validation:"time",message:H.message}),$.dirty()}else if(H.kind==="duration"){if(!b9.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"duration",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="ip"){if(!l9(X.data,H.version))J=this._getOrReturnCtx(X,J),V(J,{validation:"ip",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="jwt"){if(!m9(X.data,H.alg))J=this._getOrReturnCtx(X,J),V(J,{validation:"jwt",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="cidr"){if(!c9(X.data,H.version))J=this._getOrReturnCtx(X,J),V(J,{validation:"cidr",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="base64"){if(!x9.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"base64",code:A.invalid_string,message:H.message}),$.dirty()}else if(H.kind==="base64url"){if(!h9.test(X.data))J=this._getOrReturnCtx(X,J),V(J,{validation:"base64url",code:A.invalid_string,message:H.message}),$.dirty()}else v.assertNever(H);return{status:$.value,value:X.data}}_regex(X,Q,$){return this.refinement((J)=>X.test(J),{validation:Q,code:A.invalid_string,...L.errToObj($)})}_addCheck(X){return new g({...this._def,checks:[...this._def.checks,X]})}email(X){return this._addCheck({kind:"email",...L.errToObj(X)})}url(X){return this._addCheck({kind:"url",...L.errToObj(X)})}emoji(X){return this._addCheck({kind:"emoji",...L.errToObj(X)})}uuid(X){return this._addCheck({kind:"uuid",...L.errToObj(X)})}nanoid(X){return this._addCheck({kind:"nanoid",...L.errToObj(X)})}cuid(X){return this._addCheck({kind:"cuid",...L.errToObj(X)})}cuid2(X){return this._addCheck({kind:"cuid2",...L.errToObj(X)})}ulid(X){return this._addCheck({kind:"ulid",...L.errToObj(X)})}base64(X){return this._addCheck({kind:"base64",...L.errToObj(X)})}base64url(X){return this._addCheck({kind:"base64url",...L.errToObj(X)})}jwt(X){return this._addCheck({kind:"jwt",...L.errToObj(X)})}ip(X){return this._addCheck({kind:"ip",...L.errToObj(X)})}cidr(X){return this._addCheck({kind:"cidr",...L.errToObj(X)})}datetime(X){var Q,$;if(typeof X==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:X});return this._addCheck({kind:"datetime",precision:typeof(X===null||X===void 0?void 0:X.precision)==="undefined"?null:X===null||X===void 0?void 0:X.precision,offset:(Q=X===null||X===void 0?void 0:X.offset)!==null&&Q!==void 0?Q:!1,local:($=X===null||X===void 0?void 0:X.local)!==null&&$!==void 0?$:!1,...L.errToObj(X===null||X===void 0?void 0:X.message)})}date(X){return this._addCheck({kind:"date",message:X})}time(X){if(typeof X==="string")return this._addCheck({kind:"time",precision:null,message:X});return this._addCheck({kind:"time",precision:typeof(X===null||X===void 0?void 0:X.precision)==="undefined"?null:X===null||X===void 0?void 0:X.precision,...L.errToObj(X===null||X===void 0?void 0:X.message)})}duration(X){return this._addCheck({kind:"duration",...L.errToObj(X)})}regex(X,Q){return this._addCheck({kind:"regex",regex:X,...L.errToObj(Q)})}includes(X,Q){return this._addCheck({kind:"includes",value:X,position:Q===null||Q===void 0?void 0:Q.position,...L.errToObj(Q===null||Q===void 0?void 0:Q.message)})}startsWith(X,Q){return this._addCheck({kind:"startsWith",value:X,...L.errToObj(Q)})}endsWith(X,Q){return this._addCheck({kind:"endsWith",value:X,...L.errToObj(Q)})}min(X,Q){return this._addCheck({kind:"min",value:X,...L.errToObj(Q)})}max(X,Q){return this._addCheck({kind:"max",value:X,...L.errToObj(Q)})}length(X,Q){return this._addCheck({kind:"length",value:X,...L.errToObj(Q)})}nonempty(X){return this.min(1,L.errToObj(X))}trim(){return new g({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new g({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new g({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((X)=>X.kind==="datetime")}get isDate(){return!!this._def.checks.find((X)=>X.kind==="date")}get isTime(){return!!this._def.checks.find((X)=>X.kind==="time")}get isDuration(){return!!this._def.checks.find((X)=>X.kind==="duration")}get isEmail(){return!!this._def.checks.find((X)=>X.kind==="email")}get isURL(){return!!this._def.checks.find((X)=>X.kind==="url")}get isEmoji(){return!!this._def.checks.find((X)=>X.kind==="emoji")}get isUUID(){return!!this._def.checks.find((X)=>X.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((X)=>X.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((X)=>X.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((X)=>X.kind==="cuid2")}get isULID(){return!!this._def.checks.find((X)=>X.kind==="ulid")}get isIP(){return!!this._def.checks.find((X)=>X.kind==="ip")}get isCIDR(){return!!this._def.checks.find((X)=>X.kind==="cidr")}get isBase64(){return!!this._def.checks.find((X)=>X.kind==="base64")}get isBase64url(){return!!this._def.checks.find((X)=>X.kind==="base64url")}get minLength(){let X=null;for(let Q of this._def.checks)if(Q.kind==="min"){if(X===null||Q.value>X)X=Q.value}return X}get maxLength(){let X=null;for(let Q of this._def.checks)if(Q.kind==="max"){if(X===null||Q.value<X)X=Q.value}return X}}g.create=(X)=>{var Q;return new g({checks:[],typeName:O.ZodString,coerce:(Q=X===null||X===void 0?void 0:X.coerce)!==null&&Q!==void 0?Q:!1,..._(X)})};function u9(X,Q){let $=(X.toString().split(".")[1]||"").length,J=(Q.toString().split(".")[1]||"").length,H=$>J?$:J,W=parseInt(X.toFixed(H).replace(".","")),G=parseInt(Q.toFixed(H).replace(".",""));return W%G/Math.pow(10,H)}class o extends F{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(X){if(this._def.coerce)X.data=Number(X.data);if(this._getType(X)!==z.number){let H=this._getOrReturnCtx(X);return V(H,{code:A.invalid_type,expected:z.number,received:H.parsedType}),R}let $=void 0,J=new b;for(let H of this._def.checks)if(H.kind==="int"){if(!v.isInteger(X.data))$=this._getOrReturnCtx(X,$),V($,{code:A.invalid_type,expected:"integer",received:"float",message:H.message}),J.dirty()}else if(H.kind==="min"){if(H.inclusive?X.data<H.value:X.data<=H.value)$=this._getOrReturnCtx(X,$),V($,{code:A.too_small,minimum:H.value,type:"number",inclusive:H.inclusive,exact:!1,message:H.message}),J.dirty()}else if(H.kind==="max"){if(H.inclusive?X.data>H.value:X.data>=H.value)$=this._getOrReturnCtx(X,$),V($,{code:A.too_big,maximum:H.value,type:"number",inclusive:H.inclusive,exact:!1,message:H.message}),J.dirty()}else if(H.kind==="multipleOf"){if(u9(X.data,H.value)!==0)$=this._getOrReturnCtx(X,$),V($,{code:A.not_multiple_of,multipleOf:H.value,message:H.message}),J.dirty()}else if(H.kind==="finite"){if(!Number.isFinite(X.data))$=this._getOrReturnCtx(X,$),V($,{code:A.not_finite,message:H.message}),J.dirty()}else v.assertNever(H);return{status:J.value,value:X.data}}gte(X,Q){return this.setLimit("min",X,!0,L.toString(Q))}gt(X,Q){return this.setLimit("min",X,!1,L.toString(Q))}lte(X,Q){return this.setLimit("max",X,!0,L.toString(Q))}lt(X,Q){return this.setLimit("max",X,!1,L.toString(Q))}setLimit(X,Q,$,J){return new o({...this._def,checks:[...this._def.checks,{kind:X,value:Q,inclusive:$,message:L.toString(J)}]})}_addCheck(X){return new o({...this._def,checks:[...this._def.checks,X]})}int(X){return this._addCheck({kind:"int",message:L.toString(X)})}positive(X){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(X)})}negative(X){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(X)})}nonpositive(X){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(X)})}nonnegative(X){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(X)})}multipleOf(X,Q){return this._addCheck({kind:"multipleOf",value:X,message:L.toString(Q)})}finite(X){return this._addCheck({kind:"finite",message:L.toString(X)})}safe(X){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(X)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(X)})}get minValue(){let X=null;for(let Q of this._def.checks)if(Q.kind==="min"){if(X===null||Q.value>X)X=Q.value}return X}get maxValue(){let X=null;for(let Q of this._def.checks)if(Q.kind==="max"){if(X===null||Q.value<X)X=Q.value}return X}get isInt(){return!!this._def.checks.find((X)=>X.kind==="int"||X.kind==="multipleOf"&&v.isInteger(X.value))}get isFinite(){let X=null,Q=null;for(let $ of this._def.checks)if($.kind==="finite"||$.kind==="int"||$.kind==="multipleOf")return!0;else if($.kind==="min"){if(Q===null||$.value>Q)Q=$.value}else if($.kind==="max"){if(X===null||$.value<X)X=$.value}return Number.isFinite(Q)&&Number.isFinite(X)}}o.create=(X)=>{return new o({checks:[],typeName:O.ZodNumber,coerce:(X===null||X===void 0?void 0:X.coerce)||!1,..._(X)})};class s extends F{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(X){if(this._def.coerce)try{X.data=BigInt(X.data)}catch(H){return this._getInvalidInput(X)}if(this._getType(X)!==z.bigint)return this._getInvalidInput(X);let $=void 0,J=new b;for(let H of this._def.checks)if(H.kind==="min"){if(H.inclusive?X.data<H.value:X.data<=H.value)$=this._getOrReturnCtx(X,$),V($,{code:A.too_small,type:"bigint",minimum:H.value,inclusive:H.inclusive,message:H.message}),J.dirty()}else if(H.kind==="max"){if(H.inclusive?X.data>H.value:X.data>=H.value)$=this._getOrReturnCtx(X,$),V($,{code:A.too_big,type:"bigint",maximum:H.value,inclusive:H.inclusive,message:H.message}),J.dirty()}else if(H.kind==="multipleOf"){if(X.data%H.value!==BigInt(0))$=this._getOrReturnCtx(X,$),V($,{code:A.not_multiple_of,multipleOf:H.value,message:H.message}),J.dirty()}else v.assertNever(H);return{status:J.value,value:X.data}}_getInvalidInput(X){let Q=this._getOrReturnCtx(X);return V(Q,{code:A.invalid_type,expected:z.bigint,received:Q.parsedType}),R}gte(X,Q){return this.setLimit("min",X,!0,L.toString(Q))}gt(X,Q){return this.setLimit("min",X,!1,L.toString(Q))}lte(X,Q){return this.setLimit("max",X,!0,L.toString(Q))}lt(X,Q){return this.setLimit("max",X,!1,L.toString(Q))}setLimit(X,Q,$,J){return new s({...this._def,checks:[...this._def.checks,{kind:X,value:Q,inclusive:$,message:L.toString(J)}]})}_addCheck(X){return new s({...this._def,checks:[...this._def.checks,X]})}positive(X){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L.toString(X)})}negative(X){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(X)})}nonpositive(X){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(X)})}nonnegative(X){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(X)})}multipleOf(X,Q){return this._addCheck({kind:"multipleOf",value:X,message:L.toString(Q)})}get minValue(){let X=null;for(let Q of this._def.checks)if(Q.kind==="min"){if(X===null||Q.value>X)X=Q.value}return X}get maxValue(){let X=null;for(let Q of this._def.checks)if(Q.kind==="max"){if(X===null||Q.value<X)X=Q.value}return X}}s.create=(X)=>{var Q;return new s({checks:[],typeName:O.ZodBigInt,coerce:(Q=X===null||X===void 0?void 0:X.coerce)!==null&&Q!==void 0?Q:!1,..._(X)})};class z1 extends F{_parse(X){if(this._def.coerce)X.data=Boolean(X.data);if(this._getType(X)!==z.boolean){let $=this._getOrReturnCtx(X);return V($,{code:A.invalid_type,expected:z.boolean,received:$.parsedType}),R}return P(X.data)}}z1.create=(X)=>{return new z1({typeName:O.ZodBoolean,coerce:(X===null||X===void 0?void 0:X.coerce)||!1,..._(X)})};class J1 extends F{_parse(X){if(this._def.coerce)X.data=new Date(X.data);if(this._getType(X)!==z.date){let H=this._getOrReturnCtx(X);return V(H,{code:A.invalid_type,expected:z.date,received:H.parsedType}),R}if(isNaN(X.data.getTime())){let H=this._getOrReturnCtx(X);return V(H,{code:A.invalid_date}),R}let $=new b,J=void 0;for(let H of this._def.checks)if(H.kind==="min"){if(X.data.getTime()<H.value)J=this._getOrReturnCtx(X,J),V(J,{code:A.too_small,message:H.message,inclusive:!0,exact:!1,minimum:H.value,type:"date"}),$.dirty()}else if(H.kind==="max"){if(X.data.getTime()>H.value)J=this._getOrReturnCtx(X,J),V(J,{code:A.too_big,message:H.message,inclusive:!0,exact:!1,maximum:H.value,type:"date"}),$.dirty()}else v.assertNever(H);return{status:$.value,value:new Date(X.data.getTime())}}_addCheck(X){return new J1({...this._def,checks:[...this._def.checks,X]})}min(X,Q){return this._addCheck({kind:"min",value:X.getTime(),message:L.toString(Q)})}max(X,Q){return this._addCheck({kind:"max",value:X.getTime(),message:L.toString(Q)})}get minDate(){let X=null;for(let Q of this._def.checks)if(Q.kind==="min"){if(X===null||Q.value>X)X=Q.value}return X!=null?new Date(X):null}get maxDate(){let X=null;for(let Q of this._def.checks)if(Q.kind==="max"){if(X===null||Q.value<X)X=Q.value}return X!=null?new Date(X):null}}J1.create=(X)=>{return new J1({checks:[],coerce:(X===null||X===void 0?void 0:X.coerce)||!1,typeName:O.ZodDate,..._(X)})};class C1 extends F{_parse(X){if(this._getType(X)!==z.symbol){let $=this._getOrReturnCtx(X);return V($,{code:A.invalid_type,expected:z.symbol,received:$.parsedType}),R}return P(X.data)}}C1.create=(X)=>{return new C1({typeName:O.ZodSymbol,..._(X)})};class q1 extends F{_parse(X){if(this._getType(X)!==z.undefined){let $=this._getOrReturnCtx(X);return V($,{code:A.invalid_type,expected:z.undefined,received:$.parsedType}),R}return P(X.data)}}q1.create=(X)=>{return new q1({typeName:O.ZodUndefined,..._(X)})};class U1 extends F{_parse(X){if(this._getType(X)!==z.null){let $=this._getOrReturnCtx(X);return V($,{code:A.invalid_type,expected:z.null,received:$.parsedType}),R}return P(X.data)}}U1.create=(X)=>{return new U1({typeName:O.ZodNull,..._(X)})};class H1 extends F{constructor(){super(...arguments);this._any=!0}_parse(X){return P(X.data)}}H1.create=(X)=>{return new H1({typeName:O.ZodAny,..._(X)})};class a extends F{constructor(){super(...arguments);this._unknown=!0}_parse(X){return P(X.data)}}a.create=(X)=>{return new a({typeName:O.ZodUnknown,..._(X)})};class m extends F{_parse(X){let Q=this._getOrReturnCtx(X);return V(Q,{code:A.invalid_type,expected:z.never,received:Q.parsedType}),R}}m.create=(X)=>{return new m({typeName:O.ZodNever,..._(X)})};class b1 extends F{_parse(X){if(this._getType(X)!==z.undefined){let $=this._getOrReturnCtx(X);return V($,{code:A.invalid_type,expected:z.void,received:$.parsedType}),R}return P(X.data)}}b1.create=(X)=>{return new b1({typeName:O.ZodVoid,..._(X)})};class x extends F{_parse(X){let{ctx:Q,status:$}=this._processInputParams(X),J=this._def;if(Q.parsedType!==z.array)return V(Q,{code:A.invalid_type,expected:z.array,received:Q.parsedType}),R;if(J.exactLength!==null){let W=Q.data.length>J.exactLength.value,G=Q.data.length<J.exactLength.value;if(W||G)V(Q,{code:W?A.too_big:A.too_small,minimum:G?J.exactLength.value:void 0,maximum:W?J.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:J.exactLength.message}),$.dirty()}if(J.minLength!==null){if(Q.data.length<J.minLength.value)V(Q,{code:A.too_small,minimum:J.minLength.value,type:"array",inclusive:!0,exact:!1,message:J.minLength.message}),$.dirty()}if(J.maxLength!==null){if(Q.data.length>J.maxLength.value)V(Q,{code:A.too_big,maximum:J.maxLength.value,type:"array",inclusive:!0,exact:!1,message:J.maxLength.message}),$.dirty()}if(Q.common.async)return Promise.all([...Q.data].map((W,G)=>{return J.type._parseAsync(new Z(Q,W,Q.path,G))})).then((W)=>{return b.mergeArray($,W)});let H=[...Q.data].map((W,G)=>{return J.type._parseSync(new Z(Q,W,Q.path,G))});return b.mergeArray($,H)}get element(){return this._def.type}min(X,Q){return new x({...this._def,minLength:{value:X,message:L.toString(Q)}})}max(X,Q){return new x({...this._def,maxLength:{value:X,message:L.toString(Q)}})}length(X,Q){return new x({...this._def,exactLength:{value:X,message:L.toString(Q)}})}nonempty(X){return this.min(1,X)}}x.create=(X,Q)=>{return new x({type:X,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,..._(Q)})};function w1(X){if(X instanceof S){let Q={};for(let $ in X.shape){let J=X.shape[$];Q[$]=h.create(w1(J))}return new S({...X._def,shape:()=>Q})}else if(X instanceof x)return new x({...X._def,type:w1(X.element)});else if(X instanceof h)return h.create(w1(X.unwrap()));else if(X instanceof r)return r.create(w1(X.unwrap()));else if(X instanceof c)return c.create(X.items.map((Q)=>w1(Q)));else return X}class S extends F{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let X=this._def.shape(),Q=v.objectKeys(X);return this._cached={shape:X,keys:Q}}_parse(X){if(this._getType(X)!==z.object){let w=this._getOrReturnCtx(X);return V(w,{code:A.invalid_type,expected:z.object,received:w.parsedType}),R}let{status:$,ctx:J}=this._processInputParams(X),{shape:H,keys:W}=this._getCached(),G=[];if(!(this._def.catchall instanceof m&&this._def.unknownKeys==="strip")){for(let w in J.data)if(!W.includes(w))G.push(w)}let B=[];for(let w of W){let M=H[w],q=J.data[w];B.push({key:{status:"valid",value:w},value:M._parse(new Z(J,q,J.path,w)),alwaysSet:w in J.data})}if(this._def.catchall instanceof m){let w=this._def.unknownKeys;if(w==="passthrough")for(let M of G)B.push({key:{status:"valid",value:M},value:{status:"valid",value:J.data[M]}});else if(w==="strict"){if(G.length>0)V(J,{code:A.unrecognized_keys,keys:G}),$.dirty()}else if(w==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let w=this._def.catchall;for(let M of G){let q=J.data[M];B.push({key:{status:"valid",value:M},value:w._parse(new Z(J,q,J.path,M)),alwaysSet:M in J.data})}}if(J.common.async)return Promise.resolve().then(async()=>{let w=[];for(let M of B){let q=await M.key,U=await M.value;w.push({key:q,value:U,alwaysSet:M.alwaysSet})}return w}).then((w)=>{return b.mergeObjectSync($,w)});else return b.mergeObjectSync($,B)}get shape(){return this._def.shape()}strict(X){return L.errToObj,new S({...this._def,unknownKeys:"strict",...X!==void 0?{errorMap:(Q,$)=>{var J,H,W,G;let B=(W=(H=(J=this._def).errorMap)===null||H===void 0?void 0:H.call(J,Q,$).message)!==null&&W!==void 0?W:$.defaultError;if(Q.code==="unrecognized_keys")return{message:(G=L.errToObj(X).message)!==null&&G!==void 0?G:B};return{message:B}}}:{}})}strip(){return new S({...this._def,unknownKeys:"strip"})}passthrough(){return new S({...this._def,unknownKeys:"passthrough"})}extend(X){return new S({...this._def,shape:()=>({...this._def.shape(),...X})})}merge(X){return new S({unknownKeys:X._def.unknownKeys,catchall:X._def.catchall,shape:()=>({...this._def.shape(),...X._def.shape()}),typeName:O.ZodObject})}setKey(X,Q){return this.augment({[X]:Q})}catchall(X){return new S({...this._def,catchall:X})}pick(X){let Q={};return v.objectKeys(X).forEach(($)=>{if(X[$]&&this.shape[$])Q[$]=this.shape[$]}),new S({...this._def,shape:()=>Q})}omit(X){let Q={};return v.objectKeys(this.shape).forEach(($)=>{if(!X[$])Q[$]=this.shape[$]}),new S({...this._def,shape:()=>Q})}deepPartial(){return w1(this)}partial(X){let Q={};return v.objectKeys(this.shape).forEach(($)=>{let J=this.shape[$];if(X&&!X[$])Q[$]=J;else Q[$]=J.optional()}),new S({...this._def,shape:()=>Q})}required(X){let Q={};return v.objectKeys(this.shape).forEach(($)=>{if(X&&!X[$])Q[$]=this.shape[$];else{let H=this.shape[$];while(H instanceof h)H=H._def.innerType;Q[$]=H}}),new S({...this._def,shape:()=>Q})}keyof(){return p0(v.objectKeys(this.shape))}}S.create=(X,Q)=>{return new S({shape:()=>X,unknownKeys:"strip",catchall:m.create(),typeName:O.ZodObject,..._(Q)})};S.strictCreate=(X,Q)=>{return new S({shape:()=>X,unknownKeys:"strict",catchall:m.create(),typeName:O.ZodObject,..._(Q)})};S.lazycreate=(X,Q)=>{return new S({shape:X,unknownKeys:"strip",catchall:m.create(),typeName:O.ZodObject,..._(Q)})};class L1 extends F{_parse(X){let{ctx:Q}=this._processInputParams(X),$=this._def.options;function J(H){for(let G of H)if(G.result.status==="valid")return G.result;for(let G of H)if(G.result.status==="dirty")return Q.common.issues.push(...G.ctx.common.issues),G.result;let W=H.map((G)=>new f(G.ctx.common.issues));return V(Q,{code:A.invalid_union,unionErrors:W}),R}if(Q.common.async)return Promise.all($.map(async(H)=>{let W={...Q,common:{...Q.common,issues:[]},parent:null};return{result:await H._parseAsync({data:Q.data,path:Q.path,parent:W}),ctx:W}})).then(J);else{let H=void 0,W=[];for(let B of $){let w={...Q,common:{...Q.common,issues:[]},parent:null},M=B._parseSync({data:Q.data,path:Q.path,parent:w});if(M.status==="valid")return M;else if(M.status==="dirty"&&!H)H={result:M,ctx:w};if(w.common.issues.length)W.push(w.common.issues)}if(H)return Q.common.issues.push(...H.ctx.common.issues),H.result;let G=W.map((B)=>new f(B));return V(Q,{code:A.invalid_union,unionErrors:G}),R}}get options(){return this._def.options}}L1.create=(X,Q)=>{return new L1({options:X,typeName:O.ZodUnion,..._(Q)})};var i=(X)=>{if(X instanceof O1)return i(X.schema);else if(X instanceof T)return i(X.innerType());else if(X instanceof R1)return[X.value];else if(X instanceof t)return X.options;else if(X instanceof E1)return v.objectValues(X.enum);else if(X instanceof N1)return i(X._def.innerType);else if(X instanceof q1)return[void 0];else if(X instanceof U1)return[null];else if(X instanceof h)return[void 0,...i(X.unwrap())];else if(X instanceof r)return[null,...i(X.unwrap())];else if(X instanceof p1)return i(X.unwrap());else if(X instanceof F1)return i(X.unwrap());else if(X instanceof _1)return i(X._def.innerType);else return[]};class u1 extends F{_parse(X){let{ctx:Q}=this._processInputParams(X);if(Q.parsedType!==z.object)return V(Q,{code:A.invalid_type,expected:z.object,received:Q.parsedType}),R;let $=this.discriminator,J=Q.data[$],H=this.optionsMap.get(J);if(!H)return V(Q,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),R;if(Q.common.async)return H._parseAsync({data:Q.data,path:Q.path,parent:Q});else return H._parseSync({data:Q.data,path:Q.path,parent:Q})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(X,Q,$){let J=new Map;for(let H of Q){let W=i(H.shape[X]);if(!W.length)throw new Error(`A discriminator value for key \`${X}\` could not be extracted from all schema options`);for(let G of W){if(J.has(G))throw new Error(`Discriminator property ${String(X)} has duplicate value ${String(G)}`);J.set(G,H)}}return new u1({typeName:O.ZodDiscriminatedUnion,discriminator:X,options:Q,optionsMap:J,..._($)})}}function A0(X,Q){let $=d(X),J=d(Q);if(X===Q)return{valid:!0,data:X};else if($===z.object&&J===z.object){let H=v.objectKeys(Q),W=v.objectKeys(X).filter((B)=>H.indexOf(B)!==-1),G={...X,...Q};for(let B of W){let w=A0(X[B],Q[B]);if(!w.valid)return{valid:!1};G[B]=w.data}return{valid:!0,data:G}}else if($===z.array&&J===z.array){if(X.length!==Q.length)return{valid:!1};let H=[];for(let W=0;W<X.length;W++){let G=X[W],B=Q[W],w=A0(G,B);if(!w.valid)return{valid:!1};H.push(w.data)}return{valid:!0,data:H}}else if($===z.date&&J===z.date&&+X===+Q)return{valid:!0,data:X};else return{valid:!1}}class K1 extends F{_parse(X){let{status:Q,ctx:$}=this._processInputParams(X),J=(H,W)=>{if(w0(H)||w0(W))return R;let G=A0(H.value,W.value);if(!G.valid)return V($,{code:A.invalid_intersection_types}),R;if(M0(H)||M0(W))Q.dirty();return{status:Q.value,value:G.data}};if($.common.async)return Promise.all([this._def.left._parseAsync({data:$.data,path:$.path,parent:$}),this._def.right._parseAsync({data:$.data,path:$.path,parent:$})]).then(([H,W])=>J(H,W));else return J(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}K1.create=(X,Q,$)=>{return new K1({left:X,right:Q,typeName:O.ZodIntersection,..._($)})};class c extends F{_parse(X){let{status:Q,ctx:$}=this._processInputParams(X);if($.parsedType!==z.array)return V($,{code:A.invalid_type,expected:z.array,received:$.parsedType}),R;if($.data.length<this._def.items.length)return V($,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;if(!this._def.rest&&$.data.length>this._def.items.length)V($,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q.dirty();let H=[...$.data].map((W,G)=>{let B=this._def.items[G]||this._def.rest;if(!B)return null;return B._parse(new Z($,W,$.path,G))}).filter((W)=>!!W);if($.common.async)return Promise.all(H).then((W)=>{return b.mergeArray(Q,W)});else return b.mergeArray(Q,H)}get items(){return this._def.items}rest(X){return new c({...this._def,rest:X})}}c.create=(X,Q)=>{if(!Array.isArray(X))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new c({items:X,typeName:O.ZodTuple,rest:null,..._(Q)})};class P1 extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(X){let{status:Q,ctx:$}=this._processInputParams(X);if($.parsedType!==z.object)return V($,{code:A.invalid_type,expected:z.object,received:$.parsedType}),R;let J=[],H=this._def.keyType,W=this._def.valueType;for(let G in $.data)J.push({key:H._parse(new Z($,G,$.path,G)),value:W._parse(new Z($,$.data[G],$.path,G)),alwaysSet:G in $.data});if($.common.async)return b.mergeObjectAsync(Q,J);else return b.mergeObjectSync(Q,J)}get element(){return this._def.valueType}static create(X,Q,$){if(Q instanceof F)return new P1({keyType:X,valueType:Q,typeName:O.ZodRecord,..._($)});return new P1({keyType:g.create(),valueType:X,typeName:O.ZodRecord,..._(Q)})}}class k1 extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(X){let{status:Q,ctx:$}=this._processInputParams(X);if($.parsedType!==z.map)return V($,{code:A.invalid_type,expected:z.map,received:$.parsedType}),R;let J=this._def.keyType,H=this._def.valueType,W=[...$.data.entries()].map(([G,B],w)=>{return{key:J._parse(new Z($,G,$.path,[w,"key"])),value:H._parse(new Z($,B,$.path,[w,"value"]))}});if($.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let B of W){let w=await B.key,M=await B.value;if(w.status==="aborted"||M.status==="aborted")return R;if(w.status==="dirty"||M.status==="dirty")Q.dirty();G.set(w.value,M.value)}return{status:Q.value,value:G}})}else{let G=new Map;for(let B of W){let{key:w,value:M}=B;if(w.status==="aborted"||M.status==="aborted")return R;if(w.status==="dirty"||M.status==="dirty")Q.dirty();G.set(w.value,M.value)}return{status:Q.value,value:G}}}}k1.create=(X,Q,$)=>{return new k1({valueType:Q,keyType:X,typeName:O.ZodMap,..._($)})};class Y1 extends F{_parse(X){let{status:Q,ctx:$}=this._processInputParams(X);if($.parsedType!==z.set)return V($,{code:A.invalid_type,expected:z.set,received:$.parsedType}),R;let J=this._def;if(J.minSize!==null){if($.data.size<J.minSize.value)V($,{code:A.too_small,minimum:J.minSize.value,type:"set",inclusive:!0,exact:!1,message:J.minSize.message}),Q.dirty()}if(J.maxSize!==null){if($.data.size>J.maxSize.value)V($,{code:A.too_big,maximum:J.maxSize.value,type:"set",inclusive:!0,exact:!1,message:J.maxSize.message}),Q.dirty()}let H=this._def.valueType;function W(B){let w=new Set;for(let M of B){if(M.status==="aborted")return R;if(M.status==="dirty")Q.dirty();w.add(M.value)}return{status:Q.value,value:w}}let G=[...$.data.values()].map((B,w)=>H._parse(new Z($,B,$.path,w)));if($.common.async)return Promise.all(G).then((B)=>W(B));else return W(G)}min(X,Q){return new Y1({...this._def,minSize:{value:X,message:L.toString(Q)}})}max(X,Q){return new Y1({...this._def,maxSize:{value:X,message:L.toString(Q)}})}size(X,Q){return this.min(X,Q).max(X,Q)}nonempty(X){return this.min(1,X)}}Y1.create=(X,Q)=>{return new Y1({valueType:X,minSize:null,maxSize:null,typeName:O.ZodSet,..._(Q)})};class A1 extends F{constructor(){super(...arguments);this.validate=this.implement}_parse(X){let{ctx:Q}=this._processInputParams(X);if(Q.parsedType!==z.function)return V(Q,{code:A.invalid_type,expected:z.function,received:Q.parsedType}),R;function $(G,B){return m1({data:G,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,l1(),V1].filter((w)=>!!w),issueData:{code:A.invalid_arguments,argumentsError:B}})}function J(G,B){return m1({data:G,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,l1(),V1].filter((w)=>!!w),issueData:{code:A.invalid_return_type,returnTypeError:B}})}let H={errorMap:Q.common.contextualErrorMap},W=Q.data;if(this._def.returns instanceof W1){let G=this;return P(async function(...B){let w=new f([]),M=await G._def.args.parseAsync(B,H).catch((N)=>{throw w.addIssue($(B,N)),w}),q=await Reflect.apply(W,this,M);return await G._def.returns._def.type.parseAsync(q,H).catch((N)=>{throw w.addIssue(J(q,N)),w})})}else{let G=this;return P(function(...B){let w=G._def.args.safeParse(B,H);if(!w.success)throw new f([$(B,w.error)]);let M=Reflect.apply(W,this,w.data),q=G._def.returns.safeParse(M,H);if(!q.success)throw new f([J(M,q.error)]);return q.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...X){return new A1({...this._def,args:c.create(X).rest(a.create())})}returns(X){return new A1({...this._def,returns:X})}implement(X){return this.parse(X)}strictImplement(X){return this.parse(X)}static create(X,Q,$){return new A1({args:X?X:c.create([]).rest(a.create()),returns:Q||a.create(),typeName:O.ZodFunction,..._($)})}}class O1 extends F{get schema(){return this._def.getter()}_parse(X){let{ctx:Q}=this._processInputParams(X);return this._def.getter()._parse({data:Q.data,path:Q.path,parent:Q})}}O1.create=(X,Q)=>{return new O1({getter:X,typeName:O.ZodLazy,..._(Q)})};class R1 extends F{_parse(X){if(X.data!==this._def.value){let Q=this._getOrReturnCtx(X);return V(Q,{received:Q.data,code:A.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:X.data}}get value(){return this._def.value}}R1.create=(X,Q)=>{return new R1({value:X,typeName:O.ZodLiteral,..._(Q)})};function p0(X,Q){return new t({values:X,typeName:O.ZodEnum,..._(Q)})}class t extends F{constructor(){super(...arguments);j1.set(this,void 0)}_parse(X){if(typeof X.data!=="string"){let Q=this._getOrReturnCtx(X),$=this._def.values;return V(Q,{expected:v.joinValues($),received:Q.parsedType,code:A.invalid_type}),R}if(!c1(this,j1,"f"))l0(this,j1,new Set(this._def.values),"f");if(!c1(this,j1,"f").has(X.data)){let Q=this._getOrReturnCtx(X),$=this._def.values;return V(Q,{received:Q.data,code:A.invalid_enum_value,options:$}),R}return P(X.data)}get options(){return this._def.values}get enum(){let X={};for(let Q of this._def.values)X[Q]=Q;return X}get Values(){let X={};for(let Q of this._def.values)X[Q]=Q;return X}get Enum(){let X={};for(let Q of this._def.values)X[Q]=Q;return X}extract(X,Q=this._def){return t.create(X,{...this._def,...Q})}exclude(X,Q=this._def){return t.create(this.options.filter(($)=>!X.includes($)),{...this._def,...Q})}}j1=new WeakMap;t.create=p0;class E1 extends F{constructor(){super(...arguments);v1.set(this,void 0)}_parse(X){let Q=v.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(X);if($.parsedType!==z.string&&$.parsedType!==z.number){let J=v.objectValues(Q);return V($,{expected:v.joinValues(J),received:$.parsedType,code:A.invalid_type}),R}if(!c1(this,v1,"f"))l0(this,v1,new Set(v.getValidEnumValues(this._def.values)),"f");if(!c1(this,v1,"f").has(X.data)){let J=v.objectValues(Q);return V($,{received:$.data,code:A.invalid_enum_value,options:J}),R}return P(X.data)}get enum(){return this._def.values}}v1=new WeakMap;E1.create=(X,Q)=>{return new E1({values:X,typeName:O.ZodNativeEnum,..._(Q)})};class W1 extends F{unwrap(){return this._def.type}_parse(X){let{ctx:Q}=this._processInputParams(X);if(Q.parsedType!==z.promise&&Q.common.async===!1)return V(Q,{code:A.invalid_type,expected:z.promise,received:Q.parsedType}),R;let $=Q.parsedType===z.promise?Q.data:Promise.resolve(Q.data);return P($.then((J)=>{return this._def.type.parseAsync(J,{path:Q.path,errorMap:Q.common.contextualErrorMap})}))}}W1.create=(X,Q)=>{return new W1({type:X,typeName:O.ZodPromise,..._(Q)})};class T extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(X){let{status:Q,ctx:$}=this._processInputParams(X),J=this._def.effect||null,H={addIssue:(W)=>{if(V($,W),W.fatal)Q.abort();else Q.dirty()},get path(){return $.path}};if(H.addIssue=H.addIssue.bind(H),J.type==="preprocess"){let W=J.transform($.data,H);if($.common.async)return Promise.resolve(W).then(async(G)=>{if(Q.value==="aborted")return R;let B=await this._def.schema._parseAsync({data:G,path:$.path,parent:$});if(B.status==="aborted")return R;if(B.status==="dirty")return M1(B.value);if(Q.value==="dirty")return M1(B.value);return B});else{if(Q.value==="aborted")return R;let G=this._def.schema._parseSync({data:W,path:$.path,parent:$});if(G.status==="aborted")return R;if(G.status==="dirty")return M1(G.value);if(Q.value==="dirty")return M1(G.value);return G}}if(J.type==="refinement"){let W=(G)=>{let B=J.refinement(G,H);if($.common.async)return Promise.resolve(B);if(B instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if($.common.async===!1){let G=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(G.status==="aborted")return R;if(G.status==="dirty")Q.dirty();return W(G.value),{status:Q.value,value:G.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((G)=>{if(G.status==="aborted")return R;if(G.status==="dirty")Q.dirty();return W(G.value).then(()=>{return{status:Q.value,value:G.value}})})}if(J.type==="transform")if($.common.async===!1){let W=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!$1(W))return W;let G=J.transform(W.value,H);if(G instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:Q.value,value:G}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((W)=>{if(!$1(W))return W;return Promise.resolve(J.transform(W.value,H)).then((G)=>({status:Q.value,value:G}))});v.assertNever(J)}}T.create=(X,Q,$)=>{return new T({schema:X,typeName:O.ZodEffects,effect:Q,..._($)})};T.createWithPreprocess=(X,Q,$)=>{return new T({schema:Q,effect:{type:"preprocess",transform:X},typeName:O.ZodEffects,..._($)})};class h extends F{_parse(X){if(this._getType(X)===z.undefined)return P(void 0);return this._def.innerType._parse(X)}unwrap(){return this._def.innerType}}h.create=(X,Q)=>{return new h({innerType:X,typeName:O.ZodOptional,..._(Q)})};class r extends F{_parse(X){if(this._getType(X)===z.null)return P(null);return this._def.innerType._parse(X)}unwrap(){return this._def.innerType}}r.create=(X,Q)=>{return new r({innerType:X,typeName:O.ZodNullable,..._(Q)})};class N1 extends F{_parse(X){let{ctx:Q}=this._processInputParams(X),$=Q.data;if(Q.parsedType===z.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:Q.path,parent:Q})}removeDefault(){return this._def.innerType}}N1.create=(X,Q)=>{return new N1({innerType:X,typeName:O.ZodDefault,defaultValue:typeof Q.default==="function"?Q.default:()=>Q.default,..._(Q)})};class _1 extends F{_parse(X){let{ctx:Q}=this._processInputParams(X),$={...Q,common:{...Q.common,issues:[]}},J=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(S1(J))return J.then((H)=>{return{status:"valid",value:H.status==="valid"?H.value:this._def.catchValue({get error(){return new f($.common.issues)},input:$.data})}});else return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new f($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}_1.create=(X,Q)=>{return new _1({innerType:X,typeName:O.ZodCatch,catchValue:typeof Q.catch==="function"?Q.catch:()=>Q.catch,..._(Q)})};class f1 extends F{_parse(X){if(this._getType(X)!==z.nan){let $=this._getOrReturnCtx(X);return V($,{code:A.invalid_type,expected:z.nan,received:$.parsedType}),R}return{status:"valid",value:X.data}}}f1.create=(X)=>{return new f1({typeName:O.ZodNaN,..._(X)})};var p9=Symbol("zod_brand");class p1 extends F{_parse(X){let{ctx:Q}=this._processInputParams(X),$=Q.data;return this._def.type._parse({data:$,path:Q.path,parent:Q})}unwrap(){return this._def.type}}class I1 extends F{_parse(X){let{status:Q,ctx:$}=this._processInputParams(X);if($.common.async)return(async()=>{let H=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(H.status==="aborted")return R;if(H.status==="dirty")return Q.dirty(),M1(H.value);else return this._def.out._parseAsync({data:H.value,path:$.path,parent:$})})();else{let J=this._def.in._parseSync({data:$.data,path:$.path,parent:$});if(J.status==="aborted")return R;if(J.status==="dirty")return Q.dirty(),{status:"dirty",value:J.value};else return this._def.out._parseSync({data:J.value,path:$.path,parent:$})}}static create(X,Q){return new I1({in:X,out:Q,typeName:O.ZodPipeline})}}class F1 extends F{_parse(X){let Q=this._def.innerType._parse(X),$=(J)=>{if($1(J))J.value=Object.freeze(J.value);return J};return S1(Q)?Q.then((J)=>$(J)):$(Q)}unwrap(){return this._def.innerType}}F1.create=(X,Q)=>{return new F1({innerType:X,typeName:O.ZodReadonly,..._(Q)})};function h0(X,Q){let $=typeof X==="function"?X(Q):typeof X==="string"?{message:X}:X;return typeof $==="string"?{message:$}:$}function n0(X,Q={},$){if(X)return H1.create().superRefine((J,H)=>{var W,G;let B=X(J);if(B instanceof Promise)return B.then((w)=>{var M,q;if(!w){let U=h0(Q,J),N=(q=(M=U.fatal)!==null&&M!==void 0?M:$)!==null&&q!==void 0?q:!0;H.addIssue({code:"custom",...U,fatal:N})}});if(!B){let w=h0(Q,J),M=(G=(W=w.fatal)!==null&&W!==void 0?W:$)!==null&&G!==void 0?G:!0;H.addIssue({code:"custom",...w,fatal:M})}return});return H1.create()}var n9={object:S.lazycreate},O;(function(X){X.ZodString="ZodString",X.ZodNumber="ZodNumber",X.ZodNaN="ZodNaN",X.ZodBigInt="ZodBigInt",X.ZodBoolean="ZodBoolean",X.ZodDate="ZodDate",X.ZodSymbol="ZodSymbol",X.ZodUndefined="ZodUndefined",X.ZodNull="ZodNull",X.ZodAny="ZodAny",X.ZodUnknown="ZodUnknown",X.ZodNever="ZodNever",X.ZodVoid="ZodVoid",X.ZodArray="ZodArray",X.ZodObject="ZodObject",X.ZodUnion="ZodUnion",X.ZodDiscriminatedUnion="ZodDiscriminatedUnion",X.ZodIntersection="ZodIntersection",X.ZodTuple="ZodTuple",X.ZodRecord="ZodRecord",X.ZodMap="ZodMap",X.ZodSet="ZodSet",X.ZodFunction="ZodFunction",X.ZodLazy="ZodLazy",X.ZodLiteral="ZodLiteral",X.ZodEnum="ZodEnum",X.ZodEffects="ZodEffects",X.ZodNativeEnum="ZodNativeEnum",X.ZodOptional="ZodOptional",X.ZodNullable="ZodNullable",X.ZodDefault="ZodDefault",X.ZodCatch="ZodCatch",X.ZodPromise="ZodPromise",X.ZodBranded="ZodBranded",X.ZodPipeline="ZodPipeline",X.ZodReadonly="ZodReadonly"})(O||(O={}));var i9=(X,Q={message:`Input not instance of ${X.name}`})=>n0(($)=>$ instanceof X,Q),i0=g.create,d0=o.create,d9=f1.create,r9=s.create,r0=z1.create,a9=J1.create,o9=C1.create,s9=q1.create,t9=U1.create,e9=H1.create,X2=a.create,Q2=m.create,$2=b1.create,J2=x.create,k=S.create,H2=S.strictCreate,Y2=L1.create,W2=u1.create,G2=K1.create,B2=c.create,w2=P1.create,M2=k1.create,A2=Y1.create,V2=A1.create,z2=O1.create,q2=R1.create,U2=t.create,L2=E1.create,K2=W1.create,Z0=T.create,O2=h.create,R2=r.create,E2=T.createWithPreprocess,N2=I1.create,_2=()=>i0().optional(),F2=()=>d0().optional(),D2=()=>r0().optional(),j2={string:(X)=>g.create({...X,coerce:!0}),number:(X)=>o.create({...X,coerce:!0}),boolean:(X)=>z1.create({...X,coerce:!0}),bigint:(X)=>s.create({...X,coerce:!0}),date:(X)=>J1.create({...X,coerce:!0})},v2=R,Y=Object.freeze({__proto__:null,defaultErrorMap:V1,setErrorMap:N9,getErrorMap:l1,makeIssue:m1,EMPTY_PATH:_9,addIssueToContext:V,ParseStatus:b,INVALID:R,DIRTY:M1,OK:P,isAborted:w0,isDirty:M0,isValid:$1,isAsync:S1,get util(){return v},get objectUtil(){return B0},ZodParsedType:z,getParsedType:d,ZodType:F,datetimeRegex:u0,ZodString:g,ZodNumber:o,ZodBigInt:s,ZodBoolean:z1,ZodDate:J1,ZodSymbol:C1,ZodUndefined:q1,ZodNull:U1,ZodAny:H1,ZodUnknown:a,ZodNever:m,ZodVoid:b1,ZodArray:x,ZodObject:S,ZodUnion:L1,ZodDiscriminatedUnion:u1,ZodIntersection:K1,ZodTuple:c,ZodRecord:P1,ZodMap:k1,ZodSet:Y1,ZodFunction:A1,ZodLazy:O1,ZodLiteral:R1,ZodEnum:t,ZodNativeEnum:E1,ZodPromise:W1,ZodEffects:T,ZodTransformer:T,ZodOptional:h,ZodNullable:r,ZodDefault:N1,ZodCatch:_1,ZodNaN:f1,BRAND:p9,ZodBranded:p1,ZodPipeline:I1,ZodReadonly:F1,custom:n0,Schema:F,ZodSchema:F,late:n9,get ZodFirstPartyTypeKind(){return O},coerce:j2,any:e9,array:J2,bigint:r9,boolean:r0,date:a9,discriminatedUnion:W2,effect:Z0,enum:U2,function:V2,instanceof:i9,intersection:G2,lazy:z2,literal:q2,map:M2,nan:d9,nativeEnum:L2,never:Q2,null:t9,nullable:R2,number:d0,object:k,oboolean:D2,onumber:F2,optional:O2,ostring:_2,pipeline:N2,preprocess:E2,promise:K2,record:w2,set:A2,strictObject:H2,string:i0,symbol:o9,transformer:Z0,tuple:B2,undefined:s9,union:Y2,unknown:X2,void:$2,NEVER:v2,ZodIssueCode:A,quotelessJson:E9,ZodError:f});var V0="2024-11-05",a0=[V0,"2024-10-07"],n1="2.0",o0=Y.union([Y.string(),Y.number().int()]),s0=Y.string(),y=Y.object({_meta:Y.optional(Y.object({progressToken:Y.optional(o0)}).passthrough())}).passthrough(),I=Y.object({method:Y.string(),params:Y.optional(y)}),T1=Y.object({_meta:Y.optional(Y.object({}).passthrough())}).passthrough(),u=Y.object({method:Y.string(),params:Y.optional(T1)}),l=Y.object({_meta:Y.optional(Y.object({}).passthrough())}).passthrough(),i1=Y.union([Y.string(),Y.number().int()]),S2=Y.object({jsonrpc:Y.literal(n1),id:i1}).merge(I).strict(),C2=Y.object({jsonrpc:Y.literal(n1)}).merge(u).strict(),b2=Y.object({jsonrpc:Y.literal(n1),id:i1,result:l}).strict(),G1;(function(X){X[X.ConnectionClosed=-32000]="ConnectionClosed",X[X.RequestTimeout=-32001]="RequestTimeout",X[X.ParseError=-32700]="ParseError",X[X.InvalidRequest=-32600]="InvalidRequest",X[X.MethodNotFound=-32601]="MethodNotFound",X[X.InvalidParams=-32602]="InvalidParams",X[X.InternalError=-32603]="InternalError"})(G1||(G1={}));var P2=Y.object({jsonrpc:Y.literal(n1),id:i1,error:Y.object({code:Y.number().int(),message:Y.string(),data:Y.optional(Y.unknown())})}).strict(),t0=Y.union([S2,C2,b2,P2]),d1=l.strict(),r1=u.extend({method:Y.literal("notifications/cancelled"),params:T1.extend({requestId:i1,reason:Y.string().optional()})}),e0=Y.object({name:Y.string(),version:Y.string()}).passthrough(),k2=Y.object({experimental:Y.optional(Y.object({}).passthrough()),sampling:Y.optional(Y.object({}).passthrough()),roots:Y.optional(Y.object({listChanged:Y.optional(Y.boolean())}).passthrough())}).passthrough(),z0=I.extend({method:Y.literal("initialize"),params:y.extend({protocolVersion:Y.string(),capabilities:k2,clientInfo:e0})}),f2=Y.object({experimental:Y.optional(Y.object({}).passthrough()),logging:Y.optional(Y.object({}).passthrough()),prompts:Y.optional(Y.object({listChanged:Y.optional(Y.boolean())}).passthrough()),resources:Y.optional(Y.object({subscribe:Y.optional(Y.boolean()),listChanged:Y.optional(Y.boolean())}).passthrough()),tools:Y.optional(Y.object({listChanged:Y.optional(Y.boolean())}).passthrough())}).passthrough(),I2=l.extend({protocolVersion:Y.string(),capabilities:f2,serverInfo:e0,instructions:Y.optional(Y.string())}),q0=u.extend({method:Y.literal("notifications/initialized")}),a1=I.extend({method:Y.literal("ping")}),T2=Y.object({progress:Y.number(),total:Y.optional(Y.number())}).passthrough(),o1=u.extend({method:Y.literal("notifications/progress"),params:T1.merge(T2).extend({progressToken:o0})}),s1=I.extend({params:y.extend({cursor:Y.optional(s0)}).optional()}),t1=l.extend({nextCursor:Y.optional(s0)}),X9=Y.object({uri:Y.string(),mimeType:Y.optional(Y.string())}).passthrough(),Q9=X9.extend({text:Y.string()}),$9=X9.extend({blob:Y.string().base64()}),g2=Y.object({uri:Y.string(),name:Y.string(),description:Y.optional(Y.string()),mimeType:Y.optional(Y.string())}).passthrough(),x2=Y.object({uriTemplate:Y.string(),name:Y.string(),description:Y.optional(Y.string()),mimeType:Y.optional(Y.string())}).passthrough(),h2=s1.extend({method:Y.literal("resources/list")}),Z2=t1.extend({resources:Y.array(g2)}),y2=s1.extend({method:Y.literal("resources/templates/list")}),l2=t1.extend({resourceTemplates:Y.array(x2)}),m2=I.extend({method:Y.literal("resources/read"),params:y.extend({uri:Y.string()})}),c2=l.extend({contents:Y.array(Y.union([Q9,$9]))}),u2=u.extend({method:Y.literal("notifications/resources/list_changed")}),p2=I.extend({method:Y.literal("resources/subscribe"),params:y.extend({uri:Y.string()})}),n2=I.extend({method:Y.literal("resources/unsubscribe"),params:y.extend({uri:Y.string()})}),i2=u.extend({method:Y.literal("notifications/resources/updated"),params:T1.extend({uri:Y.string()})}),d2=Y.object({name:Y.string(),description:Y.optional(Y.string()),required:Y.optional(Y.boolean())}).passthrough(),r2=Y.object({name:Y.string(),description:Y.optional(Y.string()),arguments:Y.optional(Y.array(d2))}).passthrough(),a2=s1.extend({method:Y.literal("prompts/list")}),o2=t1.extend({prompts:Y.array(r2)}),s2=I.extend({method:Y.literal("prompts/get"),params:y.extend({name:Y.string(),arguments:Y.optional(Y.record(Y.string()))})}),e1=Y.object({type:Y.literal("text"),text:Y.string()}).passthrough(),X0=Y.object({type:Y.literal("image"),data:Y.string().base64(),mimeType:Y.string()}).passthrough(),J9=Y.object({type:Y.literal("resource"),resource:Y.union([Q9,$9])}).passthrough(),t2=Y.object({role:Y.enum(["user","assistant"]),content:Y.union([e1,X0,J9])}).passthrough(),e2=l.extend({description:Y.optional(Y.string()),messages:Y.array(t2)}),X4=u.extend({method:Y.literal("notifications/prompts/list_changed")}),Q4=Y.object({name:Y.string(),description:Y.optional(Y.string()),inputSchema:Y.object({type:Y.literal("object"),properties:Y.optional(Y.object({}).passthrough())}).passthrough()}).passthrough(),U0=s1.extend({method:Y.literal("tools/list")}),$4=t1.extend({tools:Y.array(Q4)}),H9=l.extend({content:Y.array(Y.union([e1,X0,J9])),isError:Y.boolean().default(!1).optional()}),e4=H9.or(l.extend({toolResult:Y.unknown()})),L0=I.extend({method:Y.literal("tools/call"),params:y.extend({name:Y.string(),arguments:Y.optional(Y.record(Y.unknown()))})}),J4=u.extend({method:Y.literal("notifications/tools/list_changed")}),Y9=Y.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),H4=I.extend({method:Y.literal("logging/setLevel"),params:y.extend({level:Y9})}),Y4=u.extend({method:Y.literal("notifications/message"),params:T1.extend({level:Y9,logger:Y.optional(Y.string()),data:Y.unknown()})}),W4=Y.object({name:Y.string().optional()}).passthrough(),G4=Y.object({hints:Y.optional(Y.array(W4)),costPriority:Y.optional(Y.number().min(0).max(1)),speedPriority:Y.optional(Y.number().min(0).max(1)),intelligencePriority:Y.optional(Y.number().min(0).max(1))}).passthrough(),B4=Y.object({role:Y.enum(["user","assistant"]),content:Y.union([e1,X0])}).passthrough(),w4=I.extend({method:Y.literal("sampling/createMessage"),params:y.extend({messages:Y.array(B4),systemPrompt:Y.optional(Y.string()),includeContext:Y.optional(Y.enum(["none","thisServer","allServers"])),temperature:Y.optional(Y.number()),maxTokens:Y.number().int(),stopSequences:Y.optional(Y.array(Y.string())),metadata:Y.optional(Y.object({}).passthrough()),modelPreferences:Y.optional(G4)})}),K0=l.extend({model:Y.string(),stopReason:Y.optional(Y.enum(["endTurn","stopSequence","maxTokens"]).or(Y.string())),role:Y.enum(["user","assistant"]),content:Y.discriminatedUnion("type",[e1,X0])}),M4=Y.object({type:Y.literal("ref/resource"),uri:Y.string()}).passthrough(),A4=Y.object({type:Y.literal("ref/prompt"),name:Y.string()}).passthrough(),V4=I.extend({method:Y.literal("completion/complete"),params:y.extend({ref:Y.union([A4,M4]),argument:Y.object({name:Y.string(),value:Y.string()}).passthrough()})}),z4=l.extend({completion:Y.object({values:Y.array(Y.string()).max(100),total:Y.optional(Y.number().int()),hasMore:Y.optional(Y.boolean())}).passthrough()}),q4=Y.object({uri:Y.string().startsWith("file://"),name:Y.optional(Y.string())}).passthrough(),U4=I.extend({method:Y.literal("roots/list")}),O0=l.extend({roots:Y.array(q4)}),L4=u.extend({method:Y.literal("notifications/roots/list_changed")}),X7=Y.union([a1,z0,V4,H4,s2,a2,h2,y2,m2,p2,n2,L0,U0]),Q7=Y.union([r1,o1,q0,L4]),$7=Y.union([d1,K0,O0]),J7=Y.union([a1,w4,U4]),H7=Y.union([r1,o1,Y4,i2,u2,J4,X4]),Y7=Y.union([d1,I2,z4,e2,o2,Z2,l2,c2,H9,$4]);class g1 extends Error{constructor(X,Q,$){super(`MCP error ${X}: ${Q}`);this.code=X,this.data=$}}var K4=60000;class R0{constructor(X){this._options=X,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this.setNotificationHandler(r1,(Q)=>{let $=this._requestHandlerAbortControllers.get(Q.params.requestId);$===null||$===void 0||$.abort(Q.params.reason)}),this.setNotificationHandler(o1,(Q)=>{this._onprogress(Q)}),this.setRequestHandler(a1,(Q)=>({}))}async connect(X){this._transport=X,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=(Q)=>{this._onerror(Q)},this._transport.onmessage=(Q)=>{if(!("method"in Q))this._onresponse(Q);else if("id"in Q)this._onrequest(Q);else this._onnotification(Q)},await this._transport.start()}_onclose(){var X;let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(X=this.onclose)===null||X===void 0||X.call(this);let $=new g1(G1.ConnectionClosed,"Connection closed");for(let J of Q.values())J($)}_onerror(X){var Q;(Q=this.onerror)===null||Q===void 0||Q.call(this,X)}_onnotification(X){var Q;let $=(Q=this._notificationHandlers.get(X.method))!==null&&Q!==void 0?Q:this.fallbackNotificationHandler;if($===void 0)return;Promise.resolve().then(()=>$(X)).catch((J)=>this._onerror(new Error(`Uncaught error in notification handler: ${J}`)))}_onrequest(X){var Q,$;let J=(Q=this._requestHandlers.get(X.method))!==null&&Q!==void 0?Q:this.fallbackRequestHandler;if(J===void 0){($=this._transport)===null||$===void 0||$.send({jsonrpc:"2.0",id:X.id,error:{code:G1.MethodNotFound,message:"Method not found"}}).catch((W)=>this._onerror(new Error(`Failed to send an error response: ${W}`)));return}let H=new AbortController;this._requestHandlerAbortControllers.set(X.id,H),Promise.resolve().then(()=>J(X,{signal:H.signal})).then((W)=>{var G;if(H.signal.aborted)return;return(G=this._transport)===null||G===void 0?void 0:G.send({result:W,jsonrpc:"2.0",id:X.id})},(W)=>{var G,B;if(H.signal.aborted)return;return(G=this._transport)===null||G===void 0?void 0:G.send({jsonrpc:"2.0",id:X.id,error:{code:Number.isSafeInteger(W.code)?W.code:G1.InternalError,message:(B=W.message)!==null&&B!==void 0?B:"Internal error"}})}).catch((W)=>this._onerror(new Error(`Failed to send response: ${W}`))).finally(()=>{this._requestHandlerAbortControllers.delete(X.id)})}_onprogress(X){let{progressToken:Q,...$}=X.params,J=this._progressHandlers.get(Number(Q));if(J===void 0){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(X)}`));return}J($)}_onresponse(X){let Q=X.id,$=this._responseHandlers.get(Number(Q));if($===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(X)}`));return}if(this._responseHandlers.delete(Number(Q)),this._progressHandlers.delete(Number(Q)),"result"in X)$(X);else{let J=new g1(X.error.code,X.error.message,X.error.data);$(J)}}get transport(){return this._transport}async close(){var X;await((X=this._transport)===null||X===void 0?void 0:X.close())}request(X,Q,$){return new Promise((J,H)=>{var W,G,B,w;if(!this._transport){H(new Error("Not connected"));return}if(((W=this._options)===null||W===void 0?void 0:W.enforceStrictCapabilities)===!0)this.assertCapabilityForMethod(X.method);(G=$===null||$===void 0?void 0:$.signal)===null||G===void 0||G.throwIfAborted();let M=this._requestMessageId++,q={...X,jsonrpc:"2.0",id:M};if($===null||$===void 0?void 0:$.onprogress)this._progressHandlers.set(M,$.onprogress),q.params={...X.params,_meta:{progressToken:M}};let U=void 0;this._responseHandlers.set(M,(E)=>{var j;if(U!==void 0)clearTimeout(U);if((j=$===null||$===void 0?void 0:$.signal)===null||j===void 0?void 0:j.aborted)return;if(E instanceof Error)return H(E);try{let C=Q.parse(E.result);J(C)}catch(C){H(C)}});let N=(E)=>{var j;this._responseHandlers.delete(M),this._progressHandlers.delete(M),(j=this._transport)===null||j===void 0||j.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:M,reason:String(E)}}).catch((C)=>this._onerror(new Error(`Failed to send cancellation: ${C}`))),H(E)};(B=$===null||$===void 0?void 0:$.signal)===null||B===void 0||B.addEventListener("abort",()=>{var E;if(U!==void 0)clearTimeout(U);N((E=$===null||$===void 0?void 0:$.signal)===null||E===void 0?void 0:E.reason)});let D=(w=$===null||$===void 0?void 0:$.timeout)!==null&&w!==void 0?w:K4;U=setTimeout(()=>N(new g1(G1.RequestTimeout,"Request timed out",{timeout:D})),D),this._transport.send(q).catch((E)=>{if(U!==void 0)clearTimeout(U);H(E)})})}async notification(X){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(X.method);let Q={...X,jsonrpc:"2.0"};await this._transport.send(Q)}setRequestHandler(X,Q){let $=X.shape.method.value;this.assertRequestHandlerCapability($),this._requestHandlers.set($,(J,H)=>Promise.resolve(Q(X.parse(J),H)))}removeRequestHandler(X){this._requestHandlers.delete(X)}assertCanSetRequestHandler(X){if(this._requestHandlers.has(X))throw new Error(`A request handler for ${X} already exists, which would be overridden`)}setNotificationHandler(X,Q){this._notificationHandlers.set(X.shape.method.value,($)=>Promise.resolve(Q(X.parse($))))}removeNotificationHandler(X){this._notificationHandlers.delete(X)}}function W9(X,Q){return Object.entries(Q).reduce(($,[J,H])=>{if(H&&typeof H==="object")$[J]=$[J]?{...$[J],...H}:H;else $[J]=H;return $},{...X})}class E0 extends R0{constructor(X,Q){var $;super(Q);this._serverInfo=X,this._capabilities=($=Q===null||Q===void 0?void 0:Q.capabilities)!==null&&$!==void 0?$:{},this._instructions=Q===null||Q===void 0?void 0:Q.instructions,this.setRequestHandler(z0,(J)=>this._oninitialize(J)),this.setNotificationHandler(q0,()=>{var J;return(J=this.oninitialized)===null||J===void 0?void 0:J.call(this)})}registerCapabilities(X){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=W9(this._capabilities,X)}assertCapabilityForMethod(X){var Q,$;switch(X){case"sampling/createMessage":if(!((Q=this._clientCapabilities)===null||Q===void 0?void 0:Q.sampling))throw new Error(`Client does not support sampling (required for ${X})`);break;case"roots/list":if(!(($=this._clientCapabilities)===null||$===void 0?void 0:$.roots))throw new Error(`Client does not support listing roots (required for ${X})`);break;case"ping":break}}assertNotificationCapability(X){switch(X){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${X})`);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 ${X})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${X})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${X})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(X){switch(X){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${X})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${X})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${X})`);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 ${X})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${X})`);break;case"ping":case"initialize":break}}async _oninitialize(X){let Q=X.params.protocolVersion;return this._clientCapabilities=X.params.capabilities,this._clientVersion=X.params.clientInfo,{protocolVersion:a0.includes(Q)?Q:V0,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"},d1)}async createMessage(X,Q){return this.request({method:"sampling/createMessage",params:X},K0,Q)}async listRoots(X,Q){return this.request({method:"roots/list",params:X},O0,Q)}async sendLoggingMessage(X){return this.notification({method:"notifications/message",params:X})}async sendResourceUpdated(X){return this.notification({method:"notifications/resources/updated",params:X})}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"})}}import B9 from"node:process";class N0{append(X){this._buffer=this._buffer?Buffer.concat([this._buffer,X]):X}readMessage(){if(!this._buffer)return null;let X=this._buffer.indexOf(`
3
+ `);if(X===-1)return null;let Q=this._buffer.toString("utf8",0,X);return this._buffer=this._buffer.subarray(X+1),O4(Q)}clear(){this._buffer=void 0}}function O4(X){return t0.parse(JSON.parse(X))}function G9(X){return JSON.stringify(X)+`
4
+ `}class _0{constructor(X=B9.stdin,Q=B9.stdout){this._stdin=X,this._stdout=Q,this._readBuffer=new N0,this._started=!1,this._ondata=($)=>{this._readBuffer.append($),this.processReadBuffer()},this._onerror=($)=>{var J;(J=this.onerror)===null||J===void 0||J.call(this,$)}}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,Q;while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;(X=this.onmessage)===null||X===void 0||X.call(this,$)}catch($){(Q=this.onerror)===null||Q===void 0||Q.call(this,$)}}async close(){var X;if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),(X=this.onclose)===null||X===void 0||X.call(this)}send(X){return new Promise((Q)=>{let $=G9(X);if(this._stdout.write($))Q();else this._stdout.once("drain",Q)})}}import{join as f4}from"path";import{readFile as I4,access as T4,constants as g4}from"fs/promises";import{join as h1}from"path";import{join as E4}from"path";import{readdir as M9,readFile as N4}from"fs/promises";import Q0 from"pino";import R4 from"os";var w9=process.env.LOG_FILE_PATH||(process.env.HOME?`${process.env.HOME}/.specifai/mcp-log.log`:void 0),F0={level:process.env.LOG_LEVEL||"info",base:{version:"0.4.2",pid:process.pid,hostname:R4.hostname()}},K;if(w9)try{let X={target:"pino/file",options:{destination:w9,append:!0,sync:!1,mkdir:!0,silent:!0},worker:{autoEnd:!1}};K=Q0(F0,Q0.transport(X))}catch(X){K=Q0({...F0,enabled:!1})}else K=Q0({...F0,enabled:!1});class x1{async readAllJsonFiles(X){try{let $=(await M9(X)).filter((H)=>H.endsWith(".json"));return await Promise.all($.map(async(H)=>{let W=E4(X,H),G=await N4(W,"utf-8");try{return{name:H,content:JSON.parse(G)}}catch(B){return K.error({error:B,file:H},`Error parsing JSON file ${H}`),{name:H,content:null,error:"Invalid JSON"}}}))}catch(Q){return K.warn({error:Q},"Directory not found, returning empty array"),[]}}async isDirectory(X){try{let Q=await M9(X);return!0}catch{return!1}}}class D0{fileService;constructor(){this.fileService=new x1}normalize(X){return K.debug({count:X.length},"Normalizing documents"),X.map((Q)=>({id:Q.name.replace(".json","").replace("-base",""),title:Q.content.title,description:Q.content.requirement}))}processPRDs(X){return K.debug({count:X.length},"Processing PRD files"),X.map((Q)=>{if(!Q.name.includes("feature")){let $=X.find((H)=>H.name===Q.name.replace("base","feature"));if(!$)return K.warn({basePrd:Q.name},"No matching feature PRD found"),null;let J=$.content.features.map((H)=>({id:H.id,title:H.name,description:H.description,tasks:H.tasks.map((W)=>({id:W.id,title:W.list,description:W.acceptance}))}));return K.debug({prdId:Q.name,userStoriesCount:J.length},"Processed PRD with user stories"),{id:Q.name.replace(".json","").replace("-base",""),title:Q.content.title,description:Q.content.requirement,userStories:J}}return null}).filter((Q)=>Q!==null)}async loadSolution(X){if(K.info({projectPath:X},"Loading solution"),!await this.fileService.isDirectory(X))throw K.error({projectPath:X},"Invalid project path"),new Error(`Invalid project path: ${X}`);try{let[Q,$,J,H,W]=await Promise.all([this.fileService.readAllJsonFiles(h1(X,"BP")),this.fileService.readAllJsonFiles(h1(X,"BRD")),this.fileService.readAllJsonFiles(h1(X,"PRD")),this.fileService.readAllJsonFiles(h1(X,"NFR")),this.fileService.readAllJsonFiles(h1(X,"UIR"))]),G={BP:this.normalize(Q),BRD:this.normalize($),PRD:this.processPRDs(J),NFR:this.normalize(H),UIR:this.normalize(W)};return K.info({bpsCount:G.BP.length,brdsCount:G.BRD.length,prdsCount:G.PRD.length,nfrsCount:G.NFR.length,uirsCount:G.UIR.length},"Solution loaded successfully"),G}catch(Q){return K.warn({error:Q,projectPath:X},"Some directories not found while loading solution"),{BP:[],BRD:[],PRD:[],NFR:[],UIR:[]}}}findPRD(X,Q){let $=X.PRD.find((J)=>J.id===Q)||null;if(!$)K.debug({prdId:Q},"PRD not found");return $}findUserStory(X,Q){let $=X.userStories.find((J)=>J.id===Q)||null;if(!$)K.debug({prdId:X.id,userStoryId:Q},"User Story not found");return $}findTask(X,Q){let $=X.tasks?.find((J)=>J.id===Q)||null;if(!$)K.debug({userStoryId:X.id,taskId:Q},"Task not found");return $}}class H0{constructor(X,Q){let $=X._tree,J=Array.from($.keys());this.set=X,this._type=Q,this._path=J.length>0?[{node:$,keys:J}]:[]}next(){let X=this.dive();return this.backtrack(),X}dive(){if(this._path.length===0)return{done:!0,value:void 0};let{node:X,keys:Q}=D1(this._path);if(D1(Q)==="")return{done:!1,value:this.result()};let $=X.get(D1(Q));return this._path.push({node:$,keys:Array.from($.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;let X=D1(this._path).keys;if(X.pop(),X.length>0)return;this._path.pop(),this.backtrack()}key(){return this.set._prefix+this._path.map(({keys:X})=>D1(X)).filter((X)=>X!=="").join("")}value(){return D1(this._path).node.get("")}result(){switch(this._type){case"VALUES":return this.value();case"KEYS":return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}}var D1=(X)=>{return X[X.length-1]},_4=(X,Q,$)=>{let J=new Map;if(Q===void 0)return J;let H=Q.length+1,W=H+$,G=new Uint8Array(W*H).fill($+1);for(let B=0;B<H;++B)G[B]=B;for(let B=1;B<W;++B)G[B*H]=B;return U9(X,Q,$,J,G,1,H,""),J},U9=(X,Q,$,J,H,W,G,B)=>{let w=W*G;X:for(let M of X.keys())if(M===""){let q=H[w-1];if(q<=$)J.set(B,[X.get(M),q])}else{let q=W;for(let U=0;U<M.length;++U,++q){let N=M[U],D=G*q,E=D-G,j=H[D],C=Math.max(0,q-$-1),X1=Math.min(G-1,q+$);for(let n=C;n<X1;++n){let W0=N!==Q[n],Z1=H[E+n]+ +W0,Q1=H[E+n+1]+1,y1=H[D+n]+1,g0=H[D+n+1]=Math.min(Z1,Q1,y1);if(g0<j)j=g0}if(j>$)continue X}U9(X.get(M),Q,$,J,H,q,G,B+M)}};class e{constructor(X=new Map,Q=""){this._size=void 0,this._tree=X,this._prefix=Q}atPrefix(X){if(!X.startsWith(this._prefix))throw new Error("Mismatched prefix");let[Q,$]=Y0(this._tree,X.slice(this._prefix.length));if(Q===void 0){let[J,H]=f0($);for(let W of J.keys())if(W!==""&&W.startsWith(H)){let G=new Map;return G.set(W.slice(H.length),J.get(W)),new e(G,X)}}return new e(Q,X)}clear(){this._size=void 0,this._tree.clear()}delete(X){return this._size=void 0,F4(this._tree,X)}entries(){return new H0(this,"ENTRIES")}forEach(X){for(let[Q,$]of this)X(Q,$,this)}fuzzyGet(X,Q){return _4(this._tree,X,Q)}get(X){let Q=b0(this._tree,X);return Q!==void 0?Q.get(""):void 0}has(X){let Q=b0(this._tree,X);return Q!==void 0&&Q.has("")}keys(){return new H0(this,"KEYS")}set(X,Q){if(typeof X!=="string")throw new Error("key must be a string");return this._size=void 0,j0(this._tree,X).set("",Q),this}get size(){if(this._size)return this._size;this._size=0;let X=this.entries();while(!X.next().done)this._size+=1;return this._size}update(X,Q){if(typeof X!=="string")throw new Error("key must be a string");this._size=void 0;let $=j0(this._tree,X);return $.set("",Q($.get(""))),this}fetch(X,Q){if(typeof X!=="string")throw new Error("key must be a string");this._size=void 0;let $=j0(this._tree,X),J=$.get("");if(J===void 0)$.set("",J=Q());return J}values(){return new H0(this,"VALUES")}[Symbol.iterator](){return this.entries()}static from(X){let Q=new e;for(let[$,J]of X)Q.set($,J);return Q}static fromObject(X){return e.from(Object.entries(X))}}var Y0=(X,Q,$=[])=>{if(Q.length===0||X==null)return[X,$];for(let J of X.keys())if(J!==""&&Q.startsWith(J))return $.push([X,J]),Y0(X.get(J),Q.slice(J.length),$);return $.push([X,Q]),Y0(void 0,"",$)},b0=(X,Q)=>{if(Q.length===0||X==null)return X;for(let $ of X.keys())if($!==""&&Q.startsWith($))return b0(X.get($),Q.slice($.length))},j0=(X,Q)=>{let $=Q.length;X:for(let J=0;X&&J<$;){for(let W of X.keys())if(W!==""&&Q[J]===W[0]){let G=Math.min($-J,W.length),B=1;while(B<G&&Q[J+B]===W[B])++B;let w=X.get(W);if(B===W.length)X=w;else{let M=new Map;M.set(W.slice(B),w),X.set(Q.slice(J,J+B),M),X.delete(W),X=M}J+=B;continue X}let H=new Map;return X.set(Q.slice(J),H),H}return X},F4=(X,Q)=>{let[$,J]=Y0(X,Q);if($===void 0)return;if($.delete(""),$.size===0)L9(J);else if($.size===1){let[H,W]=$.entries().next().value;K9(J,H,W)}},L9=(X)=>{if(X.length===0)return;let[Q,$]=f0(X);if(Q.delete($),Q.size===0)L9(X.slice(0,-1));else if(Q.size===1){let[J,H]=Q.entries().next().value;if(J!=="")K9(X.slice(0,-1),J,H)}},K9=(X,Q,$)=>{if(X.length===0)return;let[J,H]=f0(X);J.set(H+Q,$),J.delete(H)},f0=(X)=>{return X[X.length-1]},I0="or",O9="and",D4="and_not";class B1{constructor(X){if((X===null||X===void 0?void 0:X.fields)==null)throw new Error('MiniSearch: option "fields" must be provided');let Q=X.autoVacuum==null||X.autoVacuum===!0?C0:X.autoVacuum;this._options={...S0,...X,autoVacuum:Q,searchOptions:{...A9,...X.searchOptions||{}},autoSuggestOptions:{...b4,...X.autoSuggestOptions||{}}},this._index=new e,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=k0,this.addFields(this._options.fields)}add(X){let{extractField:Q,tokenize:$,processTerm:J,fields:H,idField:W}=this._options,G=Q(X,W);if(G==null)throw new Error(`MiniSearch: document does not have ID field "${W}"`);if(this._idToShortId.has(G))throw new Error(`MiniSearch: duplicate ID ${G}`);let B=this.addDocumentId(G);this.saveStoredFields(B,X);for(let w of H){let M=Q(X,w);if(M==null)continue;let q=$(M.toString(),w),U=this._fieldIds[w],N=new Set(q).size;this.addFieldLength(B,U,this._documentCount-1,N);for(let D of q){let E=J(D,w);if(Array.isArray(E))for(let j of E)this.addTerm(U,B,j);else if(E)this.addTerm(U,B,E)}}}addAll(X){for(let Q of X)this.add(Q)}addAllAsync(X,Q={}){let{chunkSize:$=10}=Q,J={chunk:[],promise:Promise.resolve()},{chunk:H,promise:W}=X.reduce(({chunk:G,promise:B},w,M)=>{if(G.push(w),(M+1)%$===0)return{chunk:[],promise:B.then(()=>new Promise((q)=>setTimeout(q,0))).then(()=>this.addAll(G))};else return{chunk:G,promise:B}},J);return W.then(()=>this.addAll(H))}remove(X){let{tokenize:Q,processTerm:$,extractField:J,fields:H,idField:W}=this._options,G=J(X,W);if(G==null)throw new Error(`MiniSearch: document does not have ID field "${W}"`);let B=this._idToShortId.get(G);if(B==null)throw new Error(`MiniSearch: cannot remove document with ID ${G}: it is not in the index`);for(let w of H){let M=J(X,w);if(M==null)continue;let q=Q(M.toString(),w),U=this._fieldIds[w],N=new Set(q).size;this.removeFieldLength(B,U,this._documentCount,N);for(let D of q){let E=$(D,w);if(Array.isArray(E))for(let j of E)this.removeTerm(U,B,j);else if(E)this.removeTerm(U,B,E)}}this._storedFields.delete(B),this._documentIds.delete(B),this._idToShortId.delete(G),this._fieldLength.delete(B),this._documentCount-=1}removeAll(X){if(X)for(let Q of X)this.remove(Q);else if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");else this._index=new e,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}discard(X){let Q=this._idToShortId.get(X);if(Q==null)throw new Error(`MiniSearch: cannot discard document with ID ${X}: it is not in the index`);this._idToShortId.delete(X),this._documentIds.delete(Q),this._storedFields.delete(Q),(this._fieldLength.get(Q)||[]).forEach(($,J)=>{this.removeFieldLength(Q,J,this._documentCount,$)}),this._fieldLength.delete(Q),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()}maybeAutoVacuum(){if(this._options.autoVacuum===!1)return;let{minDirtFactor:X,minDirtCount:Q,batchSize:$,batchWait:J}=this._options.autoVacuum;this.conditionalVacuum({batchSize:$,batchWait:J},{minDirtCount:Q,minDirtFactor:X})}discardAll(X){let Q=this._options.autoVacuum;try{this._options.autoVacuum=!1;for(let $ of X)this.discard($)}finally{this._options.autoVacuum=Q}this.maybeAutoVacuum()}replace(X){let{idField:Q,extractField:$}=this._options,J=$(X,Q);this.discard(J),this.add(X)}vacuum(X={}){return this.conditionalVacuum(X)}conditionalVacuum(X,Q){if(this._currentVacuum){if(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&Q,this._enqueuedVacuum!=null)return this._enqueuedVacuum;return this._enqueuedVacuum=this._currentVacuum.then(()=>{let $=this._enqueuedVacuumConditions;return this._enqueuedVacuumConditions=k0,this.performVacuuming(X,$)}),this._enqueuedVacuum}if(this.vacuumConditionsMet(Q)===!1)return Promise.resolve();return this._currentVacuum=this.performVacuuming(X),this._currentVacuum}async performVacuuming(X,Q){let $=this._dirtCount;if(this.vacuumConditionsMet(Q)){let J=X.batchSize||P0.batchSize,H=X.batchWait||P0.batchWait,W=1;for(let[G,B]of this._index){for(let[w,M]of B)for(let[q]of M){if(this._documentIds.has(q))continue;if(M.size<=1)B.delete(w);else M.delete(q)}if(this._index.get(G).size===0)this._index.delete(G);if(W%J===0)await new Promise((w)=>setTimeout(w,H));W+=1}this._dirtCount-=$}await null,this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null}vacuumConditionsMet(X){if(X==null)return!0;let{minDirtCount:Q,minDirtFactor:$}=X;return Q=Q||C0.minDirtCount,$=$||C0.minDirtFactor,this.dirtCount>=Q&&this.dirtFactor>=$}get isVacuuming(){return this._currentVacuum!=null}get dirtCount(){return this._dirtCount}get dirtFactor(){return this._dirtCount/(1+this._documentCount+this._dirtCount)}has(X){return this._idToShortId.has(X)}getStoredFields(X){let Q=this._idToShortId.get(X);if(Q==null)return;return this._storedFields.get(Q)}search(X,Q={}){let{searchOptions:$}=this._options,J={...$,...Q},H=this.executeQuery(X,Q),W=[];for(let[G,{score:B,terms:w,match:M}]of H){let q=w.length||1,U={id:this._documentIds.get(G),score:B*q,terms:Object.keys(M),queryTerms:w,match:M};if(Object.assign(U,this._storedFields.get(G)),J.filter==null||J.filter(U))W.push(U)}if(X===B1.wildcard&&J.boostDocument==null)return W;return W.sort(z9),W}autoSuggest(X,Q={}){Q={...this._options.autoSuggestOptions,...Q};let $=new Map;for(let{score:H,terms:W}of this.search(X,Q)){let G=W.join(" "),B=$.get(G);if(B!=null)B.score+=H,B.count+=1;else $.set(G,{score:H,terms:W,count:1})}let J=[];for(let[H,{score:W,terms:G,count:B}]of $)J.push({suggestion:H,terms:G,score:W/B});return J.sort(z9),J}get documentCount(){return this._documentCount}get termCount(){return this._index.size}static loadJSON(X,Q){if(Q==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(X),Q)}static async loadJSONAsync(X,Q){if(Q==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJSAsync(JSON.parse(X),Q)}static getDefault(X){if(S0.hasOwnProperty(X))return v0(S0,X);else throw new Error(`MiniSearch: unknown option "${X}"`)}static loadJS(X,Q){let{index:$,documentIds:J,fieldLength:H,storedFields:W,serializationVersion:G}=X,B=this.instantiateMiniSearch(X,Q);B._documentIds=$0(J),B._fieldLength=$0(H),B._storedFields=$0(W);for(let[w,M]of B._documentIds)B._idToShortId.set(M,w);for(let[w,M]of $){let q=new Map;for(let U of Object.keys(M)){let N=M[U];if(G===1)N=N.ds;q.set(parseInt(U,10),$0(N))}B._index.set(w,q)}return B}static async loadJSAsync(X,Q){let{index:$,documentIds:J,fieldLength:H,storedFields:W,serializationVersion:G}=X,B=this.instantiateMiniSearch(X,Q);B._documentIds=await J0(J),B._fieldLength=await J0(H),B._storedFields=await J0(W);for(let[M,q]of B._documentIds)B._idToShortId.set(q,M);let w=0;for(let[M,q]of $){let U=new Map;for(let N of Object.keys(q)){let D=q[N];if(G===1)D=D.ds;U.set(parseInt(N,10),await J0(D))}if(++w%1000===0)await R9(0);B._index.set(M,U)}return B}static instantiateMiniSearch(X,Q){let{documentCount:$,nextId:J,fieldIds:H,averageFieldLength:W,dirtCount:G,serializationVersion:B}=X;if(B!==1&&B!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");let w=new B1(Q);return w._documentCount=$,w._nextId=J,w._idToShortId=new Map,w._fieldIds=H,w._avgFieldLength=W,w._dirtCount=G||0,w._index=new e,w}executeQuery(X,Q={}){if(X===B1.wildcard)return this.executeWildcardQuery(Q);if(typeof X!=="string"){let U={...Q,...X,queries:void 0},N=X.queries.map((D)=>this.executeQuery(D,U));return this.combineResults(N,U.combineWith)}let{tokenize:$,processTerm:J,searchOptions:H}=this._options,W={tokenize:$,processTerm:J,...H,...Q},{tokenize:G,processTerm:B}=W,q=G(X).flatMap((U)=>B(U)).filter((U)=>!!U).map(C4(W)).map((U)=>this.executeQuerySpec(U,W));return this.combineResults(q,W.combineWith)}executeQuerySpec(X,Q){let $={...this._options.searchOptions,...Q},J=($.fields||this._options.fields).reduce((E,j)=>({...E,[j]:v0($.boost,j)||1}),{}),{boostDocument:H,weights:W,maxFuzzy:G,bm25:B}=$,{fuzzy:w,prefix:M}={...A9.weights,...W},q=this._index.get(X.term),U=this.termResults(X.term,X.term,1,X.termBoost,q,J,H,B),N,D;if(X.prefix)N=this._index.atPrefix(X.term);if(X.fuzzy){let E=X.fuzzy===!0?0.2:X.fuzzy,j=E<1?Math.min(G,Math.round(X.term.length*E)):E;if(j)D=this._index.fuzzyGet(X.term,j)}if(N)for(let[E,j]of N){let C=E.length-X.term.length;if(!C)continue;D===null||D===void 0||D.delete(E);let X1=M*E.length/(E.length+0.3*C);this.termResults(X.term,E,X1,X.termBoost,j,J,H,B,U)}if(D)for(let E of D.keys()){let[j,C]=D.get(E);if(!C)continue;let X1=w*E.length/(E.length+C);this.termResults(X.term,E,X1,X.termBoost,j,J,H,B,U)}return U}executeWildcardQuery(X){let Q=new Map,$={...this._options.searchOptions,...X};for(let[J,H]of this._documentIds){let W=$.boostDocument?$.boostDocument(H,"",this._storedFields.get(J)):1;Q.set(J,{score:W,terms:[],match:{}})}return Q}combineResults(X,Q=I0){if(X.length===0)return new Map;let $=Q.toLowerCase(),J=j4[$];if(!J)throw new Error(`Invalid combination operator: ${Q}`);return X.reduce(J)||new Map}toJSON(){let X=[];for(let[Q,$]of this._index){let J={};for(let[H,W]of $)J[H]=Object.fromEntries(W);X.push([Q,J])}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:X,serializationVersion:2}}termResults(X,Q,$,J,H,W,G,B,w=new Map){if(H==null)return w;for(let M of Object.keys(W)){let q=W[M],U=this._fieldIds[M],N=H.get(U);if(N==null)continue;let D=N.size,E=this._avgFieldLength[U];for(let j of N.keys()){if(!this._documentIds.has(j)){this.removeTerm(U,j,Q),D-=1;continue}let C=G?G(this._documentIds.get(j),Q,this._storedFields.get(j)):1;if(!C)continue;let X1=N.get(j),n=this._fieldLength.get(j)[U],W0=S4(X1,D,this._documentCount,n,E,B),Z1=$*J*q*C*W0,Q1=w.get(j);if(Q1){Q1.score+=Z1,P4(Q1.terms,X);let y1=v0(Q1.match,Q);if(y1)y1.push(M);else Q1.match[Q]=[M]}else w.set(j,{score:Z1,terms:[X],match:{[Q]:[M]}})}}return w}addTerm(X,Q,$){let J=this._index.fetch($,q9),H=J.get(X);if(H==null)H=new Map,H.set(Q,1),J.set(X,H);else{let W=H.get(Q);H.set(Q,(W||0)+1)}}removeTerm(X,Q,$){if(!this._index.has($)){this.warnDocumentChanged(Q,X,$);return}let J=this._index.fetch($,q9),H=J.get(X);if(H==null||H.get(Q)==null)this.warnDocumentChanged(Q,X,$);else if(H.get(Q)<=1)if(H.size<=1)J.delete(X);else H.delete(Q);else H.set(Q,H.get(Q)-1);if(this._index.get($).size===0)this._index.delete($)}warnDocumentChanged(X,Q,$){for(let J of Object.keys(this._fieldIds))if(this._fieldIds[J]===Q){this._options.logger("warn",`MiniSearch: document with ID ${this._documentIds.get(X)} has changed before removal: term "${$}" was not present in field "${J}". Removing a document after it has changed can corrupt the index!`,"version_conflict");return}}addDocumentId(X){let Q=this._nextId;return this._idToShortId.set(X,Q),this._documentIds.set(Q,X),this._documentCount+=1,this._nextId+=1,Q}addFields(X){for(let Q=0;Q<X.length;Q++)this._fieldIds[X[Q]]=Q}addFieldLength(X,Q,$,J){let H=this._fieldLength.get(X);if(H==null)this._fieldLength.set(X,H=[]);H[Q]=J;let G=(this._avgFieldLength[Q]||0)*$+J;this._avgFieldLength[Q]=G/($+1)}removeFieldLength(X,Q,$,J){if($===1){this._avgFieldLength[Q]=0;return}let H=this._avgFieldLength[Q]*$-J;this._avgFieldLength[Q]=H/($-1)}saveStoredFields(X,Q){let{storeFields:$,extractField:J}=this._options;if($==null||$.length===0)return;let H=this._storedFields.get(X);if(H==null)this._storedFields.set(X,H={});for(let W of $){let G=J(Q,W);if(G!==void 0)H[W]=G}}}B1.wildcard=Symbol("*");var v0=(X,Q)=>Object.prototype.hasOwnProperty.call(X,Q)?X[Q]:void 0,j4={[I0]:(X,Q)=>{for(let $ of Q.keys()){let J=X.get($);if(J==null)X.set($,Q.get($));else{let{score:H,terms:W,match:G}=Q.get($);J.score=J.score+H,J.match=Object.assign(J.match,G),V9(J.terms,W)}}return X},[O9]:(X,Q)=>{let $=new Map;for(let J of Q.keys()){let H=X.get(J);if(H==null)continue;let{score:W,terms:G,match:B}=Q.get(J);V9(H.terms,G),$.set(J,{score:H.score+W,terms:H.terms,match:Object.assign(H.match,B)})}return $},[D4]:(X,Q)=>{for(let $ of Q.keys())X.delete($);return X}},v4={k:1.2,b:0.7,d:0.5},S4=(X,Q,$,J,H,W)=>{let{k:G,b:B,d:w}=W;return Math.log(1+($-Q+0.5)/(Q+0.5))*(w+X*(G+1)/(X+G*(1-B+B*J/H)))},C4=(X)=>(Q,$,J)=>{let H=typeof X.fuzzy==="function"?X.fuzzy(Q,$,J):X.fuzzy||!1,W=typeof X.prefix==="function"?X.prefix(Q,$,J):X.prefix===!0,G=typeof X.boostTerm==="function"?X.boostTerm(Q,$,J):1;return{term:Q,fuzzy:H,prefix:W,termBoost:G}},S0={idField:"id",extractField:(X,Q)=>X[Q],tokenize:(X)=>X.split(k4),processTerm:(X)=>X.toLowerCase(),fields:void 0,searchOptions:void 0,storeFields:[],logger:(X,Q)=>{if(typeof(console===null||console===void 0?void 0:console[X])==="function")console[X](Q)},autoVacuum:!0},A9={combineWith:I0,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:0.45,prefix:0.375},bm25:v4},b4={combineWith:O9,prefix:(X,Q,$)=>Q===$.length-1},P0={batchSize:1000,batchWait:10},k0={minDirtFactor:0.1,minDirtCount:20},C0={...P0,...k0},P4=(X,Q)=>{if(!X.includes(Q))X.push(Q)},V9=(X,Q)=>{for(let $ of Q)if(!X.includes($))X.push($)},z9=({score:X},{score:Q})=>Q-X,q9=()=>new Map,$0=(X)=>{let Q=new Map;for(let $ of Object.keys(X))Q.set(parseInt($,10),X[$]);return Q},J0=async(X)=>{let Q=new Map,$=0;for(let J of Object.keys(X))if(Q.set(parseInt(J,10),X[J]),++$%1000===0)await R9(0);return Q},R9=(X)=>new Promise((Q)=>setTimeout(Q,X)),k4=/[\n\r\p{Z}\p{P}]+/u;var x4=k({prdId:Y.string(),cwd:Y.string()}),h4=k({prdId:Y.string(),userStoryId:Y.string(),cwd:Y.string()}),Z4=k({prdId:Y.string(),userStoryId:Y.string(),taskId:Y.string(),cwd:Y.string()}),y7=k({cwd:Y.string()}),y4=k({taskId:Y.string(),cwd:Y.string()}),l4=k({searchTerm:Y.string(),cwd:Y.string(),type:Y.enum(["PRD","BRD","NFR","UIR","BP","US","TASK"]).optional()}),m4=k({cwd:Y.string(),includeDescription:Y.boolean().optional().default(!1),limit:Y.number().optional().default(10),offset:Y.number().optional().default(0)}),c4=k({cwd:Y.string(),includeDescription:Y.boolean().optional().default(!1),limit:Y.number().optional().default(10),offset:Y.number().optional().default(0),includeUserStories:Y.boolean().optional().default(!1),includeTasks:Y.boolean().optional().default(!1)}),u4=k({cwd:Y.string(),includeDescription:Y.boolean().optional().default(!1),limit:Y.number().optional().default(10),offset:Y.number().optional().default(0)}),p4=k({cwd:Y.string(),includeDescription:Y.boolean().optional().default(!1),limit:Y.number().optional().default(10),offset:Y.number().optional().default(0)}),n4=k({cwd:Y.string(),includeDescription:Y.boolean().optional().default(!1),limit:Y.number().optional().default(10),offset:Y.number().optional().default(0)}),i4=k({cwd:Y.string(),limit:Y.number().optional().default(10),offset:Y.number().optional().default(0)});class T0{server;documentService;fileService;solution;projectPath;miniSearch;constructor(X){this.solution=null,this.projectPath=X||null,this.documentService=new D0,this.fileService=new x1,this.miniSearch=new B1({fields:["id","title","description","type"],storeFields:["id","title","description","type"],searchOptions:{fuzzy:!0}}),this.server=new E0({name:"specifai",version:"0.4.2"},{capabilities:{tools:{}}}),K.info("Initializing MCP server..."),this.setupRequestHandlers(),K.info("MCP server initialized")}formatDocuments(X){return X.map((Q)=>[`ID: ${Q.id}`,`Title: ${Q.title}`,`Description: ${Q.description}`,"--------------"].join(`
5
5
  `)).join(`
6
- `)}async loadSolutionByAutoInference($){let X=await this.inferProjectPath($);if(X)this.projectPath=X,this.solution=await this.documentService.loadSolution(X),O.info({inferredPath:X},"Project path auto-inferred")}async inferProjectPath($){if(!$)return O.debug("No directory path provided for inference"),null;try{if(!await this.fileService.isDirectory($))return O.debug({directoryPath:$},"Directory does not exist"),null;let X=n9($,".specifai-path");try{await d9(X,r9.R_OK)}catch{return O.debug({specFilePath:X},".specifai-path file not found"),null}let W=(await i9(X,"utf-8")).trim();if(!await this.fileService.isDirectory(W))return O.warn({projectPath:W},"Project path from .specifai-path is not a valid directory"),null;return O.info({directoryPath:$,projectPath:W},"Successfully inferred project path"),W}catch(X){return O.error({error:X,directoryPath:$},"Error inferring project path"),null}}setupRequestHandlers(){this.setupListToolsHandler(),this.setupCallToolHandler()}setupListToolsHandler(){this.server.setRequestHandler(Q1,async()=>{return O.info("Handling list tools request"),{tools:[{name:"get-brds",description:"Get Business Requirement Documents for this project",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}},required:["cwd"]}},{name:"get-prds",description:"Get Product Requirement Documents for this project",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}},required:["cwd"]}},{name:"get-nfrs",description:"Get Non-Functional Requirement Documents for this project",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}},required:["cwd"]}},{name:"get-uirs",description:"Get User Interface Requirement Documents for this project",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}},required:["cwd"]}},{name:"get-bpds",description:"Get Business Process Documents for this project",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}},required:["cwd"]}},{name:"get-user-stories",description:"Get User Stories for a particular PRD",inputSchema:{type:"object",required:["prdId","cwd"],properties:{prdId:{type:"string",description:"The ID of the PRD to get user stories for"},cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}}}},{name:"get-tasks",description:"Get Tasks for a particular User Story",inputSchema:{type:"object",required:["prdId","userStoryId","cwd"],properties:{prdId:{type:"string",description:"The ID of the PRD to get user stories for"},userStoryId:{type:"string",description:"The ID of the User Story to get tasks for"},cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}}}},{name:"get-task",description:"Get a Task for a particular User Story in a particular PRD",inputSchema:{type:"object",required:["prdId","userStoryId","taskId","cwd"],properties:{prdId:{type:"string",description:"The ID of the PRD to get user stories for"},userStoryId:{type:"string",description:"The ID of the User Story to get tasks for"},taskId:{type:"string",description:"The ID of the Task to get"},cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}}}},{name:"set-project-path",description:"Update the project path and reload the solution. use this tool only when we not automatically able to infer the project path or asked by the user or us., we will try to auto infer it from the environment first.",inputSchema:{type:"object",required:["path"],properties:{path:{type:"string",description:"The absolute path to a directory containing specifai specification files."}}}}]}})}setupCallToolHandler(){if(this.projectPath)O.info({projectPath:this.projectPath},"Project path is found from process.env.PWD"),this.inferProjectPath(this.projectPath).then(($)=>{if($)O.info({inferredPath:$},"Project path auto-inferred"),this.projectPath=$,this.documentService.loadSolution($).then((X)=>{this.solution=X,O.info("Solution loaded from auto-inferred project path")})});this.server.setRequestHandler(W1,async($)=>{let{name:X,arguments:Q}=$.params;O.info({tool:X,args:Q},"Handling tool call");try{switch(X){case"set-project-path":{let{path:W}=$0({path:H.string()}).parse(Q);return this.projectPath=W,this.solution=await this.documentService.loadSolution(W),this.createTextResponse(`Project path set to: ${W}`)}case"get-brds":{let{cwd:W}=k0.parse(Q);if(W)await this.loadSolutionByAutoInference(W);if(!this.solution||!W)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");return this.createTextResponse(this.formatDocuments(this.solution.BRD))}case"get-prds":{let{cwd:W}=k0.parse(Q);if(W)await this.loadSolutionByAutoInference(W);if(!this.solution||!W)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");return this.createTextResponse(this.formatDocuments(this.solution.PRD))}case"get-nfrs":{let{cwd:W}=k0.parse(Q);if(W)await this.loadSolutionByAutoInference(W);if(!this.solution||!W)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");return this.createTextResponse(this.formatDocuments(this.solution.NFR))}case"get-uirs":{let{cwd:W}=k0.parse(Q);if(W)await this.loadSolutionByAutoInference(W);if(!this.solution||!W)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");return this.createTextResponse(this.formatDocuments(this.solution.UIR))}case"get-bpds":{let{cwd:W}=k0.parse(Q);if(W)await this.loadSolutionByAutoInference(W);if(!this.solution||!W)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");return this.createTextResponse(this.formatDocuments(this.solution.BP))}case"get-user-stories":{let{prdId:W,cwd:J}=o9.parse(Q);if(J)await this.loadSolutionByAutoInference(J);if(!this.solution||!J)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let G=this.documentService.findPRD(this.solution,W);if(!G)return O.warn({prdId:W},"PRD not found"),this.createTextResponse(`No PRD found with ID ${W}`);return this.createTextResponse(this.formatDocuments(G.userStories))}case"get-tasks":{let{prdId:W,userStoryId:J,cwd:G}=a9.parse(Q);if(G)await this.loadSolutionByAutoInference(G);if(!this.solution||!G)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let Y=this.documentService.findPRD(this.solution,W);if(!Y)return O.warn({prdId:W},"PRD not found"),this.createTextResponse(`No PRD found with ID ${W}`);let B=this.documentService.findUserStory(Y,J);if(!B)return O.warn({prdId:W,userStoryId:J},"User Story not found"),this.createTextResponse(`No User Story found with ID ${J}`);return this.createTextResponse(this.formatDocuments(B.tasks))}case"get-task":{let{prdId:W,userStoryId:J,taskId:G,cwd:Y}=s9.parse(Q);if(Y)await this.loadSolutionByAutoInference(Y);if(!this.solution||!Y)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let B=this.documentService.findPRD(this.solution,W);if(!B)return O.warn({prdId:W},"PRD not found"),this.createTextResponse(`No PRD found with ID ${W}`);let M=this.documentService.findUserStory(B,J);if(!M)return O.warn({prdId:W,userStoryId:J},"User Story not found"),this.createTextResponse(`No User Story found with ID ${J}`);let V=this.documentService.findTask(M,G);if(!V)return O.warn({prdId:W,userStoryId:J,taskId:G},"Task not found"),this.createTextResponse(`No Task found with ID ${G}`);return this.createTextResponse([`ID: ${V.id}`,`Title: ${V.title}`,`Description: ${V.description}`].join(`
7
- `))}default:throw O.warn({tool:X},"Unknown tool called"),new Error(`Unknown tool: ${X}`)}}catch(W){if(W instanceof H.ZodError){let J=`Invalid arguments: ${W.errors.map((G)=>`${G.path.join(".")}: ${G.message}`).join(", ")}`;throw O.error({error:W.errors,tool:X},J),new Error(J)}throw O.error({error:W,tool:X},"Error handling tool call"),W}})}createTextResponse($){return{content:[{type:"text",text:$}]}}async start(){O.info("Starting MCP server...");let $=new q1;await this.server.connect($),O.info("MCP server started successfully")}}var m={name:"@presidio-dev/specifai-mcp-server",version:"0.3.0",description:"Specifai MCP Server that runs over stdio",type:"module",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/presidio-oss/specifai-mcp-server.git"},keywords:["specifai","mcp","model-context-protocol","cli","stdio","server"],author:"Presidio",module:"dist/index.js",main:"dist/index.js",bin:{"specifai-mcp-server":"dist/index.js"},files:["dist","README.md"],engines:{node:">=16.0.0",bun:">=1.0.0"},scripts:{test:"jest --coverage","test:watch":"jest --watch",build:"./build.sh","build:npm":"./build-npm.sh",prepublishOnly:"bun run build:npm",prepare:"husky",format:"prettier --write .","format:check":"prettier --check .",release:"release-it","release:dry-run":"release-it --dry-run","release:ci":"release-it --ci"},devDependencies:{"@commitlint/cli":"^19.7.1","@commitlint/config-conventional":"^19.7.1","@jest/globals":"^29.7.0","@release-it/conventional-changelog":"^10.0.0","@types/bun":"latest","@types/jest":"^29.5.14",husky:"^9.1.7",jest:"^29.7.0",prettier:"^3.5.1","release-it":"^18.1.2","ts-jest":"^29.2.5"},peerDependencies:{typescript:"^5.0.0"},dependencies:{"@modelcontextprotocol/sdk":"^1.5.0",pino:"^9.6.0",zod:"^3.24.2"},jest:{preset:"ts-jest/presets/default-esm",testEnvironment:"node",extensionsToTreatAsEsm:[".ts"],moduleNameMapper:{"^(\\.{1,2}/.*)\\.js$":"$1"},transform:{"^.+\\.tsx?$":["ts-jest",{useESM:!0,tsconfig:"tsconfig.jest.json"}]},collectCoverageFrom:["src/services/**/*.ts","!src/services/**/*.test.ts","!src/services/**/*test-utils.ts"]}};function e9(){console.log("0.4.0")}function $$(){console.error(`
8
- ${m.name} - v0.4.0
6
+ `)}formatDocumentsV2(X){return X.map((Q)=>[Object.keys(Q).map(($)=>`${$}: ${Q[$]}`).join(`
7
+ `),"--------------"].join(`
8
+ `)).join(`
9
+ `)}async loadSolutionByAutoInference(X){let Q=await this.inferProjectPath(X);if(Q)this.projectPath=Q,this.solution=await this.documentService.loadSolution(Q),this.updateMiniSearchIndex(),K.info({inferredPath:Q},"Project path auto-inferred")}async inferProjectPath(X){if(!X)return K.debug("No directory path provided for inference"),null;try{if(!await this.fileService.isDirectory(X))return K.debug({directoryPath:X},"Directory does not exist"),null;let Q=f4(X,".specifai-path");try{await T4(Q,g4.R_OK)}catch{return K.debug({specFilePath:Q},".specifai-path file not found"),null}let J=(await I4(Q,"utf-8")).trim();if(!await this.fileService.isDirectory(J))return K.warn({projectPath:J},"Project path from .specifai-path is not a valid directory"),null;return K.info({directoryPath:X,projectPath:J},"Successfully inferred project path"),J}catch(Q){return K.error({error:Q,directoryPath:X},"Error inferring project path"),null}}setupRequestHandlers(){this.setupListToolsHandler(),this.setupCallToolHandler()}setupListToolsHandler(){this.server.setRequestHandler(U0,async()=>{return K.info("Handling list tools request"),{tools:[{name:"get-brds",description:"Get Business Requirement Documents for this project, returns ID, Title, Description(not included by default)",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."},includeDescription:{type:"boolean",description:"Include description in the output, default is false"},limit:{type:"number",description:"Limit the number of documents to return, default is 10"},offset:{type:"number",description:"Offset the number of documents to return, default is 0"}},required:["cwd"]}},{name:"get-prds",description:"Get Product Requirement Documents for this project, returns ID, Title, Description(not included by default)",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."},includeDescription:{type:"boolean",description:"Include description in the output, default is false"},limit:{type:"number",description:"Limit the number of documents to return, default is 10"},offset:{type:"number",description:"Offset the number of documents to return, default is 0"},includeUserStories:{type:"boolean",description:"Include user stories in the output each user stories will include ID and Title, Description will not be included, default is false"},includeTasks:{type:"boolean",description:"Include tasks in the output each task will include ID and Title, Description will not be included, default is false"}},required:["cwd"]}},{name:"get-nfrs",description:"Get Non-Functional Requirement Documents for this project, returns ID, Title, Description(not included by default)",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."},includeDescription:{type:"boolean",description:"Include description in the output, default is false"},limit:{type:"number",description:"Limit the number of documents to return, default is 10"},offset:{type:"number",description:"Offset the number of documents to return, default is 0"}},required:["cwd"]}},{name:"get-uirs",description:"Get User Interface Requirement Documents for this project",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."},includeDescription:{type:"boolean",description:"Include description in the output, default is false"},limit:{type:"number",description:"Limit the number of documents to return, default is 10"},offset:{type:"number",description:"Offset the number of documents to return, default is 0"}},required:["cwd"]}},{name:"get-bpds",description:"Get Business Process Documents for this project",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}},includeDescription:{type:"boolean",description:"Include description in the output, default is false"},limit:{type:"number",description:"Limit the number of documents to return, default 10"},offset:{type:"number",description:"Offset the number of documents to return, default is 0"},required:["cwd"]}},{name:"get-user-stories",description:"Get User Stories for a particular PRD",inputSchema:{type:"object",required:["prdId","cwd"],properties:{prdId:{type:"string",description:"The ID of the PRD to get user stories for, PRD ID convention is PRD<PRD Number>, PRD number is zero padded with minimum 2 digits, e.g. PRD01, PRD12, PRD103, etc."},cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}}}},{name:"get-tasks",description:"Get Tasks for a particular User Story",inputSchema:{type:"object",required:["prdId","userStoryId","cwd"],properties:{prdId:{type:"string",description:"The ID of the PRD to get user stories for, PRD ID convention is PRD<PRD Number>, PRD number is zero padded with minimum 2 digits, e.g. PRD01, PRD12, PRD103, etc."},userStoryId:{type:"string",description:"The ID of the User Story to get tasks for, US ID convention is US<US Number>, US number is non zero padded, e.g. US1, US12, US103, etc."},cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}}}},{name:"get-task",description:"Get list of Tasks for a particular User Story in a particular PRD",inputSchema:{type:"object",required:["prdId","userStoryId","taskId","cwd"],properties:{prdId:{type:"string",description:"The ID of the PRD to get user stories for, PRD ID convention is PRD<PRD Number>, PRD number is zero padded with minimum 2 digits, e.g. PRD01, PRD12, PRD103, etc."},userStoryId:{type:"string",description:"The ID of the User Story to get tasks for, US ID convention is US<US Number>, US number is non zero padded, e.g. US1, US12, US103, etc."},taskId:{type:"string",description:"The ID of the Task to get, TASK ID convention is TASK<TASK Number>, TASK number is non zero padded, e.g. TASK1, TASK12, TASK103, etc."},cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}}}},{name:"set-project-path",description:"Update the project path and reload the solution. use this tool only when we not automatically able to infer the project path or asked by the user or us., we will try to auto infer it from the environment first.",inputSchema:{type:"object",required:["path"],properties:{path:{type:"string",description:"The absolute path to a directory containing specifai specification files."}}}},{name:"get-task-by-id",description:"Retrieves complete information about a specific task when you know its exact ID. This tool provides direct access to a single task's details without having to retrieve and filter through all tasks., returns full task object, ID, Title, Description",inputSchema:{type:"object",required:["taskId","cwd"],properties:{taskId:{type:"string",description:"The unique identifier for the task you want to retrieve Must follow the format: TASK followed by a number without leading zeros Examples: TASK1 TASK12, TASK103 Note: The number portion is NOT zero-padded (use TASK1, not TASK01), Convert the Task ID to mentioned format to use this tool."},cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}}}},{name:"list-all-tasks",description:"List all the tasks available across all PRDs and User Stories, without task description, only return ID and Title",inputSchema:{type:"object",required:["cwd"],properties:{cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."},limit:{type:"number",description:"Limit the number of documents to return, default is 10"},offset:{type:"number",description:"Offset the number of documents to return, default is 0"}}}},{name:"search",description:"Full text search across all documents, returns an array of document ID, Title, Description",inputSchema:{type:"object",required:["searchTerm","cwd"],properties:{searchTerm:{type:"string",description:"The search term to search for"},type:{type:"string",description:"Optional type of document to search in, valid values are: PRD, BRD, NFR, UIR, BP, US, TASK"},cwd:{type:"string",description:"Absolute path where the tool is called from and containing the `.specifai-path` file to auto-infer the specifai project path. This path will be current working directory (cwd) from where the tool is called."}}}}]}})}updateMiniSearchIndex(){if(!this.solution)return;this.miniSearch.removeAll();let X=[...this.solution.PRD.map((Q)=>({...Q,type:"PRD"})),...this.solution.BRD.map((Q)=>({...Q,type:"BRD"})),...this.solution.NFR.map((Q)=>({...Q,type:"NFR"})),...this.solution.UIR.map((Q)=>({...Q,type:"UIR"})),...this.solution.BP.map((Q)=>({...Q,type:"BP"})),...this.solution.PRD.flatMap((Q)=>Q.userStories).map((Q)=>({...Q,type:"US"})),...this.solution.PRD.flatMap((Q)=>Q.userStories.flatMap(($)=>$.tasks)).map((Q)=>({...Q,type:"TASK"}))];this.miniSearch.addAll(X)}paginate(X,Q=0,$=0){if(Q===0)return X.slice($);return X.slice($,$+Q)}setupCallToolHandler(){if(this.projectPath)K.info({projectPath:this.projectPath},"Project path is found from process.env.PWD"),this.inferProjectPath(this.projectPath).then((X)=>{if(X)K.info({inferredPath:X},"Project path auto-inferred"),this.projectPath=X,this.documentService.loadSolution(X).then((Q)=>{this.solution=Q,this.updateMiniSearchIndex(),K.info("Solution loaded from auto-inferred project path")})});this.server.setRequestHandler(L0,async(X)=>{let{name:Q,arguments:$}=X.params;K.info({tool:Q,args:$},"Handling tool call");try{switch(Q){case"set-project-path":{let{path:J}=k({path:Y.string()}).parse($);return this.projectPath=J,this.solution=await this.documentService.loadSolution(J),this.updateMiniSearchIndex(),this.createTextResponse(`Project path set to: ${J}`)}case"get-brds":{let{cwd:J,includeDescription:H,limit:W,offset:G}=m4.parse($);if(J)await this.loadSolutionByAutoInference(J);if(!this.solution||!J)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let B=this.paginate(this.solution.BRD.map((w)=>({ID:w.id,Title:w.title,...H?{Description:w.description}:{}})),W,G);if(B.length===0)return this.createTextResponse("No BRDs found");return this.createTextResponse(this.formatDocumentsV2(B))}case"get-prds":{let{cwd:J,includeDescription:H,includeTasks:W,includeUserStories:G,limit:B,offset:w}=c4.parse($);if(J)await this.loadSolutionByAutoInference(J);if(!this.solution||!J)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let M=this.paginate(this.solution.PRD,B,w);if(M.length===0)return this.createTextResponse("No PRDs found");return this.createTextResponse(M.reduce((q,U)=>{let N=[`ID: ${U.id}`,`Title: ${U.title}`,...H?[`Description: ${U.description}`]:[]];if(G)if(U.userStories.length===0)N.push(`User Stories: ${U.id} has no user stories`);else N.push("User Stories:"),U.userStories.forEach((D)=>{if(N.push(` US ID: ${D.id}`),N.push(` US Title: ${D.title}`),W)if(D.tasks.length===0)N.push(` Tasks: ${D.id} has no tasks`);else N.push(" Tasks:"),D.tasks.forEach((E)=>{N.push(` TASK ID: ${E.id}`),N.push(` TASK Title: ${E.title}`)})});return N.push(`--------------
10
+ `),q+N.join(`
11
+ `)+`
12
+ `},""))}case"get-nfrs":{let{cwd:J,includeDescription:H,limit:W,offset:G}=u4.parse($);if(J)await this.loadSolutionByAutoInference(J);if(!this.solution||!J)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let B=this.paginate(this.solution.NFR.map((w)=>({ID:w.id,Title:w.title,...H?{Description:w.description}:{}})),W,G);if(B.length===0)return this.createTextResponse("No NFRs found");return this.createTextResponse(this.formatDocumentsV2(B))}case"get-uirs":{let{cwd:J,includeDescription:H,limit:W,offset:G}=p4.parse($);if(J)await this.loadSolutionByAutoInference(J);if(!this.solution||!J)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let B=this.paginate(this.solution.UIR.map((w)=>({ID:w.id,Title:w.title,...H?{Description:w.description}:{}})),W,G);if(B.length===0)return this.createTextResponse("No UIRs found");return this.createTextResponse(this.formatDocumentsV2(B))}case"get-bpds":{let{cwd:J,includeDescription:H,limit:W,offset:G}=n4.parse($);if(J)await this.loadSolutionByAutoInference(J);if(!this.solution||!J)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let B=this.paginate(this.solution.BP.map((w)=>({ID:w.id,Title:w.title,...H?{Description:w.description}:{}})),W,G);if(B.length===0)return this.createTextResponse("No BPs found");return this.createTextResponse(this.formatDocumentsV2(B))}case"get-user-stories":{let{prdId:J,cwd:H}=x4.parse($);if(H)await this.loadSolutionByAutoInference(H);if(!this.solution||!H)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let W=this.documentService.findPRD(this.solution,J);if(!W)return K.warn({prdId:J},"PRD not found"),this.createTextResponse(`No PRD found with ID ${J}`);return this.createTextResponse(this.formatDocuments(W.userStories))}case"get-tasks":{let{prdId:J,userStoryId:H,cwd:W}=h4.parse($);if(W)await this.loadSolutionByAutoInference(W);if(!this.solution||!W)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let G=this.documentService.findPRD(this.solution,J);if(!G)return K.warn({prdId:J},"PRD not found"),this.createTextResponse(`No PRD found with ID ${J}`);let B=this.documentService.findUserStory(G,H);if(!B)return K.warn({prdId:J,userStoryId:H},"User Story not found"),this.createTextResponse(`No User Story found with ID ${H}`);return this.createTextResponse(this.formatDocuments(B.tasks))}case"get-task":{let{prdId:J,userStoryId:H,taskId:W,cwd:G}=Z4.parse($);if(G)await this.loadSolutionByAutoInference(G);if(!this.solution||!G)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let B=this.documentService.findPRD(this.solution,J);if(!B)return K.warn({prdId:J},"PRD not found"),this.createTextResponse(`No PRD found with ID ${J}`);let w=this.documentService.findUserStory(B,H);if(!w)return K.warn({prdId:J,userStoryId:H},"User Story not found"),this.createTextResponse(`No User Story found with ID ${H}`);let M=this.documentService.findTask(w,W);if(!M)return K.warn({prdId:J,userStoryId:H,taskId:W},"Task not found"),this.createTextResponse(`No Task found with ID ${W}`);return this.createTextResponse([`ID: ${M.id}`,`Title: ${M.title}`,`Description: ${M.description}`].join(`
13
+ `))}case"list-all-tasks":{let{cwd:J,limit:H,offset:W}=i4.parse($);if(J)await this.loadSolutionByAutoInference(J);if(!this.solution||!J)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let G=this.paginate(this.solution.PRD.map((B)=>B.userStories.map((w)=>w.tasks)).flat(2),H,W);if(!G||G.length===0)return this.createTextResponse("No tasks found");return this.createTextResponse(this.formatDocumentsV2(G.map((B)=>({ID:B.id,Title:B.title}))))}case"get-task-by-id":{let{taskId:J,cwd:H}=y4.parse($);if(H)await this.loadSolutionByAutoInference(H);if(!this.solution||!H)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let W=this.solution.PRD.flatMap((G)=>G.userStories.flatMap((B)=>B.tasks)).find((G)=>G.id===J);if(!W)return K.warn({taskId:J},"Task not found"),this.createTextResponse(`No Task found with ID ${J}`);return this.createTextResponse([`ID: ${W.id}`,`Title: ${W.title}`,`Description: ${W.description}`].join(`
14
+ `))}case"search":{let{searchTerm:J,cwd:H,type:W}=l4.parse($);if(H)await this.loadSolutionByAutoInference(H);if(!this.solution||!H)throw new Error("No project path set. Use set-project-path first or provide a valid cwd to auto-infer.");let G=this.miniSearch.search(J);if(W)G=G.filter((w)=>w.type===W);if(G.length===0)return this.createTextResponse("No results found");let B=G.map((w)=>[`ID: ${w.id}`,`Title: ${w.title}`,`Description: ${w.description}`,`Type: ${w.type}`,"--------------"].join(`
15
+ `)).join(`
16
+ `);return this.createTextResponse(B)}default:throw K.warn({tool:Q},"Unknown tool called"),new Error(`Unknown tool: ${Q}`)}}catch(J){if(J instanceof Y.ZodError){let H=`Invalid arguments: ${J.errors.map((W)=>`${W.path.join(".")}: ${W.message}`).join(", ")}`;throw K.error({error:J.errors,tool:Q},H),new Error(H)}throw K.error({error:J,tool:Q},"Error handling tool call"),J}})}createTextResponse(X){return{content:[{type:"text",text:X}]}}async start(){K.info("Starting MCP server...");let X=new _0;await this.server.connect(X),K.info("MCP server started successfully")}}var p={name:"@presidio-dev/specifai-mcp-server",version:"0.4.1",description:"Specifai MCP Server that runs over stdio",type:"module",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/presidio-oss/specifai-mcp-server.git"},keywords:["specifai","mcp","model-context-protocol","cli","stdio","server"],author:"Presidio",module:"dist/index.js",main:"dist/index.js",bin:{"specifai-mcp-server":"dist/index.js"},files:["dist","README.md"],engines:{node:">=16.0.0",bun:">=1.0.0"},scripts:{test:"jest --coverage","test:watch":"jest --watch",dev:"bun build ./index.ts --outdir ./dist --target node --minify --sourcemap --external pino","dev:watch":"bun build --watch ./index.ts --outdir ./dist --target node --minify --sourcemap --external pino",build:"./build.sh","build:npm":"./build-npm.sh",prepublishOnly:"bun run build:npm",prepare:"husky",format:"prettier --write .","format:check":"prettier --check .",release:"release-it","release:dry-run":"release-it --dry-run","release:ci":"release-it --ci"},devDependencies:{"@commitlint/cli":"^19.7.1","@commitlint/config-conventional":"^19.7.1","@jest/globals":"^29.7.0","@release-it/conventional-changelog":"^10.0.0","@types/bun":"latest","@types/jest":"^29.5.14",husky:"^9.1.7",jest:"^29.7.0",prettier:"^3.5.1","release-it":"^18.1.2","ts-jest":"^29.2.5"},peerDependencies:{typescript:"^5.0.0"},dependencies:{"@modelcontextprotocol/sdk":"^1.5.0",minisearch:"^7.1.2",pino:"^9.6.0",zod:"^3.24.2"},jest:{preset:"ts-jest/presets/default-esm",testEnvironment:"node",extensionsToTreatAsEsm:[".ts"],moduleNameMapper:{"^(\\.{1,2}/.*)\\.js$":"$1"},transform:{"^.+\\.tsx?$":["ts-jest",{useESM:!0,tsconfig:"tsconfig.jest.json"}]},collectCoverageFrom:["src/services/**/*.ts","!src/services/**/*.test.ts","!src/services/**/*test-utils.ts"]}};function r4(){console.log("0.4.2")}function a4(){console.error(`
17
+ ${p.name} - v0.4.2
9
18
 
10
- Usage: ${m.bin?Object.keys(m.bin)[0]:m.name}
19
+ Usage: ${p.bin?Object.keys(p.bin)[0]:p.name}
11
20
 
12
21
  Options:
13
22
  -h, --help Display this help message
14
23
  -v, --version Display version information
15
24
 
16
25
  Example:
17
- ${m.bin?Object.keys(m.bin)[0]:m.name}
26
+ ${p.bin?Object.keys(p.bin)[0]:p.name}
18
27
 
19
- npx --yes ${m.name}
28
+ npx --yes ${p.name}
20
29
 
21
- bunx ${m.name}
22
- `)}async function X$(){try{O.info({version:"0.4.0",pwd:process.env.PWD,...process.env},"Starting Specifai MCP Server");let $=process.argv.slice(2);if($[0]==="--help"||$[0]==="-h")$$(),process.exit($.length===0?1:0);if($[0]==="--version"||$[0]==="-v")e9(),process.exit(0);await new w1(process.env.PWD).start(),O.info("Specifai MCP Server running on stdio")}catch($){O.error({error:$ instanceof Error?$.message:String($)},"Fatal error"),process.exit(1)}}process.on("SIGINT",()=>{O.info("Received SIGINT. Shutting down..."),process.exit(0)});process.on("SIGTERM",()=>{O.info("Received SIGTERM. Shutting down..."),process.exit(0)});X$();
30
+ bunx ${p.name}
31
+ `)}async function o4(){try{K.info({version:"0.4.2",pwd:process.env.PWD,...process.env},"Starting Specifai MCP Server");let X=process.argv.slice(2);if(X[0]==="--help"||X[0]==="-h")a4(),process.exit(X.length===0?1:0);if(X[0]==="--version"||X[0]==="-v")r4(),process.exit(0);await new T0(process.env.PWD).start(),K.info("Specifai MCP Server running on stdio")}catch(X){K.error({error:X instanceof Error?X.message:String(X)},"Fatal error"),process.exit(1)}}process.on("SIGINT",()=>{K.info("Received SIGINT. Shutting down..."),process.exit(0)});process.on("SIGTERM",()=>{K.info("Received SIGTERM. Shutting down..."),process.exit(0)});o4();
23
32
 
24
- //# debugId=9B6F2473C99A4C0164756E2164756E21
33
+ //# debugId=EF67114C24607CFF64756E2164756E21
25
34
  //# sourceMappingURL=index.js.map