@typescape-ai/mcp 1.9.2 → 1.9.4
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/mcp.js +3 -3
- package/package.json +1 -1
package/dist/mcp.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var T4=Object.create;var{getPrototypeOf:g4,defineProperty:g0,getOwnPropertyNames:x4}=Object;var h4=Object.prototype.hasOwnProperty;function Z4($){return this[$]}var m4,y4,x0=($,W,X)=>{var J=$!=null&&typeof $==="object";if(J){var Y=W?m4??=new WeakMap:y4??=new WeakMap,w=Y.get($);if(w)return w}X=$!=null?T4(g4($)):{};let B=W||!$||!$.__esModule?g0(X,"default",{value:$,enumerable:!0}):X;for(let M of x4($))if(!h4.call(B,M))g0(B,M,{get:Z4.bind($,M),enumerable:!0});if(J)Y.set($,B);return B};var l4=($,W)=>()=>(W||$((W={exports:{}}).exports,W),W.exports);var L0=l4((I6,c4)=>{c4.exports={name:"@typescape-ai/mcp",version:"1.9.2",description:"Typescape MCP Server - Model Context Protocol integration for AI agents",type:"module",bin:{"typescape-mcp":"./dist/mcp.js"},files:["dist","README.md"],exports:{".":"./dist/mcp.js"},publishConfig:{access:"public"},scripts:{build:"bun build src/index.ts --outfile=dist/mcp.js --target=bun --bundle --minify",dev:"bun run --watch src/index.ts",test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src",prepublishOnly:"bun run build"},dependencies:{},devDependencies:{"@modelcontextprotocol/sdk":"1.0.4","@types/bun":"1.1.14","@typescape/schemas":"workspace:*",zod:"4.3.0"},engines:{bun:">=1.0.0"},keywords:["typescape","mcp","model-context-protocol","ai","claude","review","bun"],repository:{type:"git",url:"https://github.com/voidserf/typescape-docs.git",directory:"apps/mcp"},license:"MIT"}});function h0(){let $=new Map;return{register(W,X){$.set(W.name,{definition:W,handler:X})},getTools(){return Array.from($.values()).map((W)=>W.definition)},getHandler(W){return $.get(W)?.handler}}}var u4=await Promise.resolve().then(() => x0(L0(),1)),Z0=`typescape-mcp/${u4.version}`;class q extends Error{status;code;requestId;details;fixHint;constructor($,W,X,J,Y,w){super(X);this.status=$;this.code=W;this.requestId=J;this.details=Y;this.fixHint=w;this.name="ApiError"}}var e1=30000;function m0($,W,X=e1){let Y=$.replace(/\/$/,"");async function w(B,M,j={}){let R=`${Y}/v1${M}`;if(j.query&&Object.keys(j.query).length>0){let A=new URLSearchParams(j.query);R+=`?${A.toString()}`}let f={Authorization:`Bearer ${W}`,Accept:"application/json","User-Agent":Z0,...j.headers};if(j.body!==void 0)f["Content-Type"]="application/json";let P;try{P=await fetch(R,{method:B,headers:f,body:j.body!==void 0?JSON.stringify(j.body):void 0,signal:AbortSignal.timeout(X)})}catch(A){if(A instanceof DOMException&&(A.name==="TimeoutError"||A.name==="AbortError")){let Z1=Math.round(X/1000);throw new q(0,"request_timeout",`Request timed out after ${Z1}s. Check your network connection and server URL.`,"unknown")}let Q1=A instanceof Error?A.message:String(A);throw new q(0,"network_error",`Network error: ${Q1}`,"unknown")}let h;if((P.headers.get("Content-Type")||"").includes("application/json"))try{h=await P.json()}catch{h={}}else h={};let Z=h?.request_id||P.headers.get("X-Request-Id")||"unknown";if(!P.ok){let A=h,I=A.error?.code||"api_error",Q1=A.error?.message||`API request failed with status ${P.status}`;throw new q(P.status,I,Q1,Z,A.error?.details,A.error?.fix_hint)}return{status:P.status,body:h,requestId:Z}}return{async get(B,M){return w("GET",B,M)},async post(B,M){return w("POST",B,M)},async postFormData(B,M,j){let R=`${Y}/v1${B}`;if(j?.query&&Object.keys(j.query).length>0){let A=new URLSearchParams(j.query);R+=`?${A.toString()}`}let f={Authorization:`Bearer ${W}`,Accept:"application/json","User-Agent":Z0,...j?.headers},P;try{P=await fetch(R,{method:"POST",headers:f,body:M,signal:AbortSignal.timeout(X)})}catch(A){if(A instanceof DOMException&&(A.name==="TimeoutError"||A.name==="AbortError")){let Z1=Math.round(X/1000);throw new q(0,"request_timeout",`Request timed out after ${Z1}s. Check your network connection and server URL.`,"unknown")}let Q1=A instanceof Error?A.message:String(A);throw new q(0,"network_error",`Network error: ${Q1}`,"unknown")}let h;if((P.headers.get("Content-Type")||"").includes("application/json"))try{h=await P.json()}catch{h={}}else h={};let Z=h?.request_id||P.headers.get("X-Request-Id")||"unknown";if(!P.ok){let A=h,I=A.error?.code||"api_error",Q1=A.error?.message||`API request failed with status ${P.status}`;throw new q(P.status,I,Q1,Z,A.error?.details,A.error?.fix_hint)}return{status:P.status,body:h,requestId:Z}},request:w}}var b;(function($){$.assertEqual=(Y)=>Y;function W(Y){}$.assertIs=W;function X(Y){throw Error()}$.assertNever=X,$.arrayToEnum=(Y)=>{let w={};for(let B of Y)w[B]=B;return w},$.getValidEnumValues=(Y)=>{let w=$.objectKeys(Y).filter((M)=>typeof Y[Y[M]]!=="number"),B={};for(let M of w)B[M]=Y[M];return $.objectValues(B)},$.objectValues=(Y)=>{return $.objectKeys(Y).map(function(w){return Y[w]})},$.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let w=[];for(let B in Y)if(Object.prototype.hasOwnProperty.call(Y,B))w.push(B);return w},$.find=(Y,w)=>{for(let B of Y)if(w(B))return B;return},$.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&isFinite(Y)&&Math.floor(Y)===Y;function J(Y,w=" | "){return Y.map((B)=>typeof B==="string"?`'${B}'`:B).join(w)}$.joinValues=J,$.jsonStringifyReplacer=(Y,w)=>{if(typeof w==="bigint")return w.toString();return w}})(b||(b={}));var K0;(function($){$.mergeShapes=(W,X)=>{return{...W,...X}}})(K0||(K0={}));var D=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),G1=($)=>{switch(typeof $){case"undefined":return D.undefined;case"string":return D.string;case"number":return isNaN($)?D.nan:D.number;case"boolean":return D.boolean;case"function":return D.function;case"bigint":return D.bigint;case"symbol":return D.symbol;case"object":if(Array.isArray($))return D.array;if($===null)return D.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return D.promise;if(typeof Map<"u"&&$ instanceof Map)return D.map;if(typeof Set<"u"&&$ instanceof Set)return D.set;if(typeof Date<"u"&&$ instanceof Date)return D.date;return D.object;default:return D.unknown}},L=b.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),n4=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class u extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(X)=>{this.issues=[...this.issues,X]},this.addIssues=(X=[])=>{this.issues=[...this.issues,...X]};let W=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,W);else this.__proto__=W;this.name="ZodError",this.issues=$}format($){let W=$||function(Y){return Y.message},X={_errors:[]},J=(Y)=>{for(let w of Y.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)X._errors.push(W(w));else{let B=X,M=0;while(M<w.path.length){let j=w.path[M];if(M!==w.path.length-1)B[j]=B[j]||{_errors:[]};else B[j]=B[j]||{_errors:[]},B[j]._errors.push(W(w));B=B[j],M++}}};return J(this),X}static assert($){if(!($ instanceof u))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(W)=>W.message){let W={},X=[];for(let J of this.issues)if(J.path.length>0)W[J.path[0]]=W[J.path[0]]||[],W[J.path[0]].push($(J));else X.push($(J));return{formErrors:X,fieldErrors:W}}get formErrors(){return this.flatten()}}u.create=($)=>{return new u($)};var E1=($,W)=>{let X;switch($.code){case L.invalid_type:if($.received===D.undefined)X="Required";else X=`Expected ${$.expected}, received ${$.received}`;break;case L.invalid_literal:X=`Invalid literal value, expected ${JSON.stringify($.expected,b.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:X=`Unrecognized key(s) in object: ${b.joinValues($.keys,", ")}`;break;case L.invalid_union:X="Invalid input";break;case L.invalid_union_discriminator:X=`Invalid discriminator value. Expected ${b.joinValues($.options)}`;break;case L.invalid_enum_value:X=`Invalid enum value. Expected ${b.joinValues($.options)}, received '${$.received}'`;break;case L.invalid_arguments:X="Invalid function arguments";break;case L.invalid_return_type:X="Invalid function return type";break;case L.invalid_date:X="Invalid date";break;case L.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(X=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")X=`${X} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)X=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)X=`Invalid input: must end with "${$.validation.endsWith}"`;else b.assertNever($.validation);else if($.validation!=="regex")X=`Invalid ${$.validation}`;else X="Invalid";break;case L.too_small:if($.type==="array")X=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")X=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")X=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")X=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else X="Invalid input";break;case L.too_big:if($.type==="array")X=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")X=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")X=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")X=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")X=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else X="Invalid input";break;case L.custom:X="Invalid input";break;case L.invalid_intersection_types:X="Intersection results could not be merged";break;case L.not_multiple_of:X=`Number must be a multiple of ${$.multipleOf}`;break;case L.not_finite:X="Number must be finite";break;default:X=W.defaultError,b.assertNever($)}return{message:X}},c0=E1;function d4($){c0=$}function $0(){return c0}var W0=($)=>{let{data:W,path:X,errorMaps:J,issueData:Y}=$,w=[...X,...Y.path||[]],B={...Y,path:w};if(Y.message!==void 0)return{...Y,path:w,message:Y.message};let M="",j=J.filter((R)=>!!R).slice().reverse();for(let R of j)M=R(B,{data:W,defaultError:M}).message;return{...Y,path:w,message:M}},p4=[];function K($,W){let X=$0(),J=W0({issueData:W,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,X,X===E1?void 0:E1].filter((Y)=>!!Y)});$.common.issues.push(J)}class l{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,W){let X=[];for(let J of W){if(J.status==="aborted")return S;if(J.status==="dirty")$.dirty();X.push(J.value)}return{status:$.value,value:X}}static async mergeObjectAsync($,W){let X=[];for(let J of W){let Y=await J.key,w=await J.value;X.push({key:Y,value:w})}return l.mergeObjectSync($,X)}static mergeObjectSync($,W){let X={};for(let J of W){let{key:Y,value:w}=J;if(Y.status==="aborted")return S;if(w.status==="aborted")return S;if(Y.status==="dirty")$.dirty();if(w.status==="dirty")$.dirty();if(Y.value!=="__proto__"&&(typeof w.value<"u"||J.alwaysSet))X[Y.value]=w.value}return{status:$.value,value:X}}}var S=Object.freeze({status:"aborted"}),_1=($)=>({status:"dirty",value:$}),c=($)=>({status:"valid",value:$}),U0=($)=>$.status==="aborted",D0=($)=>$.status==="dirty",j1=($)=>$.status==="valid",c1=($)=>typeof Promise<"u"&&$ instanceof Promise;function X0($,W,X,J){if(X==="a"&&!J)throw TypeError("Private accessor was defined without a getter");if(typeof W==="function"?$!==W||!J:!W.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?J:X==="a"?J.call($):J?J.value:W.get($)}function u0($,W,X,J,Y){if(J==="m")throw TypeError("Private method is not writable");if(J==="a"&&!Y)throw TypeError("Private accessor was defined without a setter");if(typeof W==="function"?$!==W||!Y:!W.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return J==="a"?Y.call($,X):Y?Y.value=X:W.set($,X),X}var N;(function($){$.errToObj=(W)=>typeof W==="string"?{message:W}:W||{},$.toString=(W)=>typeof W==="string"?W:W===null||W===void 0?void 0:W.message})(N||(N={}));var y1,l1;class t{constructor($,W,X,J){this._cachedPath=[],this.parent=$,this.data=W,this._path=X,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 y0=($,W)=>{if(j1(W))return{success:!0,data:W.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let X=new u($.common.issues);return this._error=X,this._error}}}};function E($){if(!$)return{};let{errorMap:W,invalid_type_error:X,required_error:J,description:Y}=$;if(W&&(X||J))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(W)return{errorMap:W,description:Y};return{errorMap:(B,M)=>{var j,R;let{message:f}=$;if(B.code==="invalid_enum_value")return{message:f!==null&&f!==void 0?f:M.defaultError};if(typeof M.data>"u")return{message:(j=f!==null&&f!==void 0?f:J)!==null&&j!==void 0?j:M.defaultError};if(B.code!=="invalid_type")return{message:M.defaultError};return{message:(R=f!==null&&f!==void 0?f:X)!==null&&R!==void 0?R:M.defaultError}},description:Y}}class k{get description(){return this._def.description}_getType($){return G1($.data)}_getOrReturnCtx($,W){return W||{common:$.parent.common,data:$.data,parsedType:G1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new l,ctx:{common:$.parent.common,data:$.data,parsedType:G1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let W=this._parse($);if(c1(W))throw Error("Synchronous parse encountered promise.");return W}_parseAsync($){let W=this._parse($);return Promise.resolve(W)}parse($,W){let X=this.safeParse($,W);if(X.success)return X.data;throw X.error}safeParse($,W){var X;let J={common:{issues:[],async:(X=W===null||W===void 0?void 0:W.async)!==null&&X!==void 0?X:!1,contextualErrorMap:W===null||W===void 0?void 0:W.errorMap},path:(W===null||W===void 0?void 0:W.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:G1($)},Y=this._parseSync({data:$,path:J.path,parent:J});return y0(J,Y)}"~validate"($){var W,X;let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:G1($)};if(!this["~standard"].async)try{let Y=this._parseSync({data:$,path:[],parent:J});return j1(Y)?{value:Y.value}:{issues:J.common.issues}}catch(Y){if((X=(W=Y===null||Y===void 0?void 0:Y.message)===null||W===void 0?void 0:W.toLowerCase())===null||X===void 0?void 0:X.includes("encountered"))this["~standard"].async=!0;J.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:J}).then((Y)=>j1(Y)?{value:Y.value}:{issues:J.common.issues})}async parseAsync($,W){let X=await this.safeParseAsync($,W);if(X.success)return X.data;throw X.error}async safeParseAsync($,W){let X={common:{issues:[],contextualErrorMap:W===null||W===void 0?void 0:W.errorMap,async:!0},path:(W===null||W===void 0?void 0:W.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:G1($)},J=this._parse({data:$,path:X.path,parent:X}),Y=await(c1(J)?J:Promise.resolve(J));return y0(X,Y)}refine($,W){let X=(J)=>{if(typeof W==="string"||typeof W>"u")return{message:W};else if(typeof W==="function")return W(J);else return W};return this._refinement((J,Y)=>{let w=$(J),B=()=>Y.addIssue({code:L.custom,...X(J)});if(typeof Promise<"u"&&w instanceof Promise)return w.then((M)=>{if(!M)return B(),!1;else return!0});if(!w)return B(),!1;else return!0})}refinement($,W){return this._refinement((X,J)=>{if(!$(X))return J.addIssue(typeof W==="function"?W(X,J):W),!1;else return!0})}_refinement($){return new d({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(W)=>this["~validate"](W)}}optional(){return a.create(this,this._def)}nullable(){return z1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return o.create(this)}promise(){return U1.create(this,this._def)}or($){return f1.create([this,$],this._def)}and($){return b1.create(this,$,this._def)}transform($){return new d({...E(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:$}})}default($){let W=typeof $==="function"?$:()=>$;return new g1({...E(this._def),innerType:this,defaultValue:W,typeName:_.ZodDefault})}brand(){return new Y0({typeName:_.ZodBranded,type:this,...E(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new x1({...E(this._def),innerType:this,catchValue:W,typeName:_.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return o1.create(this,$)}readonly(){return h1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var i4=/^c[^\s-]{8,}$/i,o4=/^[0-9a-z]+$/,a4=/^[0-9A-HJKMNP-TV-Z]{26}$/i,t4=/^[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,r4=/^[a-z0-9_-]{21}$/i,s4=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,e4=/^[-+]?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)?)??$/,$2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,W2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",F0,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])$/,Y2=/^(([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}(=)?))?$/,n0="((\\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])))",z2=new RegExp(`^${n0}$`);function d0($){let W="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if($.precision)W=`${W}\\.\\d{${$.precision}}`;else if($.precision==null)W=`${W}(\\.\\d+)?`;return W}function w2($){return new RegExp(`^${d0($)}$`)}function p0($){let W=`${n0}T${d0($)}`,X=[];if(X.push($.local?"Z?":"Z"),$.offset)X.push("([+-]\\d{2}:?\\d{2})");return W=`${W}(${X.join("|")})`,new RegExp(`^${W}$`)}function B2($,W){if((W==="v4"||!W)&&X2.test($))return!0;if((W==="v6"||!W)&&Y2.test($))return!0;return!1}function q2($,W){if(!s4.test($))return!1;try{let[X]=$.split("."),J=X.replace(/-/g,"+").replace(/_/g,"/").padEnd(X.length+(4-X.length%4)%4,"="),Y=JSON.parse(atob(J));if(typeof Y!=="object"||Y===null)return!1;if(!Y.typ||!Y.alg)return!1;if(W&&Y.alg!==W)return!1;return!0}catch(X){return!1}}function V2($,W){if((W==="v4"||!W)&&Q2.test($))return!0;if((W==="v6"||!W)&&J2.test($))return!0;return!1}class i extends k{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==D.string){let Y=this._getOrReturnCtx($);return K(Y,{code:L.invalid_type,expected:D.string,received:Y.parsedType}),S}let X=new l,J=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.length<Y.value)J=this._getOrReturnCtx($,J),K(J,{code:L.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if($.data.length>Y.value)J=this._getOrReturnCtx($,J),K(J,{code:L.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="length"){let w=$.data.length>Y.value,B=$.data.length<Y.value;if(w||B){if(J=this._getOrReturnCtx($,J),w)K(J,{code:L.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(B)K(J,{code:L.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});X.dirty()}}else if(Y.kind==="email"){if(!$2.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"email",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="emoji"){if(!F0)F0=new RegExp(W2,"u");if(!F0.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"emoji",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="uuid"){if(!t4.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"uuid",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="nanoid"){if(!r4.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"nanoid",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="cuid"){if(!i4.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"cuid",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="cuid2"){if(!o4.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"cuid2",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="ulid"){if(!a4.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"ulid",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="url")try{new URL($.data)}catch(w){J=this._getOrReturnCtx($,J),K(J,{validation:"url",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"regex",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="trim")$.data=$.data.trim();else if(Y.kind==="includes"){if(!$.data.includes(Y.value,Y.position))J=this._getOrReturnCtx($,J),K(J,{code:L.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),X.dirty()}else if(Y.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(Y.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(Y.kind==="startsWith"){if(!$.data.startsWith(Y.value))J=this._getOrReturnCtx($,J),K(J,{code:L.invalid_string,validation:{startsWith:Y.value},message:Y.message}),X.dirty()}else if(Y.kind==="endsWith"){if(!$.data.endsWith(Y.value))J=this._getOrReturnCtx($,J),K(J,{code:L.invalid_string,validation:{endsWith:Y.value},message:Y.message}),X.dirty()}else if(Y.kind==="datetime"){if(!p0(Y).test($.data))J=this._getOrReturnCtx($,J),K(J,{code:L.invalid_string,validation:"datetime",message:Y.message}),X.dirty()}else if(Y.kind==="date"){if(!z2.test($.data))J=this._getOrReturnCtx($,J),K(J,{code:L.invalid_string,validation:"date",message:Y.message}),X.dirty()}else if(Y.kind==="time"){if(!w2(Y).test($.data))J=this._getOrReturnCtx($,J),K(J,{code:L.invalid_string,validation:"time",message:Y.message}),X.dirty()}else if(Y.kind==="duration"){if(!e4.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"duration",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="ip"){if(!B2($.data,Y.version))J=this._getOrReturnCtx($,J),K(J,{validation:"ip",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="jwt"){if(!q2($.data,Y.alg))J=this._getOrReturnCtx($,J),K(J,{validation:"jwt",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="cidr"){if(!V2($.data,Y.version))J=this._getOrReturnCtx($,J),K(J,{validation:"cidr",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="base64"){if(!H2.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"base64",code:L.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="base64url"){if(!G2.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"base64url",code:L.invalid_string,message:Y.message}),X.dirty()}else b.assertNever(Y);return{status:X.value,value:$.data}}_regex($,W,X){return this.refinement((J)=>$.test(J),{validation:W,code:L.invalid_string,...N.errToObj(X)})}_addCheck($){return new i({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...N.errToObj($)})}url($){return this._addCheck({kind:"url",...N.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...N.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...N.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...N.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...N.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...N.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...N.errToObj($)})}base64($){return this._addCheck({kind:"base64",...N.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...N.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...N.errToObj($)})}ip($){return this._addCheck({kind:"ip",...N.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...N.errToObj($)})}datetime($){var W,X;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)>"u"?null:$===null||$===void 0?void 0:$.precision,offset:(W=$===null||$===void 0?void 0:$.offset)!==null&&W!==void 0?W:!1,local:(X=$===null||$===void 0?void 0:$.local)!==null&&X!==void 0?X:!1,...N.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)>"u"?null:$===null||$===void 0?void 0:$.precision,...N.errToObj($===null||$===void 0?void 0:$.message)})}duration($){return this._addCheck({kind:"duration",...N.errToObj($)})}regex($,W){return this._addCheck({kind:"regex",regex:$,...N.errToObj(W)})}includes($,W){return this._addCheck({kind:"includes",value:$,position:W===null||W===void 0?void 0:W.position,...N.errToObj(W===null||W===void 0?void 0:W.message)})}startsWith($,W){return this._addCheck({kind:"startsWith",value:$,...N.errToObj(W)})}endsWith($,W){return this._addCheck({kind:"endsWith",value:$,...N.errToObj(W)})}min($,W){return this._addCheck({kind:"min",value:$,...N.errToObj(W)})}max($,W){return this._addCheck({kind:"max",value:$,...N.errToObj(W)})}length($,W){return this._addCheck({kind:"length",value:$,...N.errToObj(W)})}nonempty($){return this.min(1,N.errToObj($))}trim(){return new i({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new i({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new i({...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 W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxLength(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}i.create=($)=>{var W;return new i({checks:[],typeName:_.ZodString,coerce:(W=$===null||$===void 0?void 0:$.coerce)!==null&&W!==void 0?W:!1,...E($)})};function M2($,W){let X=($.toString().split(".")[1]||"").length,J=(W.toString().split(".")[1]||"").length,Y=X>J?X:J,w=parseInt($.toFixed(Y).replace(".","")),B=parseInt(W.toFixed(Y).replace(".",""));return w%B/Math.pow(10,Y)}class B1 extends k{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($)!==D.number){let Y=this._getOrReturnCtx($);return K(Y,{code:L.invalid_type,expected:D.number,received:Y.parsedType}),S}let X=void 0,J=new l;for(let Y of this._def.checks)if(Y.kind==="int"){if(!b.isInteger($.data))X=this._getOrReturnCtx($,X),K(X,{code:L.invalid_type,expected:"integer",received:"float",message:Y.message}),J.dirty()}else if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)X=this._getOrReturnCtx($,X),K(X,{code:L.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),J.dirty()}else if(Y.kind==="max"){if(Y.inclusive?$.data>Y.value:$.data>=Y.value)X=this._getOrReturnCtx($,X),K(X,{code:L.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),J.dirty()}else if(Y.kind==="multipleOf"){if(M2($.data,Y.value)!==0)X=this._getOrReturnCtx($,X),K(X,{code:L.not_multiple_of,multipleOf:Y.value,message:Y.message}),J.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite($.data))X=this._getOrReturnCtx($,X),K(X,{code:L.not_finite,message:Y.message}),J.dirty()}else b.assertNever(Y);return{status:J.value,value:$.data}}gte($,W){return this.setLimit("min",$,!0,N.toString(W))}gt($,W){return this.setLimit("min",$,!1,N.toString(W))}lte($,W){return this.setLimit("max",$,!0,N.toString(W))}lt($,W){return this.setLimit("max",$,!1,N.toString(W))}setLimit($,W,X,J){return new B1({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:X,message:N.toString(J)}]})}_addCheck($){return new B1({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:N.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:N.toString(W)})}finite($){return this._addCheck({kind:"finite",message:N.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString($)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&b.isInteger($.value))}get isFinite(){let $=null,W=null;for(let X of this._def.checks)if(X.kind==="finite"||X.kind==="int"||X.kind==="multipleOf")return!0;else if(X.kind==="min"){if(W===null||X.value>W)W=X.value}else if(X.kind==="max"){if($===null||X.value<$)$=X.value}return Number.isFinite(W)&&Number.isFinite($)}}B1.create=($)=>{return new B1({checks:[],typeName:_.ZodNumber,coerce:($===null||$===void 0?void 0:$.coerce)||!1,...E($)})};class q1 extends k{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch(Y){return this._getInvalidInput($)}if(this._getType($)!==D.bigint)return this._getInvalidInput($);let X=void 0,J=new l;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)X=this._getOrReturnCtx($,X),K(X,{code:L.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),J.dirty()}else if(Y.kind==="max"){if(Y.inclusive?$.data>Y.value:$.data>=Y.value)X=this._getOrReturnCtx($,X),K(X,{code:L.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),J.dirty()}else if(Y.kind==="multipleOf"){if($.data%Y.value!==BigInt(0))X=this._getOrReturnCtx($,X),K(X,{code:L.not_multiple_of,multipleOf:Y.value,message:Y.message}),J.dirty()}else b.assertNever(Y);return{status:J.value,value:$.data}}_getInvalidInput($){let W=this._getOrReturnCtx($);return K(W,{code:L.invalid_type,expected:D.bigint,received:W.parsedType}),S}gte($,W){return this.setLimit("min",$,!0,N.toString(W))}gt($,W){return this.setLimit("min",$,!1,N.toString(W))}lte($,W){return this.setLimit("max",$,!0,N.toString(W))}lt($,W){return this.setLimit("max",$,!1,N.toString(W))}setLimit($,W,X,J){return new q1({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:X,message:N.toString(J)}]})}_addCheck($){return new q1({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:N.toString(W)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}q1.create=($)=>{var W;return new q1({checks:[],typeName:_.ZodBigInt,coerce:(W=$===null||$===void 0?void 0:$.coerce)!==null&&W!==void 0?W:!1,...E($)})};class v1 extends k{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==D.boolean){let X=this._getOrReturnCtx($);return K(X,{code:L.invalid_type,expected:D.boolean,received:X.parsedType}),S}return c($.data)}}v1.create=($)=>{return new v1({typeName:_.ZodBoolean,coerce:($===null||$===void 0?void 0:$.coerce)||!1,...E($)})};class L1 extends k{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==D.date){let Y=this._getOrReturnCtx($);return K(Y,{code:L.invalid_type,expected:D.date,received:Y.parsedType}),S}if(isNaN($.data.getTime())){let Y=this._getOrReturnCtx($);return K(Y,{code:L.invalid_date}),S}let X=new l,J=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.getTime()<Y.value)J=this._getOrReturnCtx($,J),K(J,{code:L.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),X.dirty()}else if(Y.kind==="max"){if($.data.getTime()>Y.value)J=this._getOrReturnCtx($,J),K(J,{code:L.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),X.dirty()}else b.assertNever(Y);return{status:X.value,value:new Date($.data.getTime())}}_addCheck($){return new L1({...this._def,checks:[...this._def.checks,$]})}min($,W){return this._addCheck({kind:"min",value:$.getTime(),message:N.toString(W)})}max($,W){return this._addCheck({kind:"max",value:$.getTime(),message:N.toString(W)})}get minDate(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $!=null?new Date($):null}}L1.create=($)=>{return new L1({checks:[],coerce:($===null||$===void 0?void 0:$.coerce)||!1,typeName:_.ZodDate,...E($)})};class u1 extends k{_parse($){if(this._getType($)!==D.symbol){let X=this._getOrReturnCtx($);return K(X,{code:L.invalid_type,expected:D.symbol,received:X.parsedType}),S}return c($.data)}}u1.create=($)=>{return new u1({typeName:_.ZodSymbol,...E($)})};class k1 extends k{_parse($){if(this._getType($)!==D.undefined){let X=this._getOrReturnCtx($);return K(X,{code:L.invalid_type,expected:D.undefined,received:X.parsedType}),S}return c($.data)}}k1.create=($)=>{return new k1({typeName:_.ZodUndefined,...E($)})};class C1 extends k{_parse($){if(this._getType($)!==D.null){let X=this._getOrReturnCtx($);return K(X,{code:L.invalid_type,expected:D.null,received:X.parsedType}),S}return c($.data)}}C1.create=($)=>{return new C1({typeName:_.ZodNull,...E($)})};class F1 extends k{constructor(){super(...arguments);this._any=!0}_parse($){return c($.data)}}F1.create=($)=>{return new F1({typeName:_.ZodAny,...E($)})};class w1 extends k{constructor(){super(...arguments);this._unknown=!0}_parse($){return c($.data)}}w1.create=($)=>{return new w1({typeName:_.ZodUnknown,...E($)})};class $1 extends k{_parse($){let W=this._getOrReturnCtx($);return K(W,{code:L.invalid_type,expected:D.never,received:W.parsedType}),S}}$1.create=($)=>{return new $1({typeName:_.ZodNever,...E($)})};class n1 extends k{_parse($){if(this._getType($)!==D.undefined){let X=this._getOrReturnCtx($);return K(X,{code:L.invalid_type,expected:D.void,received:X.parsedType}),S}return c($.data)}}n1.create=($)=>{return new n1({typeName:_.ZodVoid,...E($)})};class o extends k{_parse($){let{ctx:W,status:X}=this._processInputParams($),J=this._def;if(W.parsedType!==D.array)return K(W,{code:L.invalid_type,expected:D.array,received:W.parsedType}),S;if(J.exactLength!==null){let w=W.data.length>J.exactLength.value,B=W.data.length<J.exactLength.value;if(w||B)K(W,{code:w?L.too_big:L.too_small,minimum:B?J.exactLength.value:void 0,maximum:w?J.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:J.exactLength.message}),X.dirty()}if(J.minLength!==null){if(W.data.length<J.minLength.value)K(W,{code:L.too_small,minimum:J.minLength.value,type:"array",inclusive:!0,exact:!1,message:J.minLength.message}),X.dirty()}if(J.maxLength!==null){if(W.data.length>J.maxLength.value)K(W,{code:L.too_big,maximum:J.maxLength.value,type:"array",inclusive:!0,exact:!1,message:J.maxLength.message}),X.dirty()}if(W.common.async)return Promise.all([...W.data].map((w,B)=>{return J.type._parseAsync(new t(W,w,W.path,B))})).then((w)=>{return l.mergeArray(X,w)});let Y=[...W.data].map((w,B)=>{return J.type._parseSync(new t(W,w,W.path,B))});return l.mergeArray(X,Y)}get element(){return this._def.type}min($,W){return new o({...this._def,minLength:{value:$,message:N.toString(W)}})}max($,W){return new o({...this._def,maxLength:{value:$,message:N.toString(W)}})}length($,W){return new o({...this._def,exactLength:{value:$,message:N.toString(W)}})}nonempty($){return this.min(1,$)}}o.create=($,W)=>{return new o({type:$,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...E(W)})};function A1($){if($ instanceof x){let W={};for(let X in $.shape){let J=$.shape[X];W[X]=a.create(A1(J))}return new x({...$._def,shape:()=>W})}else if($ instanceof o)return new o({...$._def,type:A1($.element)});else if($ instanceof a)return a.create(A1($.unwrap()));else if($ instanceof z1)return z1.create(A1($.unwrap()));else if($ instanceof W1)return W1.create($.items.map((W)=>A1(W)));else return $}class x extends k{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(),W=b.objectKeys($);return this._cached={shape:$,keys:W}}_parse($){if(this._getType($)!==D.object){let j=this._getOrReturnCtx($);return K(j,{code:L.invalid_type,expected:D.object,received:j.parsedType}),S}let{status:X,ctx:J}=this._processInputParams($),{shape:Y,keys:w}=this._getCached(),B=[];if(!(this._def.catchall instanceof $1&&this._def.unknownKeys==="strip")){for(let j in J.data)if(!w.includes(j))B.push(j)}let M=[];for(let j of w){let R=Y[j],f=J.data[j];M.push({key:{status:"valid",value:j},value:R._parse(new t(J,f,J.path,j)),alwaysSet:j in J.data})}if(this._def.catchall instanceof $1){let j=this._def.unknownKeys;if(j==="passthrough")for(let R of B)M.push({key:{status:"valid",value:R},value:{status:"valid",value:J.data[R]}});else if(j==="strict"){if(B.length>0)K(J,{code:L.unrecognized_keys,keys:B}),X.dirty()}else if(j==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let j=this._def.catchall;for(let R of B){let f=J.data[R];M.push({key:{status:"valid",value:R},value:j._parse(new t(J,f,J.path,R)),alwaysSet:R in J.data})}}if(J.common.async)return Promise.resolve().then(async()=>{let j=[];for(let R of M){let f=await R.key,P=await R.value;j.push({key:f,value:P,alwaysSet:R.alwaysSet})}return j}).then((j)=>{return l.mergeObjectSync(X,j)});else return l.mergeObjectSync(X,M)}get shape(){return this._def.shape()}strict($){return N.errToObj,new x({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(W,X)=>{var J,Y,w,B;let M=(w=(Y=(J=this._def).errorMap)===null||Y===void 0?void 0:Y.call(J,W,X).message)!==null&&w!==void 0?w:X.defaultError;if(W.code==="unrecognized_keys")return{message:(B=N.errToObj($).message)!==null&&B!==void 0?B:M};return{message:M}}}:{}})}strip(){return new x({...this._def,unknownKeys:"strip"})}passthrough(){return new x({...this._def,unknownKeys:"passthrough"})}extend($){return new x({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new x({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:_.ZodObject})}setKey($,W){return this.augment({[$]:W})}catchall($){return new x({...this._def,catchall:$})}pick($){let W={};return b.objectKeys($).forEach((X)=>{if($[X]&&this.shape[X])W[X]=this.shape[X]}),new x({...this._def,shape:()=>W})}omit($){let W={};return b.objectKeys(this.shape).forEach((X)=>{if(!$[X])W[X]=this.shape[X]}),new x({...this._def,shape:()=>W})}deepPartial(){return A1(this)}partial($){let W={};return b.objectKeys(this.shape).forEach((X)=>{let J=this.shape[X];if($&&!$[X])W[X]=J;else W[X]=J.optional()}),new x({...this._def,shape:()=>W})}required($){let W={};return b.objectKeys(this.shape).forEach((X)=>{if($&&!$[X])W[X]=this.shape[X];else{let Y=this.shape[X];while(Y instanceof a)Y=Y._def.innerType;W[X]=Y}}),new x({...this._def,shape:()=>W})}keyof(){return i0(b.objectKeys(this.shape))}}x.create=($,W)=>{return new x({shape:()=>$,unknownKeys:"strip",catchall:$1.create(),typeName:_.ZodObject,...E(W)})};x.strictCreate=($,W)=>{return new x({shape:()=>$,unknownKeys:"strict",catchall:$1.create(),typeName:_.ZodObject,...E(W)})};x.lazycreate=($,W)=>{return new x({shape:$,unknownKeys:"strip",catchall:$1.create(),typeName:_.ZodObject,...E(W)})};class f1 extends k{_parse($){let{ctx:W}=this._processInputParams($),X=this._def.options;function J(Y){for(let B of Y)if(B.result.status==="valid")return B.result;for(let B of Y)if(B.result.status==="dirty")return W.common.issues.push(...B.ctx.common.issues),B.result;let w=Y.map((B)=>new u(B.ctx.common.issues));return K(W,{code:L.invalid_union,unionErrors:w}),S}if(W.common.async)return Promise.all(X.map(async(Y)=>{let w={...W,common:{...W.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:W.data,path:W.path,parent:w}),ctx:w}})).then(J);else{let Y=void 0,w=[];for(let M of X){let j={...W,common:{...W.common,issues:[]},parent:null},R=M._parseSync({data:W.data,path:W.path,parent:j});if(R.status==="valid")return R;else if(R.status==="dirty"&&!Y)Y={result:R,ctx:j};if(j.common.issues.length)w.push(j.common.issues)}if(Y)return W.common.issues.push(...Y.ctx.common.issues),Y.result;let B=w.map((M)=>new u(M));return K(W,{code:L.invalid_union,unionErrors:B}),S}}get options(){return this._def.options}}f1.create=($,W)=>{return new f1({options:$,typeName:_.ZodUnion,...E(W)})};var H1=($)=>{if($ instanceof P1)return H1($.schema);else if($ instanceof d)return H1($.innerType());else if($ instanceof I1)return[$.value];else if($ instanceof V1)return $.options;else if($ instanceof T1)return b.objectValues($.enum);else if($ instanceof g1)return H1($._def.innerType);else if($ instanceof k1)return[void 0];else if($ instanceof C1)return[null];else if($ instanceof a)return[void 0,...H1($.unwrap())];else if($ instanceof z1)return[null,...H1($.unwrap())];else if($ instanceof Y0)return H1($.unwrap());else if($ instanceof h1)return H1($.unwrap());else if($ instanceof x1)return H1($._def.innerType);else return[]};class Q0 extends k{_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==D.object)return K(W,{code:L.invalid_type,expected:D.object,received:W.parsedType}),S;let X=this.discriminator,J=W.data[X],Y=this.optionsMap.get(J);if(!Y)return K(W,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[X]}),S;if(W.common.async)return Y._parseAsync({data:W.data,path:W.path,parent:W});else return Y._parseSync({data:W.data,path:W.path,parent:W})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,W,X){let J=new Map;for(let Y of W){let w=H1(Y.shape[$]);if(!w.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let B of w){if(J.has(B))throw Error(`Discriminator property ${String($)} has duplicate value ${String(B)}`);J.set(B,Y)}}return new Q0({typeName:_.ZodDiscriminatedUnion,discriminator:$,options:W,optionsMap:J,...E(X)})}}function R0($,W){let X=G1($),J=G1(W);if($===W)return{valid:!0,data:$};else if(X===D.object&&J===D.object){let Y=b.objectKeys(W),w=b.objectKeys($).filter((M)=>Y.indexOf(M)!==-1),B={...$,...W};for(let M of w){let j=R0($[M],W[M]);if(!j.valid)return{valid:!1};B[M]=j.data}return{valid:!0,data:B}}else if(X===D.array&&J===D.array){if($.length!==W.length)return{valid:!1};let Y=[];for(let w=0;w<$.length;w++){let B=$[w],M=W[w],j=R0(B,M);if(!j.valid)return{valid:!1};Y.push(j.data)}return{valid:!0,data:Y}}else if(X===D.date&&J===D.date&&+$===+W)return{valid:!0,data:$};else return{valid:!1}}class b1 extends k{_parse($){let{status:W,ctx:X}=this._processInputParams($),J=(Y,w)=>{if(U0(Y)||U0(w))return S;let B=R0(Y.value,w.value);if(!B.valid)return K(X,{code:L.invalid_intersection_types}),S;if(D0(Y)||D0(w))W.dirty();return{status:W.value,value:B.data}};if(X.common.async)return Promise.all([this._def.left._parseAsync({data:X.data,path:X.path,parent:X}),this._def.right._parseAsync({data:X.data,path:X.path,parent:X})]).then(([Y,w])=>J(Y,w));else return J(this._def.left._parseSync({data:X.data,path:X.path,parent:X}),this._def.right._parseSync({data:X.data,path:X.path,parent:X}))}}b1.create=($,W,X)=>{return new b1({left:$,right:W,typeName:_.ZodIntersection,...E(X)})};class W1 extends k{_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==D.array)return K(X,{code:L.invalid_type,expected:D.array,received:X.parsedType}),S;if(X.data.length<this._def.items.length)return K(X,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;if(!this._def.rest&&X.data.length>this._def.items.length)K(X,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W.dirty();let Y=[...X.data].map((w,B)=>{let M=this._def.items[B]||this._def.rest;if(!M)return null;return M._parse(new t(X,w,X.path,B))}).filter((w)=>!!w);if(X.common.async)return Promise.all(Y).then((w)=>{return l.mergeArray(W,w)});else return l.mergeArray(W,Y)}get items(){return this._def.items}rest($){return new W1({...this._def,rest:$})}}W1.create=($,W)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new W1({items:$,typeName:_.ZodTuple,rest:null,...E(W)})};class d1 extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==D.object)return K(X,{code:L.invalid_type,expected:D.object,received:X.parsedType}),S;let J=[],Y=this._def.keyType,w=this._def.valueType;for(let B in X.data)J.push({key:Y._parse(new t(X,B,X.path,B)),value:w._parse(new t(X,X.data[B],X.path,B)),alwaysSet:B in X.data});if(X.common.async)return l.mergeObjectAsync(W,J);else return l.mergeObjectSync(W,J)}get element(){return this._def.valueType}static create($,W,X){if(W instanceof k)return new d1({keyType:$,valueType:W,typeName:_.ZodRecord,...E(X)});return new d1({keyType:i.create(),valueType:$,typeName:_.ZodRecord,...E(W)})}}class p1 extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==D.map)return K(X,{code:L.invalid_type,expected:D.map,received:X.parsedType}),S;let J=this._def.keyType,Y=this._def.valueType,w=[...X.data.entries()].map(([B,M],j)=>{return{key:J._parse(new t(X,B,X.path,[j,"key"])),value:Y._parse(new t(X,M,X.path,[j,"value"]))}});if(X.common.async){let B=new Map;return Promise.resolve().then(async()=>{for(let M of w){let j=await M.key,R=await M.value;if(j.status==="aborted"||R.status==="aborted")return S;if(j.status==="dirty"||R.status==="dirty")W.dirty();B.set(j.value,R.value)}return{status:W.value,value:B}})}else{let B=new Map;for(let M of w){let{key:j,value:R}=M;if(j.status==="aborted"||R.status==="aborted")return S;if(j.status==="dirty"||R.status==="dirty")W.dirty();B.set(j.value,R.value)}return{status:W.value,value:B}}}}p1.create=($,W,X)=>{return new p1({valueType:W,keyType:$,typeName:_.ZodMap,...E(X)})};class K1 extends k{_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==D.set)return K(X,{code:L.invalid_type,expected:D.set,received:X.parsedType}),S;let J=this._def;if(J.minSize!==null){if(X.data.size<J.minSize.value)K(X,{code:L.too_small,minimum:J.minSize.value,type:"set",inclusive:!0,exact:!1,message:J.minSize.message}),W.dirty()}if(J.maxSize!==null){if(X.data.size>J.maxSize.value)K(X,{code:L.too_big,maximum:J.maxSize.value,type:"set",inclusive:!0,exact:!1,message:J.maxSize.message}),W.dirty()}let Y=this._def.valueType;function w(M){let j=new Set;for(let R of M){if(R.status==="aborted")return S;if(R.status==="dirty")W.dirty();j.add(R.value)}return{status:W.value,value:j}}let B=[...X.data.values()].map((M,j)=>Y._parse(new t(X,M,X.path,j)));if(X.common.async)return Promise.all(B).then((M)=>w(M));else return w(B)}min($,W){return new K1({...this._def,minSize:{value:$,message:N.toString(W)}})}max($,W){return new K1({...this._def,maxSize:{value:$,message:N.toString(W)}})}size($,W){return this.min($,W).max($,W)}nonempty($){return this.min(1,$)}}K1.create=($,W)=>{return new K1({valueType:$,minSize:null,maxSize:null,typeName:_.ZodSet,...E(W)})};class S1 extends k{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==D.function)return K(W,{code:L.invalid_type,expected:D.function,received:W.parsedType}),S;function X(B,M){return W0({data:B,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,$0(),E1].filter((j)=>!!j),issueData:{code:L.invalid_arguments,argumentsError:M}})}function J(B,M){return W0({data:B,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,$0(),E1].filter((j)=>!!j),issueData:{code:L.invalid_return_type,returnTypeError:M}})}let Y={errorMap:W.common.contextualErrorMap},w=W.data;if(this._def.returns instanceof U1){let B=this;return c(async function(...M){let j=new u([]),R=await B._def.args.parseAsync(M,Y).catch((h)=>{throw j.addIssue(X(M,h)),j}),f=await Reflect.apply(w,this,R);return await B._def.returns._def.type.parseAsync(f,Y).catch((h)=>{throw j.addIssue(J(f,h)),j})})}else{let B=this;return c(function(...M){let j=B._def.args.safeParse(M,Y);if(!j.success)throw new u([X(M,j.error)]);let R=Reflect.apply(w,this,j.data),f=B._def.returns.safeParse(R,Y);if(!f.success)throw new u([J(R,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new S1({...this._def,args:W1.create($).rest(w1.create())})}returns($){return new S1({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,W,X){return new S1({args:$?$:W1.create([]).rest(w1.create()),returns:W||w1.create(),typeName:_.ZodFunction,...E(X)})}}class P1 extends k{get schema(){return this._def.getter()}_parse($){let{ctx:W}=this._processInputParams($);return this._def.getter()._parse({data:W.data,path:W.path,parent:W})}}P1.create=($,W)=>{return new P1({getter:$,typeName:_.ZodLazy,...E(W)})};class I1 extends k{_parse($){if($.data!==this._def.value){let W=this._getOrReturnCtx($);return K(W,{received:W.data,code:L.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:$.data}}get value(){return this._def.value}}I1.create=($,W)=>{return new I1({value:$,typeName:_.ZodLiteral,...E(W)})};function i0($,W){return new V1({values:$,typeName:_.ZodEnum,...E(W)})}class V1 extends k{constructor(){super(...arguments);y1.set(this,void 0)}_parse($){if(typeof $.data!=="string"){let W=this._getOrReturnCtx($),X=this._def.values;return K(W,{expected:b.joinValues(X),received:W.parsedType,code:L.invalid_type}),S}if(!X0(this,y1,"f"))u0(this,y1,new Set(this._def.values),"f");if(!X0(this,y1,"f").has($.data)){let W=this._getOrReturnCtx($),X=this._def.values;return K(W,{received:W.data,code:L.invalid_enum_value,options:X}),S}return c($.data)}get options(){return this._def.values}get enum(){let $={};for(let W of this._def.values)$[W]=W;return $}get Values(){let $={};for(let W of this._def.values)$[W]=W;return $}get Enum(){let $={};for(let W of this._def.values)$[W]=W;return $}extract($,W=this._def){return V1.create($,{...this._def,...W})}exclude($,W=this._def){return V1.create(this.options.filter((X)=>!$.includes(X)),{...this._def,...W})}}y1=new WeakMap;V1.create=i0;class T1 extends k{constructor(){super(...arguments);l1.set(this,void 0)}_parse($){let W=b.getValidEnumValues(this._def.values),X=this._getOrReturnCtx($);if(X.parsedType!==D.string&&X.parsedType!==D.number){let J=b.objectValues(W);return K(X,{expected:b.joinValues(J),received:X.parsedType,code:L.invalid_type}),S}if(!X0(this,l1,"f"))u0(this,l1,new Set(b.getValidEnumValues(this._def.values)),"f");if(!X0(this,l1,"f").has($.data)){let J=b.objectValues(W);return K(X,{received:X.data,code:L.invalid_enum_value,options:J}),S}return c($.data)}get enum(){return this._def.values}}l1=new WeakMap;T1.create=($,W)=>{return new T1({values:$,typeName:_.ZodNativeEnum,...E(W)})};class U1 extends k{unwrap(){return this._def.type}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==D.promise&&W.common.async===!1)return K(W,{code:L.invalid_type,expected:D.promise,received:W.parsedType}),S;let X=W.parsedType===D.promise?W.data:Promise.resolve(W.data);return c(X.then((J)=>{return this._def.type.parseAsync(J,{path:W.path,errorMap:W.common.contextualErrorMap})}))}}U1.create=($,W)=>{return new U1({type:$,typeName:_.ZodPromise,...E(W)})};class d extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:W,ctx:X}=this._processInputParams($),J=this._def.effect||null,Y={addIssue:(w)=>{if(K(X,w),w.fatal)W.abort();else W.dirty()},get path(){return X.path}};if(Y.addIssue=Y.addIssue.bind(Y),J.type==="preprocess"){let w=J.transform(X.data,Y);if(X.common.async)return Promise.resolve(w).then(async(B)=>{if(W.value==="aborted")return S;let M=await this._def.schema._parseAsync({data:B,path:X.path,parent:X});if(M.status==="aborted")return S;if(M.status==="dirty")return _1(M.value);if(W.value==="dirty")return _1(M.value);return M});else{if(W.value==="aborted")return S;let B=this._def.schema._parseSync({data:w,path:X.path,parent:X});if(B.status==="aborted")return S;if(B.status==="dirty")return _1(B.value);if(W.value==="dirty")return _1(B.value);return B}}if(J.type==="refinement"){let w=(B)=>{let M=J.refinement(B,Y);if(X.common.async)return Promise.resolve(M);if(M instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return B};if(X.common.async===!1){let B=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(B.status==="aborted")return S;if(B.status==="dirty")W.dirty();return w(B.value),{status:W.value,value:B.value}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((B)=>{if(B.status==="aborted")return S;if(B.status==="dirty")W.dirty();return w(B.value).then(()=>{return{status:W.value,value:B.value}})})}if(J.type==="transform")if(X.common.async===!1){let w=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(!j1(w))return w;let B=J.transform(w.value,Y);if(B instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:W.value,value:B}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((w)=>{if(!j1(w))return w;return Promise.resolve(J.transform(w.value,Y)).then((B)=>({status:W.value,value:B}))});b.assertNever(J)}}d.create=($,W,X)=>{return new d({schema:$,typeName:_.ZodEffects,effect:W,...E(X)})};d.createWithPreprocess=($,W,X)=>{return new d({schema:W,effect:{type:"preprocess",transform:$},typeName:_.ZodEffects,...E(X)})};class a extends k{_parse($){if(this._getType($)===D.undefined)return c(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}a.create=($,W)=>{return new a({innerType:$,typeName:_.ZodOptional,...E(W)})};class z1 extends k{_parse($){if(this._getType($)===D.null)return c(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}z1.create=($,W)=>{return new z1({innerType:$,typeName:_.ZodNullable,...E(W)})};class g1 extends k{_parse($){let{ctx:W}=this._processInputParams($),X=W.data;if(W.parsedType===D.undefined)X=this._def.defaultValue();return this._def.innerType._parse({data:X,path:W.path,parent:W})}removeDefault(){return this._def.innerType}}g1.create=($,W)=>{return new g1({innerType:$,typeName:_.ZodDefault,defaultValue:typeof W.default==="function"?W.default:()=>W.default,...E(W)})};class x1 extends k{_parse($){let{ctx:W}=this._processInputParams($),X={...W,common:{...W.common,issues:[]}},J=this._def.innerType._parse({data:X.data,path:X.path,parent:{...X}});if(c1(J))return J.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new u(X.common.issues)},input:X.data})}});else return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new u(X.common.issues)},input:X.data})}}removeCatch(){return this._def.innerType}}x1.create=($,W)=>{return new x1({innerType:$,typeName:_.ZodCatch,catchValue:typeof W.catch==="function"?W.catch:()=>W.catch,...E(W)})};class i1 extends k{_parse($){if(this._getType($)!==D.nan){let X=this._getOrReturnCtx($);return K(X,{code:L.invalid_type,expected:D.nan,received:X.parsedType}),S}return{status:"valid",value:$.data}}}i1.create=($)=>{return new i1({typeName:_.ZodNaN,...E($)})};var O2=Symbol("zod_brand");class Y0 extends k{_parse($){let{ctx:W}=this._processInputParams($),X=W.data;return this._def.type._parse({data:X,path:W.path,parent:W})}unwrap(){return this._def.type}}class o1 extends k{_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:X.data,path:X.path,parent:X});if(Y.status==="aborted")return S;if(Y.status==="dirty")return W.dirty(),_1(Y.value);else return this._def.out._parseAsync({data:Y.value,path:X.path,parent:X})})();else{let J=this._def.in._parseSync({data:X.data,path:X.path,parent:X});if(J.status==="aborted")return S;if(J.status==="dirty")return W.dirty(),{status:"dirty",value:J.value};else return this._def.out._parseSync({data:J.value,path:X.path,parent:X})}}static create($,W){return new o1({in:$,out:W,typeName:_.ZodPipeline})}}class h1 extends k{_parse($){let W=this._def.innerType._parse($),X=(J)=>{if(j1(J))J.value=Object.freeze(J.value);return J};return c1(W)?W.then((J)=>X(J)):X(W)}unwrap(){return this._def.innerType}}h1.create=($,W)=>{return new h1({innerType:$,typeName:_.ZodReadonly,...E(W)})};function o0($,W={},X){if($)return F1.create().superRefine((J,Y)=>{var w,B;if(!$(J)){let M=typeof W==="function"?W(J):typeof W==="string"?{message:W}:W,j=(B=(w=M.fatal)!==null&&w!==void 0?w:X)!==null&&B!==void 0?B:!0,R=typeof M==="string"?{message:M}:M;Y.addIssue({code:"custom",...R,fatal:j})}});return F1.create()}var j2={object:x.lazycreate},_;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(_||(_={}));var L2=($,W={message:`Input not instance of ${$.name}`})=>o0((X)=>X instanceof $,W),a0=i.create,t0=B1.create,F2=i1.create,K2=q1.create,r0=v1.create,U2=L1.create,D2=u1.create,R2=k1.create,N2=C1.create,A2=F1.create,_2=w1.create,S2=$1.create,E2=n1.create,v2=o.create,k2=x.create,C2=x.strictCreate,f2=f1.create,b2=Q0.create,P2=b1.create,I2=W1.create,T2=d1.create,g2=p1.create,x2=K1.create,h2=S1.create,Z2=P1.create,m2=I1.create,y2=V1.create,l2=T1.create,c2=U1.create,l0=d.create,u2=a.create,n2=z1.create,d2=d.createWithPreprocess,p2=o1.create,i2=()=>a0().optional(),o2=()=>t0().optional(),a2=()=>r0().optional(),t2={string:($)=>i.create({...$,coerce:!0}),number:($)=>B1.create({...$,coerce:!0}),boolean:($)=>v1.create({...$,coerce:!0}),bigint:($)=>q1.create({...$,coerce:!0}),date:($)=>L1.create({...$,coerce:!0})},r2=S,H=Object.freeze({__proto__:null,defaultErrorMap:E1,setErrorMap:d4,getErrorMap:$0,makeIssue:W0,EMPTY_PATH:p4,addIssueToContext:K,ParseStatus:l,INVALID:S,DIRTY:_1,OK:c,isAborted:U0,isDirty:D0,isValid:j1,isAsync:c1,get util(){return b},get objectUtil(){return K0},ZodParsedType:D,getParsedType:G1,ZodType:k,datetimeRegex:p0,ZodString:i,ZodNumber:B1,ZodBigInt:q1,ZodBoolean:v1,ZodDate:L1,ZodSymbol:u1,ZodUndefined:k1,ZodNull:C1,ZodAny:F1,ZodUnknown:w1,ZodNever:$1,ZodVoid:n1,ZodArray:o,ZodObject:x,ZodUnion:f1,ZodDiscriminatedUnion:Q0,ZodIntersection:b1,ZodTuple:W1,ZodRecord:d1,ZodMap:p1,ZodSet:K1,ZodFunction:S1,ZodLazy:P1,ZodLiteral:I1,ZodEnum:V1,ZodNativeEnum:T1,ZodPromise:U1,ZodEffects:d,ZodTransformer:d,ZodOptional:a,ZodNullable:z1,ZodDefault:g1,ZodCatch:x1,ZodNaN:i1,BRAND:O2,ZodBranded:Y0,ZodPipeline:o1,ZodReadonly:h1,custom:o0,Schema:k,ZodSchema:k,late:j2,get ZodFirstPartyTypeKind(){return _},coerce:t2,any:A2,array:v2,bigint:K2,boolean:r0,date:U2,discriminatedUnion:b2,effect:l0,enum:y2,function:h2,instanceof:L2,intersection:P2,lazy:Z2,literal:m2,map:g2,nan:F2,nativeEnum:l2,never:S2,null:N2,nullable:n2,number:t0,object:k2,oboolean:a2,onumber:o2,optional:u2,ostring:i2,pipeline:p2,preprocess:d2,promise:c2,record:T2,set:x2,strictObject:C2,string:a0,symbol:D2,transformer:l0,tuple:I2,undefined:R2,union:f2,unknown:_2,void:E2,NEVER:r2,ZodIssueCode:L,quotelessJson:n4,ZodError:u});var N0="2024-11-05",s0=[N0,"2024-10-07"],J0="2.0",e0=H.union([H.string(),H.number().int()]),$4=H.string(),r=H.object({_meta:H.optional(H.object({progressToken:H.optional(e0)}).passthrough())}).passthrough(),n=H.object({method:H.string(),params:H.optional(r)}),a1=H.object({_meta:H.optional(H.object({}).passthrough())}).passthrough(),X1=H.object({method:H.string(),params:H.optional(a1)}),s=H.object({_meta:H.optional(H.object({}).passthrough())}).passthrough(),H0=H.union([H.string(),H.number().int()]),s2=H.object({jsonrpc:H.literal(J0),id:H0}).merge(n).strict(),e2=H.object({jsonrpc:H.literal(J0)}).merge(X1).strict(),$9=H.object({jsonrpc:H.literal(J0),id:H0,result:s}).strict(),D1;(function($){$[$.ConnectionClosed=-1]="ConnectionClosed",$[$.RequestTimeout=-2]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError"})(D1||(D1={}));var W9=H.object({jsonrpc:H.literal(J0),id:H0,error:H.object({code:H.number().int(),message:H.string(),data:H.optional(H.unknown())})}).strict(),W4=H.union([s2,e2,$9,W9]),G0=s.strict(),z0=X1.extend({method:H.literal("notifications/cancelled"),params:a1.extend({requestId:H0,reason:H.string().optional()})}),X4=H.object({name:H.string(),version:H.string()}).passthrough(),X9=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(),A0=n.extend({method:H.literal("initialize"),params:r.extend({protocolVersion:H.string(),capabilities:X9,clientInfo:X4})}),Q9=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(),Y9=s.extend({protocolVersion:H.string(),capabilities:Q9,serverInfo:X4}),_0=X1.extend({method:H.literal("notifications/initialized")}),w0=n.extend({method:H.literal("ping")}),J9=H.object({progress:H.number(),total:H.optional(H.number())}).passthrough(),B0=X1.extend({method:H.literal("notifications/progress"),params:a1.merge(J9).extend({progressToken:e0})}),q0=n.extend({params:r.extend({cursor:H.optional($4)}).optional()}),V0=s.extend({nextCursor:H.optional($4)}),Q4=H.object({uri:H.string(),mimeType:H.optional(H.string())}).passthrough(),Y4=Q4.extend({text:H.string()}),J4=Q4.extend({blob:H.string().base64()}),H9=H.object({uri:H.string(),name:H.string(),description:H.optional(H.string()),mimeType:H.optional(H.string())}).passthrough(),G9=H.object({uriTemplate:H.string(),name:H.string(),description:H.optional(H.string()),mimeType:H.optional(H.string())}).passthrough(),z9=q0.extend({method:H.literal("resources/list")}),w9=V0.extend({resources:H.array(H9)}),B9=q0.extend({method:H.literal("resources/templates/list")}),q9=V0.extend({resourceTemplates:H.array(G9)}),V9=n.extend({method:H.literal("resources/read"),params:r.extend({uri:H.string()})}),M9=s.extend({contents:H.array(H.union([Y4,J4]))}),O9=X1.extend({method:H.literal("notifications/resources/list_changed")}),j9=n.extend({method:H.literal("resources/subscribe"),params:r.extend({uri:H.string()})}),L9=n.extend({method:H.literal("resources/unsubscribe"),params:r.extend({uri:H.string()})}),F9=X1.extend({method:H.literal("notifications/resources/updated"),params:a1.extend({uri:H.string()})}),K9=H.object({name:H.string(),description:H.optional(H.string()),required:H.optional(H.boolean())}).passthrough(),U9=H.object({name:H.string(),description:H.optional(H.string()),arguments:H.optional(H.array(K9))}).passthrough(),D9=q0.extend({method:H.literal("prompts/list")}),R9=V0.extend({prompts:H.array(U9)}),N9=n.extend({method:H.literal("prompts/get"),params:r.extend({name:H.string(),arguments:H.optional(H.record(H.string()))})}),M0=H.object({type:H.literal("text"),text:H.string()}).passthrough(),O0=H.object({type:H.literal("image"),data:H.string().base64(),mimeType:H.string()}).passthrough(),H4=H.object({type:H.literal("resource"),resource:H.union([Y4,J4])}).passthrough(),A9=H.object({role:H.enum(["user","assistant"]),content:H.union([M0,O0,H4])}).passthrough(),_9=s.extend({description:H.optional(H.string()),messages:H.array(A9)}),S9=X1.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(),S0=q0.extend({method:H.literal("tools/list")}),v9=V0.extend({tools:H.array(E9)}),G4=s.extend({content:H.array(H.union([M0,O0,H4])),isError:H.boolean().default(!1).optional()}),h6=G4.or(s.extend({toolResult:H.unknown()})),E0=n.extend({method:H.literal("tools/call"),params:r.extend({name:H.string(),arguments:H.optional(H.record(H.unknown()))})}),k9=X1.extend({method:H.literal("notifications/tools/list_changed")}),z4=H.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),C9=n.extend({method:H.literal("logging/setLevel"),params:r.extend({level:z4})}),f9=X1.extend({method:H.literal("notifications/message"),params:a1.extend({level:z4,logger:H.optional(H.string()),data:H.unknown()})}),b9=H.object({name:H.string().optional()}).passthrough(),P9=H.object({hints:H.optional(H.array(b9)),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(),I9=H.object({role:H.enum(["user","assistant"]),content:H.union([M0,O0])}).passthrough(),T9=n.extend({method:H.literal("sampling/createMessage"),params:r.extend({messages:H.array(I9),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(P9)})}),v0=s.extend({model:H.string(),stopReason:H.optional(H.enum(["endTurn","stopSequence","maxTokens"]).or(H.string())),role:H.enum(["user","assistant"]),content:H.discriminatedUnion("type",[M0,O0])}),g9=H.object({type:H.literal("ref/resource"),uri:H.string()}).passthrough(),x9=H.object({type:H.literal("ref/prompt"),name:H.string()}).passthrough(),h9=n.extend({method:H.literal("completion/complete"),params:r.extend({ref:H.union([x9,g9]),argument:H.object({name:H.string(),value:H.string()}).passthrough()})}),Z9=s.extend({completion:H.object({values:H.array(H.string()).max(100),total:H.optional(H.number().int()),hasMore:H.optional(H.boolean())}).passthrough()}),m9=H.object({uri:H.string().startsWith("file://"),name:H.optional(H.string())}).passthrough(),y9=n.extend({method:H.literal("roots/list")}),k0=s.extend({roots:H.array(m9)}),l9=X1.extend({method:H.literal("notifications/roots/list_changed")}),Z6=H.union([w0,A0,h9,C9,N9,D9,z9,B9,V9,j9,L9,E0,S0]),m6=H.union([z0,B0,_0,l9]),y6=H.union([G0,v0,k0]),l6=H.union([w0,T9,y9]),c6=H.union([z0,B0,f9,F9,O9,k9,S9]),u6=H.union([G0,Y9,Z9,_9,R9,w9,q9,M9,G4,v9]);class t1 extends Error{constructor($,W,X){super(`MCP error ${$}: ${W}`);this.code=$,this.data=X}}var c9=60000;class C0{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(z0,(W)=>{let X=this._requestHandlerAbortControllers.get(W.params.requestId);X===null||X===void 0||X.abort(W.params.reason)}),this.setNotificationHandler(B0,(W)=>{this._onprogress(W)}),this.setRequestHandler(w0,(W)=>({}))}async connect($){this._transport=$,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=(W)=>{this._onerror(W)},this._transport.onmessage=(W)=>{if(!("method"in W))this._onresponse(W);else if("id"in W)this._onrequest(W);else this._onnotification(W)},await this._transport.start()}_onclose(){var $;let W=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,($=this.onclose)===null||$===void 0||$.call(this);let X=new t1(D1.ConnectionClosed,"Connection closed");for(let J of W.values())J(X)}_onerror($){var W;(W=this.onerror)===null||W===void 0||W.call(this,$)}_onnotification($){var W;let X=(W=this._notificationHandlers.get($.method))!==null&&W!==void 0?W:this.fallbackNotificationHandler;if(X===void 0)return;Promise.resolve().then(()=>X($)).catch((J)=>this._onerror(Error(`Uncaught error in notification handler: ${J}`)))}_onrequest($){var W,X;let J=(W=this._requestHandlers.get($.method))!==null&&W!==void 0?W:this.fallbackRequestHandler;if(J===void 0){(X=this._transport)===null||X===void 0||X.send({jsonrpc:"2.0",id:$.id,error:{code:D1.MethodNotFound,message:"Method not found"}}).catch((w)=>this._onerror(Error(`Failed to send an error response: ${w}`)));return}let Y=new AbortController;this._requestHandlerAbortControllers.set($.id,Y),Promise.resolve().then(()=>J($,{signal:Y.signal})).then((w)=>{var B;if(Y.signal.aborted)return;return(B=this._transport)===null||B===void 0?void 0:B.send({result:w,jsonrpc:"2.0",id:$.id})},(w)=>{var B,M;if(Y.signal.aborted)return;return(B=this._transport)===null||B===void 0?void 0:B.send({jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(w.code)?w.code:D1.InternalError,message:(M=w.message)!==null&&M!==void 0?M:"Internal error"}})}).catch((w)=>this._onerror(Error(`Failed to send response: ${w}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:W,...X}=$.params,J=this._progressHandlers.get(Number(W));if(J===void 0){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}J(X)}_onresponse($){let W=$.id,X=this._responseHandlers.get(Number(W));if(X===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}if(this._responseHandlers.delete(Number(W)),this._progressHandlers.delete(Number(W)),"result"in $)X($);else{let J=new t1($.error.code,$.error.message,$.error.data);X(J)}}get transport(){return this._transport}async close(){var $;await(($=this._transport)===null||$===void 0?void 0:$.close())}request($,W,X){return new Promise((J,Y)=>{var w,B,M,j;if(!this._transport){Y(Error("Not connected"));return}if(((w=this._options)===null||w===void 0?void 0:w.enforceStrictCapabilities)===!0)this.assertCapabilityForMethod($.method);(B=X===null||X===void 0?void 0:X.signal)===null||B===void 0||B.throwIfAborted();let R=this._requestMessageId++,f={...$,jsonrpc:"2.0",id:R};if(X===null||X===void 0?void 0:X.onprogress)this._progressHandlers.set(R,X.onprogress),f.params={...$.params,_meta:{progressToken:R}};let P=void 0;this._responseHandlers.set(R,(Z)=>{var A;if(P!==void 0)clearTimeout(P);if((A=X===null||X===void 0?void 0:X.signal)===null||A===void 0?void 0:A.aborted)return;if(Z instanceof Error)return Y(Z);try{let I=W.parse(Z.result);J(I)}catch(I){Y(I)}});let h=(Z)=>{var A;this._responseHandlers.delete(R),this._progressHandlers.delete(R),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:R,reason:String(Z)}}).catch((I)=>this._onerror(Error(`Failed to send cancellation: ${I}`))),Y(Z)};(M=X===null||X===void 0?void 0:X.signal)===null||M===void 0||M.addEventListener("abort",()=>{var Z;if(P!==void 0)clearTimeout(P);h((Z=X===null||X===void 0?void 0:X.signal)===null||Z===void 0?void 0:Z.reason)});let e=(j=X===null||X===void 0?void 0:X.timeout)!==null&&j!==void 0?j:c9;P=setTimeout(()=>h(new t1(D1.RequestTimeout,"Request timed out",{timeout:e})),e),this._transport.send(f).catch((Z)=>{if(P!==void 0)clearTimeout(P);Y(Z)})})}async notification($){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let W={...$,jsonrpc:"2.0"};await this._transport.send(W)}setRequestHandler($,W){let X=$.shape.method.value;this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(J,Y)=>Promise.resolve(W($.parse(J),Y)))}removeRequestHandler($){this._requestHandlers.delete($)}setNotificationHandler($,W){this._notificationHandlers.set($.shape.method.value,(X)=>Promise.resolve(W($.parse(X))))}removeNotificationHandler($){this._notificationHandlers.delete($)}}class f0 extends C0{constructor($,W){super(W);this._serverInfo=$,this._capabilities=W.capabilities,this.setRequestHandler(A0,(X)=>this._oninitialize(X)),this.setNotificationHandler(_0,()=>{var X;return(X=this.oninitialized)===null||X===void 0?void 0:X.call(this)})}assertCapabilityForMethod($){var W,X;switch($){case"sampling/createMessage":if(!((W=this._clientCapabilities)===null||W===void 0?void 0:W.sampling))throw Error(`Client does not support sampling (required for ${$})`);break;case"roots/list":if(!((X=this._clientCapabilities)===null||X===void 0?void 0:X.roots))throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw 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 Error(`Server does not support sampling (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"ping":case"initialize":break}}async _oninitialize($){let W=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:s0.includes(W)?W:N0,capabilities:this.getCapabilities(),serverInfo:this._serverInfo}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},G0)}async createMessage($,W){return this.request({method:"sampling/createMessage",params:$},v0,W)}async listRoots($,W){return this.request({method:"roots/list",params:$},k0,W)}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 B4 from"process";class b0{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 W=this._buffer.toString("utf8",0,$);return this._buffer=this._buffer.subarray($+1),
|
|
4
|
-
`}class P0{constructor($=B4.stdin,W=B4.stdout){this._stdin=$,this._stdout=W,this._readBuffer=new b0,this._started=!1,this._ondata=(X)=>{this._readBuffer.append(X),this.processReadBuffer()},this._onerror=(X)=>{var J;(J=this.onerror)===null||J===void 0||J.call(this,X)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){var $,W;while(!0)try{let X=this._readBuffer.readMessage();if(X===null)break;($=this.onmessage)===null||$===void 0||$.call(this,X)}catch(X){(W=this.onerror)===null||W===void 0||W.call(this,X)}}async close(){var $;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._readBuffer.clear(),($=this.onclose)===null||$===void 0||$.call(this)}send($){return new Promise((W)=>{let X=w4($);if(this._stdout.write(X))W();else this._stdout.once("drain",W)})}}var n9=await Promise.resolve().then(() => x0(L0(),1)),q4=n9.version;async function V4($){let W=new f0({name:"typescape",version:q4},{capabilities:{tools:{}}});W.setRequestHandler(S0,async()=>{return{tools:$.getTools().map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}))}}),W.setRequestHandler(E0,async(J)=>{let{name:Y,arguments:w}=J.params,B=$.getHandler(Y);if(!B)return{content:[{type:"text",text:`Unknown tool: ${Y}`}],isError:!0};try{let M=await B(w||{});return{content:M.content.map((j)=>({type:j.type,text:j.text})),isError:M.isError}}catch(M){return{content:[{type:"text",text:`Error: ${M instanceof Error?M.message:String(M)}`}],isError:!0}}});let X=new P0;await W.connect(X),console.error(`Typescape MCP server v${q4} started`)}var I0=["file","doc","pr","custom"],d9=new Set(I0),p9=1e7,L4=/^[A-Za-z0-9+/]*={0,2}$/,M4="inline_assets_enabled",i9={type:"object",properties:{repo_id:{type:"string",description:"Repository identifier (short slug, e.g. 'typescape'; not a GitHub path like 'org/repo')"},git_sha:{type:"string",description:"Concrete 40-hex Git commit SHA (agent must resolve; no symbolic refs)"},file_path:{type:"string",description:"Path to the source document"},project_id:{type:"string",description:"Upload project ID for upload-backed sessions (requires upload_batch_id)"},upload_batch_id:{type:"string",description:"Upload batch ID for upload-backed sessions (requires project_id)"},title:{type:"string",description:"Session title (optional)"},participants:{type:"array",items:{type:"object",properties:{email:{type:"string"},name:{type:"string"},role:{type:"string",enum:["reviewer","approver","observer","owner"]},scopes:{type:"array",minItems:1,items:{type:"string",enum:["read","comment","approve","admin"]}}},required:["email","role"]},description:"Participants to invite (optional). Scopes are optional and default by role."},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"},expected_version:{type:"string",description:"Expected version for optimistic concurrency (If-Match header, optional)"},identity_restriction:{type:"string",enum:["open","participants_only","domain"],description:'Identity verification mode for OTP step-up. "open" (default): any email accepted. "participants_only": only invited participant emails. "domain": only emails from allowed_email_domains.'},allowed_email_domains:{type:"array",items:{type:"string"},description:'Allowed email domains when identity_restriction is "domain" (e.g., ["acme.com", "example.org"])'},operator_name:{type:"string",maxLength:200,description:"Name of the operator initiating the review (optional)"},focus_areas:{type:"array",items:{type:"string",maxLength:100},maxItems:10,description:"Areas the reviewer should focus on (optional)"},framing:{type:"string",maxLength:1000,description:"Context framing text shown to reviewers (optional)"},carry_forward_threads:{type:"boolean",description:"Whether to carry forward threads from the superseded session (optional)"},carry_forward_filter:{type:"string",enum:["all","blocking","needs_changes"],description:"Filter for which threads to carry forward (optional)"},content_body:{type:"string",maxLength:1048576,description:"Inline Markdown content (alternative to repo_id+git_sha). Creates an upload-backed session automatically."},inline_assets:{oneOf:[{type:"object",additionalProperties:{oneOf:[{type:"string"},{type:"object",properties:{base64:{type:"string"},content_base64:{type:"string"},content:{type:"string"},data:{type:"string"}},additionalProperties:!0}]}},{type:"array",items:{type:"object",properties:{path:{type:"string"},file_path:{type:"string"},filename:{type:"string"},file_name:{type:"string"},name:{type:"string"},base64:{type:"string"},content_base64:{type:"string"},content:{type:"string"},data:{type:"string"}},additionalProperties:!0}}],description:'Companion assets as either a map of relative path => base64 content, or a list of asset objects. Map example: { "images/fig.png": "iVBORw0KGgo..." }. Array example: [{ "path": "images/fig.png", "base64": "iVBORw0KGgo..." }]. Total decoded size must be <= 10MB.'},document_type:{type:"string",enum:["markdown","image_set","pdf"],description:'Document type (default: "markdown"). Use "image_set" for image-only review sessions or "pdf" for PDF review sessions.'},filenames:{type:"array",items:{type:"string"},minItems:1,maxItems:100,description:'Ordered list of image filenames (required when document_type is "image_set"). Each filename must be a relative path. Supported formats: PNG, JPEG, WebP, GIF, SVG.'}},required:["file_path"]},o9={type:"object",properties:{session_id:{type:"string",description:"ID of the session to supersede (the predecessor, e.g., sess_01HXYZ...)"},git_sha:{type:"string",description:"Concrete 40-hex Git commit SHA for the new revision (agent must resolve; no symbolic refs)"},content_body:{type:"string",description:"Inline Markdown content for upload-backed supersede sessions (alternative to git_sha/upload_batch_id)"},project_id:{type:"string",description:"Upload project ID for upload-backed supersede sessions (required with upload_batch_id)"},upload_batch_id:{type:"string",description:"Upload batch ID for upload-backed supersede sessions (alternative to git_sha/content_body)"},file_path:{type:"string",description:"Path to the source document (optional; defaults to predecessor's file_path)"},document_type:{type:"string",enum:["markdown","image_set","pdf"],description:"Document type for supersede (optional; defaults to predecessor document_type)"},filename:{type:"string",description:"PDF filename for document_type=pdf supersedes (optional; defaults to file_path)"},filenames:{type:"array",items:{type:"string"},minItems:1,description:"Ordered image filenames for document_type=image_set supersedes"},title:{type:"string",description:"Title for the new session (optional; defaults to predecessor's title)"},changes_summary:{type:"string",maxLength:5000,description:"Summary of changes for round-transition emails and the superseded banner (optional)"},resolutions:{type:"array",items:{type:"object",properties:{thread_id:{type:"string",description:"Thread ID from the predecessor session"},disposition:{type:"string",enum:["fixed","wont_fix","duplicate","by_design"],description:"How the thread was resolved"},evidence:{type:"string",maxLength:2000,description:"Optional evidence or explanation for the resolution"}},required:["thread_id","disposition"]},description:"Resolution manifest for threads from the predecessor session (optional)"},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"}},required:["session_id"]},a9={type:"object",properties:{session_id:{type:"string",description:"Session ID to export (e.g., sess_01HXYZ...)"},schema:{type:"string",default:"v1",description:"Export schema version (default: v1)"},view:{type:"string",description:"Export view variant (optional). Values: redacted, response_matrix.v1, delta_review.v1"},expected_version:{type:"string",description:"Expected version for optimistic concurrency (If-Match header, optional)"}},required:["session_id"]},t9={type:"object",properties:{repo_id:{type:"string",description:"Filter sessions by repository identifier (short slug, e.g. 'typescape'; optional)"},state:{type:"string",description:"Filter by session state: active, closed, archived (optional)"},file_paths:{type:"string",description:"Comma-separated list of file paths to filter by (optional)"},cursor:{type:"string",description:"Pagination cursor from previous response (optional)"},limit:{type:"number",description:"Maximum number of sessions to return (optional, default: 20)"},root_session_id:{type:"string",description:"Filter by supersede chain root session ID (optional, e.g., sess_...)"},supersedes_session_id:{type:"string",description:"Filter by immediate predecessor session ID (optional, e.g., sess_...)"},has_successor:{type:"boolean",description:"If true, return only sessions that have been superseded; if false, only chain heads (optional)"}},required:[]},r9={type:"object",properties:{session_id:{type:"string",description:"Session ID to retrieve (e.g., sess_01HXYZ...)"}},required:["session_id"]},s9={type:"object",properties:{session_id:{type:"string",description:"Session ID to render (e.g., sess_01HXYZ...)"},include_plaintext:{type:"boolean",description:"Include plaintext representation alongside HTML (optional, default: false)"}},required:["session_id"]},e9={type:"object",properties:{session_id:{type:"string",description:"Session ID to list threads for (e.g., sess_01HXYZ...)"},block_id:{type:"string",description:"Filter threads by block_id anchor (optional)"},status:{type:"string",description:"Filter threads by status: open, resolved, all (optional, default: all)"},cursor:{type:"string",description:"Pagination cursor from previous response (optional)"},limit:{type:"number",description:"Maximum number of threads to return (optional, default: 50)"}},required:["session_id"]},$6={type:"object",properties:{session_id:{type:"string",description:"Session ID to export response matrix for (e.g., sess_01HXYZ...)"}},required:["session_id"]};function v($,W){return{content:[{type:"text",text:JSON.stringify({...$,request_id:W},null,2)}]}}function V($){let W=$.status===0||$.status>=500||$.status===429;return{content:[{type:"text",text:JSON.stringify({error:{code:$.code,message:$.message,retryable:W,request_id:$.requestId,...$.details?{details:$.details}:{},...$.fixHint?{fix_hint:$.fixHint}:{}}},null,2)}],isError:!0}}function O4($){if(typeof $==="string"){let Y=$.trim();return Y.length>0?Y:null}if(!$||typeof $!=="object"||Array.isArray($))return null;let W=$,X=W.base64??W.content_base64??W.content??W.data??W.bytes;if(typeof X!=="string")return null;let J=X.trim();return J.length>0?J:null}function j4($,W){if(typeof $==="string"){let Y=$.trim();return Y.length>0?Y:null}if(!$||typeof $!=="object"||Array.isArray($))return W??null;let X=$,J=X.path??X.file_path??X.filename??X.file_name??X.name;if(typeof J==="string"&&J.trim().length>0)return J.trim();return W??null}function W6($,W){if($===void 0||$===null)return{assets:{}};let X={};if(Array.isArray($)){for(let[Y,w]of $.entries()){let B=j4(w,W),M=O4(w);if(!B||!M)return{error:new q(422,"invalid_argument",`inline_assets[${Y}] requires both a path and base64 payload`,"local")};X[B]=M}return{assets:X}}if(typeof $!=="object")return{error:new q(422,"invalid_argument","inline_assets must be an object map or array","local")};let J=Object.entries($);for(let[Y,w]of J){let B=J.length===1&&/^[0-9]+$/.test(Y)&&typeof W==="string"&&W.trim().length>0?W.trim():Y,M=w&&typeof w==="object"&&!Array.isArray(w)?j4(w,B):B,j=O4(w);if(!M||!j)return{error:new q(422,"invalid_argument",`inline_assets entry '${Y}' requires base64 content`,"local")};X[M]=j}return{assets:X}}function X6($){if(!$||$.length===0)return"Asset path is empty";if($.includes("\x00"))return"Asset path contains NUL byte";let W=$.replace(/\\/g,"/");if(W.startsWith("/"))return"Asset path must be relative (no leading /)";let X=W.split("/");for(let J of X)if(J==="..")return"Asset path must not contain '..' segments";return null}function F4($){let W=$.replace(/\s+/g,"");if(W.length===0)return new Uint8Array;if(W.length%4!==0||!L4.test(W))return null;let X=Buffer.from(W,"base64"),J=W.replace(/=+$/,""),Y=X.toString("base64").replace(/=+$/,"");if(J!==Y)return null;return Uint8Array.from(X)}function Q6($){if($.code!=="feature_disabled")return!1;let W=$.details?.feature;if(typeof W==="string"&&W.toLowerCase()===M4)return!0;return`${$.message} ${$.fixHint??""}`.toLowerCase().includes(M4)}function Y6($){let X=$.replace(/\\/g,"/").split("/"),J=X[X.length-1];return J&&J.length>0?J:"asset.bin"}async function J6($,W,X){let J=X&&X.trim().length>0?`MCP ${X.trim()}`:`MCP inline upload ${Date.now()}`,Y=await $.post("/projects",{body:{name:J}});if(!Y.body.id||Y.body.id.length===0)throw new q(502,"invalid_upstream_response","Upload project creation did not return project id",Y.requestId);let w=new FormData,B=Object.entries(W).sort(([j],[R])=>j.localeCompare(R));for(let[j,R]of B){let f=F4(R);if(f===null)throw new q(422,"invalid_argument",`Invalid base64 content for asset: ${j}`,"local");w.append(j,new Blob([f]),Y6(j))}let M=await $.postFormData(`/projects/${encodeURIComponent(Y.body.id)}/upload`,w);if(!M.body.upload_batch_id||M.body.upload_batch_id.length===0)throw new q(502,"invalid_upstream_response","Upload batch response did not include upload_batch_id",M.requestId);return{projectId:Y.body.id,uploadBatchId:M.body.upload_batch_id}}function H6($){if($==="approver")return["read","comment","approve"];if($==="observer")return["read"];if($==="owner")return["read","comment","approve","admin"];return["read","comment"]}function G6($){return $.map((W)=>{let X=W.scopes&&W.scopes.length>0?[...new Set(W.scopes)]:H6(W.role);return{email:W.email,...W.name?{name:W.name}:{},role:W.role,scopes:X}})}var z6={type:"object",properties:{source_type:{type:"string",enum:["git","upload"],description:"Source type for the review set"},title:{type:"string",description:"Review set title (optional)"},kind:{type:"string",enum:["review_set","release_bundle","packet"],description:"Kind of review set (optional, default: review_set)"},participants:{type:"array",items:{type:"object",properties:{email:{type:"string"},role:{type:"string",enum:["reviewer","approver"]},roles:{type:"array",items:{type:"string",enum:["reviewer","approver"]},minItems:1}},required:["email"]},description:"Participants to invite (optional). Supports role (single) or roles (array)."},sessions:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{session_id:{type:"string"},required:{type:"boolean"}},required:["session_id"],additionalProperties:!1}]},minItems:1,description:"Session IDs (or session entry objects) to include in this review set."},files:{type:"array",items:{type:"object",properties:{repo_id:{type:"string"},git_sha:{type:"string"},project_id:{type:"string"},upload_batch_id:{type:"string"},file_path:{type:"string"},required:{type:"boolean"}},required:["file_path"],additionalProperties:!1},minItems:1,description:"File entries for git or upload source types (must include file_path plus source identifiers)."},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"}},required:["source_type"]},w6={type:"object",properties:{review_set_id:{type:"string",description:"Review set ID to export"},schema:{type:"string",description:"Export schema version (optional, default: v1)"},view:{type:"string",description:"Export view variant (optional). Values: full, redacted, response_matrix.v1, etc."}},required:["review_set_id"]},B6={type:"object",properties:{source_type:{type:"string",enum:["git","upload"],description:"Source type for the review ref"},repo_id:{type:"string",description:"Repository identifier (required for git source_type; short slug, e.g. 'typescape')"},project_id:{type:"string",description:"Project identifier (required for upload source_type; omit for git)"},kind:{type:"string",enum:I0,description:"Review ref kind"},key:{type:"string",description:"Review ref key (e.g., file path, doc slug, PR number, custom name)"},head_session_id:{type:"string",description:"Session ID to use as the initial head (required, e.g., sess_01HXYZ...)"}},required:["source_type","kind","key","head_session_id"]},q6={type:"object",properties:{review_ref_id:{type:"string",description:"Review ref ID to resolve"}},required:["review_ref_id"]},V6={type:"object",properties:{review_ref_id:{type:"string",description:"Review ref ID to advance"},head_session_id:{type:"string",description:"New head session ID to advance to"},expected_head_session_id:{type:"string",description:"Expected current head for optimistic concurrency (optional)"}},required:["review_ref_id","head_session_id"]},M6={type:"object",properties:{session_id:{type:"string",description:"Session ID to request approval for"},approver_emails:{type:"array",items:{type:"string"},description:"Email addresses of approvers"},message:{type:"string",description:"Message to include with the approval request (optional)"},notify:{type:"object",properties:{email:{type:"boolean"},slack:{type:"boolean"}},description:"Notification channels (optional)"},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"}},required:["session_id","approver_emails"]},O6={type:"object",properties:{session_id:{type:"string",description:"Session ID to get status for"},simulate:{type:"boolean",description:"Run policy evaluation without side effects (optional)"},wait:{type:"number",description:"Long-poll timeout in seconds (optional)"}},required:["session_id"]},j6={type:"object",properties:{session_id:{type:"string",description:"Session ID to run checks against"}},required:["session_id"]},L6={type:"object",properties:{},additionalProperties:!1},F6={type:"object",properties:{},additionalProperties:!1},K6={type:"object",properties:{},additionalProperties:!1},U6={type:"object",properties:{session_id:{type:"string",description:"Session ID to create thread in (e.g., sess_01HXYZ...)"},body_md:{type:"string",description:"Thread body in Markdown"},block_id:{type:"string",description:"Block ID to anchor thread to (optional; omit for session-level)"},anchor:{type:"object",properties:{type:{type:"string",enum:["session","block","range"],description:"Anchor type (default: session if no block_id, block if block_id provided)"},start_offset:{type:"number",description:"Start offset for range anchor"},end_offset:{type:"number",description:"End offset for range anchor"}},description:"Anchor details (optional)"},severity:{type:"string",enum:["suggestion","needs_changes","blocking"],description:"Thread severity. Note: 'blocking' from automation is coerced to 'needs_changes' per Ch 11 L6250"},tags:{type:"array",items:{type:"string"},description:"Tags for categorization (optional)"},suggestion:{type:"object",properties:{type:{type:"string",enum:["replace","insert","delete"]}},description:"Suggested change (optional)"},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"}},required:["session_id","body_md"]},D6={type:"object",properties:{session_id:{type:"string",description:"Session ID containing the thread"},thread_id:{type:"string",description:"Thread ID to post comment to"},body_md:{type:"string",description:"Comment body in Markdown"},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"}},required:["session_id","thread_id","body_md"]},R6={type:"object",properties:{session_id:{type:"string",description:"Session ID containing the thread"},thread_id:{type:"string",description:"Thread ID to resolve"},disposition:{type:"object",properties:{state:{type:"string",enum:["accepted_change","rejected_wont_fix","deferred","duplicate","needs_more_info","answered_no_change"],description:"Disposition state"},rationale_md:{type:"string",description:"Rationale in Markdown (optional)"}},required:["state"],description:"Disposition to record with resolution (optional)"},expected_version:{type:"string",description:"Expected version for optimistic concurrency (If-Match header, optional)"},if_match:{type:"string",description:"Alias for expected_version (If-Match header, optional)"}},required:["session_id","thread_id"]},N6={type:"object",properties:{session_id:{type:"string",description:"Session ID containing the thread"},thread_id:{type:"string",description:"Thread ID to reopen"},expected_version:{type:"string",description:"Expected version for optimistic concurrency (If-Match header, optional)"},if_match:{type:"string",description:"Alias for expected_version (If-Match header, optional)"}},required:["session_id","thread_id"]},A6={type:"object",properties:{session_id:{type:"string",description:"Session ID containing the thread"},thread_id:{type:"string",description:"Thread ID to record disposition for"},state:{type:"string",enum:["undecided","accepted_change","rejected_wont_fix","deferred","duplicate","needs_more_info","answered_no_change"],description:"Disposition state"},rationale_md:{type:"string",description:"Rationale in Markdown (optional)"}},required:["session_id","thread_id","state"]},_6={type:"object",properties:{session_id:{type:"string",description:"Session ID containing the thread"},thread_id:{type:"string",description:"Thread ID to attach evidence to"},evidence_type:{type:"string",enum:["commit","proposed_change","pr","attestation","external_ticket","note"],description:"Evidence type (required). Determines which additional fields are relevant."},commit_sha:{type:"string",description:"Git commit SHA (for evidence_type=commit)"},repo_url:{type:"string",description:"Repository URL (for evidence_type=commit)"},message:{type:"string",description:"Commit message (for evidence_type=commit)"},proposed_change_id:{type:"string",description:"Proposed change ID (for evidence_type=proposed_change)"},patch_sha256:{type:"string",description:"Patch SHA256 (for evidence_type=proposed_change)"},pr_url:{type:"string",description:"PR URL (for evidence_type=pr)"},pr_number:{type:"number",description:"PR number (for evidence_type=pr)"},attestation_id:{type:"string",description:"Attestation ID (for evidence_type=attestation)"},attestor:{type:"string",description:"Attestor identity (optional, for attestation type)"},ticket_url:{type:"string",description:"Ticket URL (for evidence_type=external_ticket)"},ticket_id:{type:"string",description:"Ticket ID (for evidence_type=external_ticket)"},system:{type:"string",description:"Ticket system (for evidence_type=external_ticket)"},note_md:{type:"string",description:"Note text (for evidence_type=note)"},dedupe_key:{type:"string",description:"Optional idempotency/deduplication key for evidence attach"}},required:["session_id","thread_id","evidence_type"]},S6={type:"object",properties:{name:{type:"string",description:"Collection name (1-100 characters, unique per tenant among non-archived collections)"},description:{type:"string",description:"Optional Markdown description (max 2000 characters)"},color:{type:"string",description:"Optional hex color (e.g., #12A594)"}},required:["name"]},E6={type:"object",properties:{collection_id:{type:"string",description:"Collection ID (e.g., col_01HXYZ...)"},session_id:{type:"string",description:"Session ID to add (e.g., sess_01HXYZ...)"}},required:["collection_id","session_id"]};function K4($,W){let X={name:"typescape_create_session",description:"Create a new Typescape review session for Markdown, image-set, or PDF content. Supports three source modes: (1) git-backed with repo_id+git_sha, (2) inline with content_body and optional inline_assets (base64), or (3) upload-backed with project_id+upload_batch_id. Returns the session ID and any invitations sent.",inputSchema:i9};$.register(X,async(O)=>{let Q=O,G=W6(Q.inline_assets,Q.file_path);if("error"in G)return V(G.error);let z=G.assets;if(!Q.file_path)return V(new q(400,"missing_param","Missing required parameter: file_path","local"));let F=typeof Q.repo_id==="string"&&Q.repo_id.length>0,U=typeof Q.git_sha==="string"&&Q.git_sha.length>0,C=typeof Q.project_id==="string"&&Q.project_id.length>0,T=typeof Q.upload_batch_id==="string"&&Q.upload_batch_id.length>0,p=F&&U,y=C&&T,R1=!!Q.content_body,M1=Object.keys(z).length>0;if(F&&!U||!F&&U)return V(new q(422,"invalid_argument","Both repo_id and git_sha are required for git-backed sessions","local"));if(C&&!T||!C&&T)return V(new q(422,"invalid_argument","Both project_id and upload_batch_id are required for upload-backed sessions","local"));if(Q.document_type!==void 0&&Q.document_type!=="markdown"&&Q.document_type!=="image_set"&&Q.document_type!=="pdf")return V(new q(422,"invalid_argument",`Unsupported document_type: ${Q.document_type}. Supported values: "markdown", "image_set", "pdf".`,"local"));let N1=Q.document_type==="image_set",m1=Q.document_type==="pdf";if(N1){if(!M1&&!y)return V(new q(400,"image_set_empty","image_set sessions require inline_assets or upload-batch input (project_id + upload_batch_id)","local"));if(y&&(!Q.filenames||Q.filenames.length===0))return V(new q(400,"missing_param",'document_type "image_set" with upload-batch mode requires filenames.',"local"));let g=new Set([".png",".jpg",".jpeg",".webp",".gif",".svg"]);if(M1){for(let Y1 of Object.keys(z)){let J1=Y1.slice(Y1.lastIndexOf(".")).toLowerCase();if(!g.has(J1))return V(new q(422,"unsupported_media_type",`Unsupported image format for image_set: ${Y1}. Supported extensions: ${[...g].join(", ")}`,"local"))}if(Object.keys(z).length>100)return V(new q(422,"image_set_limit_exceeded",`Image set has ${Object.keys(z).length} images, exceeding the maximum of 100`,"local"))}}if(m1){if(p)return V(new q(422,"invalid_argument",'document_type "pdf" is only supported with upload-backed sources (inline_assets or project_id+upload_batch_id).',"local"));if(R1)return V(new q(422,"invalid_argument",'document_type "pdf" does not support content_body; provide inline_assets with one .pdf file.',"local"));if(!M1&&!y)return V(new q(400,"missing_param",'document_type "pdf" requires either inline_assets with one .pdf file, or upload-batch input (project_id + upload_batch_id).',"local"));if(M1&&y)return V(new q(422,"invalid_argument",'document_type "pdf" cannot mix inline_assets and upload-batch inputs.',"local"));if(M1&&Object.keys(z).length!==1)return V(new q(422,"invalid_argument",'document_type "pdf" requires exactly one inline asset.',"local"));if(M1){let[g]=Object.keys(z);if(!g)return V(new q(400,"missing_param",'document_type "pdf" requires inline_assets with exactly one .pdf file.',"local"));if(g.slice(g.lastIndexOf(".")).toLowerCase()!==".pdf")return V(new q(422,"unsupported_media_type",`Unsupported PDF format: ${g}. Supported extension: .pdf`,"local"));if(Q.file_path!==g)return V(new q(422,"invalid_argument",`For document_type "pdf", file_path must match inline_assets key: ${g}`,"local"))}}let T0=[p,R1,y].filter(Boolean).length;if(!N1&&!m1&&T0===0)return V(new q(400,"missing_param","Provide one source mode: (repo_id + git_sha), (content_body), or (project_id + upload_batch_id)","local"));if(T0>1)return V(new q(422,"ambiguous_session_input","Cannot mix source modes: choose exactly one of git-backed, inline content_body, or upload-backed.","local"));if(!N1&&Q.filenames&&Q.filenames.length>0)return V(new q(422,"invalid_argument","filenames is only valid when document_type is image_set.","local"));if(Q.identity_restriction==="domain"&&(!Q.allowed_email_domains||Q.allowed_email_domains.length===0))return V(new q(422,"invalid_argument",'allowed_email_domains is required when identity_restriction is "domain"',"local"));if(Object.keys(z).length>0){if(!R1&&!N1&&!m1)return V(new q(422,"invalid_argument","inline_assets requires content_body (inline mode)","local"));let g=0;for(let[Y1,J1]of Object.entries(z)){let s1=X6(Y1);if(s1)return V(new q(422,"invalid_argument",`${s1}: ${Y1}`,"local"));let O1=F4(J1);if(O1===null)return V(new q(422,"invalid_argument",`Invalid base64 content for asset: ${Y1}`,"local"));g+=O1.byteLength}if(g>p9)return V(new q(413,"inline_payload_too_large",`Total decoded inline assets (${g} bytes) exceed 10MB limit. Use the Typescape CLI with upload batch for larger payloads.`,"local"))}let m={file_path:Q.file_path};if(p)m.repo_id=Q.repo_id,m.git_sha=Q.git_sha;if(y)m.project_id=Q.project_id,m.upload_batch_id=Q.upload_batch_id;if(R1)m.content_body=Q.content_body;if(Object.keys(z).length>0)m.inline_assets=z;if(Q.participants&&Q.participants.length>0)m.participants=G6(Q.participants);if(Q.title!==void 0)m.title=Q.title;if(Q.identity_restriction!==void 0)m.identity_restriction=Q.identity_restriction;if(Q.allowed_email_domains!==void 0&&Q.allowed_email_domains.length>0)m.allowed_email_domains=Q.allowed_email_domains;if(Q.operator_name!==void 0)m.operator_name=Q.operator_name;if(Q.focus_areas!==void 0&&Q.focus_areas.length>0)m.focus_areas=Q.focus_areas;if(Q.framing!==void 0)m.framing=Q.framing;if(Q.carry_forward_threads!==void 0)m.carry_forward_threads=Q.carry_forward_threads;if(Q.carry_forward_filter!==void 0)m.carry_forward_filter=Q.carry_forward_filter;if(Q.document_type!==void 0)m.document_type=Q.document_type;if(m1)m.filename=Q.file_path;if(N1){let g=Q.filenames&&Q.filenames.length>0?Q.filenames:Object.keys(z).sort();m.filenames=g}let r1={};if(Q.idempotency_key)r1["Idempotency-Key"]=Q.idempotency_key;if(Q.expected_version)r1["If-Match"]=Q.expected_version;try{let g=await W.post("/sessions",{body:m,headers:r1});return v({session:g.body.session,invitations:g.body.invitations??[]},g.requestId)}catch(g){if(g instanceof q){if(M1&&!y&&!p&&!R1&&(N1||m1)&&Q6(g))try{let{projectId:J1,uploadBatchId:s1}=await J6(W,z,Q.title),O1={...m};delete O1.inline_assets,O1.project_id=J1,O1.upload_batch_id=s1;let j0=await W.post("/sessions",{body:O1,headers:r1});return v({session:j0.body.session,invitations:j0.body.invitations??[]},j0.requestId)}catch(J1){if(J1 instanceof q)return V(J1);throw J1}return V(g)}throw g}});let J={name:"typescape_supersede_session",description:"Create a new Typescape review session pinned to a newer revision, superseding an existing session. The predecessor becomes read-only and unresolved threads are carried forward to the new session. Supports git supersede (git_sha) and upload supersede (content_body or upload_batch_id+project_id).",inputSchema:o9};$.register(J,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));let G=typeof Q.git_sha==="string"&&Q.git_sha.length>0,z=typeof Q.content_body==="string"&&Q.content_body.length>0,F=typeof Q.upload_batch_id==="string"&&Q.upload_batch_id.length>0,U=typeof Q.project_id==="string"&&Q.project_id.length>0;if(U&&!F||!U&&F)return V(new q(422,"invalid_argument","Both project_id and upload_batch_id are required for upload-backed supersede","local"));let C=[G,z,F].filter(Boolean).length;if(C===0)return V(new q(400,"missing_param","One of git_sha, content_body, or upload_batch_id is required","local"));if(C>1)return V(new q(422,"invalid_argument","git_sha, content_body, and upload_batch_id are mutually exclusive","local"));if(G&&!/^[a-f0-9]{40}$/i.test(Q.git_sha))return V(new q(400,"invalid_param",`Invalid git_sha format: must be a 40-character hex string, got "${Q.git_sha}"`,"local"));let T={};if(G)T.git_sha=Q.git_sha.toLowerCase();if(z)T.content_body=Q.content_body;if(F)T.project_id=Q.project_id,T.upload_batch_id=Q.upload_batch_id;if(Q.file_path!==void 0)T.file_path=Q.file_path;if(Q.document_type!==void 0)T.document_type=Q.document_type;if(Q.filename!==void 0)T.filename=Q.filename;else if(Q.document_type==="pdf"&&Q.file_path!==void 0)T.filename=Q.file_path;if(Q.filenames!==void 0&&Q.filenames.length>0)T.filenames=Q.filenames;if(Q.title!==void 0)T.title=Q.title;if(Q.changes_summary!==void 0)T.changes_summary=Q.changes_summary;if(Q.resolutions!==void 0&&Q.resolutions.length>0)T.resolutions=Q.resolutions;let p={};if(Q.idempotency_key)p["Idempotency-Key"]=Q.idempotency_key;try{let y=await W.post(`/sessions/${encodeURIComponent(Q.session_id)}/supersede`,{body:T,headers:p});return v(y.body,y.requestId)}catch(y){if(y instanceof q)return V(y);throw y}});let Y={name:"typescape_export_feedback",description:"Export all feedback from a Typescape review session as structured JSON. Returns the full export document including threads, comments, and anchors.",inputSchema:a9};$.register(Y,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));let G={schema:Q.schema||"v1"};if(Q.view)G.view=Q.view;let z={};if(Q.expected_version)z["If-Match"]=Q.expected_version;try{let F=await W.get(`/sessions/${Q.session_id}/export`,{query:G,headers:z});return v(F.body,F.requestId)}catch(F){if(F instanceof q)return V(F);throw F}});let w={name:"typescape_list_sessions",description:"List Typescape review sessions with optional filters. Returns paginated session summaries. Use cursor from previous response for pagination.",inputSchema:t9};$.register(w,async(O)=>{let Q=O,G={};if(Q.repo_id)G.repo_id=Q.repo_id;if(Q.state)G.state=Q.state;if(Q.file_paths)G.file_paths=Q.file_paths;if(Q.cursor)G.cursor=Q.cursor;if(Q.limit!==void 0)G.limit=String(Q.limit);if(Q.root_session_id)G.root_session_id=Q.root_session_id;if(Q.supersedes_session_id)G.supersedes_session_id=Q.supersedes_session_id;if(Q.has_successor!==void 0)G.has_successor=Q.has_successor?"true":"false";try{let z=await W.get("/sessions",{query:G});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let B={name:"typescape_get_session",description:"Get details of a specific Typescape review session. Returns full session metadata including participants, stats, and provenance.",inputSchema:r9};$.register(B,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));try{let G=await W.get(`/sessions/${Q.session_id}`);return v(G.body,G.requestId)}catch(G){if(G instanceof q)return V(G);throw G}});let M={name:"typescape_get_render",description:"Get the rendered content of a review session. Returns immutable block-level HTML structure with block_ids for anchoring.",inputSchema:s9},j=new Map;function R(O){let Q=O.indexOf("#");if(Q===-1)throw new q(500,"invalid_review_url","Review link URL is missing fragment token","local");return O.slice(Q+1)}async function f(O){let Q=j.get(O);if(Q&&Q.expiresAtMs>Date.now())return Q.token;let G=await W.get(`/sessions/${O}/participants`,{query:{role:"reviewer"}}),z=G.body.items?.[0]?.participant_id??null;if(!z)z=(await W.get(`/sessions/${O}/participants`,{query:{limit:"1"}})).body.items?.[0]?.participant_id??null;if(!z)throw new q(422,"no_participants","No participants available to mint a render token",G.requestId);let F=await W.post(`/sessions/${O}/links`,{body:{participant_id:z,scope:"read",single_use:!0,url_token_ttl_minutes:60}}),U=F.body.url;if(!U||typeof U!=="string")throw new q(500,"invalid_link_response","Failed to mint review link for render",F.requestId);let C=await W.post("/auth/exchange",{body:{url_token:R(U)}}),T=C.body.session_access_token,p=C.body.expires_in_seconds;if(!T||typeof T!=="string")throw new q(500,"token_exchange_failed","Failed to exchange review link for session access token",C.requestId);let y=typeof p==="number"&&Number.isFinite(p)?Math.max(0,Math.trunc(p)-30)*1000:300000;return j.set(O,{token:T,expiresAtMs:Date.now()+y}),T}$.register(M,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));let G={};if(Q.include_plaintext)G.include_plaintext="true";try{let z=await f(Q.session_id),F=await W.get(`/sessions/${Q.session_id}/render`,{query:G,headers:{Authorization:`Bearer ${z}`}});return v(F.body,F.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let P={name:"typescape_get_threads",description:"List threads (comments) for a review session. Optionally filter by block_id anchor or thread status. Returns paginated thread list with comments.",inputSchema:e9};$.register(P,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));let G={};if(Q.block_id)G.block_id=Q.block_id;if(Q.status)G.status=Q.status;if(Q.cursor)G.cursor=Q.cursor;if(Q.limit!==void 0)G.limit=String(Q.limit);try{let z=await W.get(`/sessions/${Q.session_id}/threads`,{query:G});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let h={name:"typescape_export_response_matrix",description:"Export the response matrix for a review session. Returns per-thread disposition and evidence summary.",inputSchema:$6};$.register(h,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));try{let G=await W.get(`/sessions/${Q.session_id}/export`,{query:{schema:"v1",view:"response_matrix.v1"}});return v(G.body,G.requestId)}catch(G){if(G instanceof q)return V(G);throw G}}),$.register({name:"typescape_create_thread",description:"Create a new thread (comment) on a review session. Optionally anchor to a specific block_id. Agent-created threads are tagged source='automation'. Severity 'blocking' is coerced to 'needs_changes' for automation sources.",inputSchema:U6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.body_md)return V(new q(400,"missing_param","Missing required parameter: body_md","local"));let G={body_md:Q.body_md,source:"automation"},z=typeof Q.block_id==="string"?Q.block_id.trim():void 0;if(z)G.block_id=z;if(Q.anchor!==void 0)G.anchor=Q.anchor;else if(z)G.anchor={type:"block"};if(Q.severity!==void 0)G.severity=Q.severity;if(Q.tags!==void 0)G.tags=Q.tags;if(Q.suggestion!==void 0)G.suggestion=Q.suggestion;let F={};if(Q.idempotency_key)F["Idempotency-Key"]=Q.idempotency_key;try{let U=await W.post(`/sessions/${Q.session_id}/threads`,{body:G,headers:F});return v(U.body,U.requestId)}catch(U){if(U instanceof q)return V(U);throw U}}),$.register({name:"typescape_post_comment",description:"Post a comment (reply) to an existing thread. Returns the created comment with its ID.",inputSchema:D6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.thread_id)return V(new q(400,"missing_param","Missing required parameter: thread_id","local"));if(!Q.body_md)return V(new q(400,"missing_param","Missing required parameter: body_md","local"));let G={body_md:Q.body_md,source:"automation"},z={};if(Q.idempotency_key)z["Idempotency-Key"]=Q.idempotency_key;try{let F=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/comments`,{body:G,headers:z});return v(F.body,F.requestId)}catch(F){if(F instanceof q)return V(F);throw F}}),$.register({name:"typescape_resolve_thread",description:"Resolve (close) a thread. Optionally include a disposition. Use expected_version or if_match for optimistic concurrency.",inputSchema:R6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.thread_id)return V(new q(400,"missing_param","Missing required parameter: thread_id","local"));let G={};if(Q.disposition!==void 0)G.disposition=Q.disposition;let z={},F=Q.expected_version??Q.if_match;if(F)z["If-Match"]=F;try{let U=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/resolve`,{body:G,headers:z});return v(U.body,U.requestId)}catch(U){if(U instanceof q)return V(U);throw U}}),$.register({name:"typescape_reopen_thread",description:"Reopen a previously resolved thread. Use expected_version or if_match for optimistic concurrency.",inputSchema:N6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.thread_id)return V(new q(400,"missing_param","Missing required parameter: thread_id","local"));let G={},z={},F=Q.expected_version??Q.if_match;if(F)z["If-Match"]=F;try{let U=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/reopen`,{body:G,headers:z});return v(U.body,U.requestId)}catch(U){if(U instanceof q)return V(U);throw U}}),$.register({name:"typescape_record_disposition",description:"Record a disposition (decision) on a thread. Dispositions track how feedback was addressed. Note: recording a resolving disposition may automatically resolve the thread.",inputSchema:A6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.thread_id)return V(new q(400,"missing_param","Missing required parameter: thread_id","local"));if(!Q.state)return V(new q(400,"missing_param","Missing required parameter: state","local"));let G={state:Q.state};if(Q.rationale_md!==void 0)G.rationale_md=Q.rationale_md;try{let z=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/dispositions`,{body:G});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}}),$.register({name:"typescape_attach_evidence",description:"Attach evidence to a thread. Evidence proves that feedback was addressed (e.g., commit SHA, proposed change, PR URL, or attestation).",inputSchema:_6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.thread_id)return V(new q(400,"missing_param","Missing required parameter: thread_id","local"));let G,z;if(Q.evidence_type){G=Q.evidence_type.trim(),z={};let U=["commit_sha","repo_url","message","proposed_change_id","patch_sha256","pr_url","pr_number","attestation_id","attestor","ticket_url","ticket_id","system","note_md"];for(let C of U)if(Q[C]!==void 0){let T=C==="note_md"?"text":C;z[T]=Q[C]}}else if(Q.evidence)G=typeof Q.evidence.type==="string"?Q.evidence.type.trim():"",z={...Q.evidence},delete z.type;else return V(new q(400,"missing_param","Missing required parameter: evidence_type","local"));if(!G)return V(new q(422,"invalid_argument","evidence_type is required","local"));let F={evidence_type:G,evidence_json:z};if(Q.dedupe_key)F.dedupe_key=Q.dedupe_key;try{let U=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/evidence`,{body:F});return v(U.body,U.requestId)}catch(U){if(U instanceof q)return V(U);throw U}});let e=null,Z=300000;async function A(){let O=Date.now();if(e&&O-e.fetchedAt<Z)return e.features;try{return e={features:(await W.get("/me/capabilities")).body.features??{},fetchedAt:O},e.features}catch(Q){if(Q instanceof q)throw Q;throw Q}}function I(O){return{content:[{type:"text",text:JSON.stringify({error:{code:"feature_disabled",feature:O,message:`Feature '${O}' is not enabled on this server`,request_id:"local"}},null,2)}],isError:!0}}$.register({name:"typescape_create_review_set",description:"Create a new review set (multi-file review pack). Requires features.review_sets to be enabled.",inputSchema:z6},async(O)=>{let Q=O;try{if(!(await A()).review_sets)return I("review_sets")}catch(C){if(C instanceof q)return V(C);throw C}if(!Q.source_type)return V(new q(400,"missing_param","Missing required parameter: source_type","local"));if(Q.source_type!=="git"&&Q.source_type!=="upload")return V(new q(422,"invalid_argument","source_type must be one of: git, upload","local"));let G=Array.isArray(Q.sessions)&&Q.sessions.length>0,z=Array.isArray(Q.files)&&Q.files.length>0;if(!G&&!z)return V(new q(400,"missing_param","At least one of sessions[] or files[] is required","local"));let F={source_type:Q.source_type};if(Q.title!==void 0)F.title=Q.title;if(Q.kind!==void 0)F.kind=Q.kind;if(G)F.sessions=Q.sessions;if(z)F.files=Q.files;if(Q.participants!==void 0)F.participants=Q.participants.map((C)=>{if(Array.isArray(C.roles)&&C.roles.length>0)return{email:C.email,roles:C.roles};if(C.role)return{email:C.email,roles:[C.role]};return C});let U={};if(Q.idempotency_key)U["Idempotency-Key"]=Q.idempotency_key;try{let C=await W.post("/review-sets",{body:F,headers:U});return v(C.body,C.requestId)}catch(C){if(C instanceof q)return V(C);throw C}}),$.register({name:"typescape_export_review_set",description:"Export feedback from a review set. Requires features.review_sets to be enabled.",inputSchema:w6},async(O)=>{let Q=O;try{if(!(await A()).review_sets)return I("review_sets")}catch(z){if(z instanceof q)return V(z);throw z}if(!Q.review_set_id)return V(new q(400,"missing_param","Missing required parameter: review_set_id","local"));let G={schema:Q.schema||"v1"};if(Q.view)G.view=Q.view;try{let z=await W.get(`/review-sets/${encodeURIComponent(Q.review_set_id)}/export`,{query:G});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}}),$.register({name:"typescape_create_review_ref",description:"Create a stable review reference that tracks HEAD session for doc/file/PR/custom keys. Always available (core primitive).",inputSchema:B6},async(O)=>{let Q=O;if(!Q.source_type)return V(new q(400,"missing_param","Missing required parameter: source_type","local"));if(!Q.kind)return V(new q(400,"missing_param","Missing required parameter: kind","local"));if(!Q.key)return V(new q(400,"missing_param","Missing required parameter: key","local"));if(!Q.head_session_id)return V(new q(400,"missing_param","Missing required parameter: head_session_id","local"));let G=Q.kind.trim().toLowerCase();if(!d9.has(G))return V(new q(400,"invalid_param",`Invalid parameter: kind must be one of ${I0.join(", ")}`,"local"));let z={source_type:Q.source_type,kind:G,key:Q.key,head_session_id:Q.head_session_id};if(Q.repo_id!==void 0)z.repo_id=Q.repo_id;if(Q.project_id!==void 0)z.project_id=Q.project_id;try{let F=await W.post("/review-refs",{body:z});return v(F.body,F.requestId)}catch(F){if(F instanceof q)return V(F);throw F}}),$.register({name:"typescape_resolve_review_ref",description:"Resolve a review ref to its current head session. Returns the head session ID and pinned content details.",inputSchema:q6},async(O)=>{let Q=O;if(!Q.review_ref_id)return V(new q(400,"missing_param","Missing required parameter: review_ref_id","local"));try{let G=await W.get(`/review-refs/${encodeURIComponent(Q.review_ref_id)}/resolve`);return v(G.body,G.requestId)}catch(G){if(G instanceof q)return V(G);throw G}}),$.register({name:"typescape_advance_review_ref",description:"Advance a review ref to a new head session. Use expected_head_session_id for optimistic concurrency.",inputSchema:V6},async(O)=>{let Q=O;if(!Q.review_ref_id)return V(new q(400,"missing_param","Missing required parameter: review_ref_id","local"));if(!Q.head_session_id)return V(new q(400,"missing_param","Missing required parameter: head_session_id","local"));let G={head_session_id:Q.head_session_id};if(Q.expected_head_session_id!==void 0)G.expected_head_session_id=Q.expected_head_session_id;try{let z=await W.post(`/review-refs/${encodeURIComponent(Q.review_ref_id)}/advance`,{body:G});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}}),$.register({name:"typescape_request_approval",description:"Request approval for a review session from specified approvers. Sends notifications via configured channels.",inputSchema:M6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.approver_emails||Q.approver_emails.length===0)return V(new q(400,"missing_param","Missing required parameter: approver_emails","local"));let G={approver_emails:Q.approver_emails};if(Q.message!==void 0)G.message=Q.message;if(Q.notify!==void 0)G.notify=Q.notify;let z={};if(Q.idempotency_key)z["Idempotency-Key"]=Q.idempotency_key;try{let F=await W.post(`/sessions/${encodeURIComponent(Q.session_id)}/request-approval`,{body:G,headers:z});return v(F.body,F.requestId)}catch(F){if(F instanceof q)return V(F);throw F}}),$.register({name:"typescape_get_status",description:"Get the policy verdict for a session. Returns pass/fail/needs_review with reasons. Requires features.policy to be enabled.",inputSchema:O6},async(O)=>{let Q=O;try{if(!(await A()).policy)return I("policy")}catch(z){if(z instanceof q)return V(z);throw z}if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));let G={};if(Q.simulate)G.simulate="true";if(Q.wait!==void 0)G.wait=String(Q.wait);try{let z=await W.get(`/sessions/${encodeURIComponent(Q.session_id)}/status`,{query:G});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}}),$.register({name:"typescape_run_checks",description:"Trigger quality checks (DocLint-as-Threads) for a session. Returns the check run ID. Requires features.checks to be enabled.",inputSchema:j6},async(O)=>{let Q=O;try{if(!(await A()).checks)return I("checks")}catch(G){if(G instanceof q)return V(G);throw G}if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));try{let G=await W.post(`/sessions/${encodeURIComponent(Q.session_id)}/run-checks`,{body:{}});return v(G.body,G.requestId)}catch(G){if(G instanceof q)return V(G);throw G}}),$.register({name:"typescape_account_usage",description:"Get account usage and quota information (sessions used/limit, remaining, and billing period).",inputSchema:L6},async()=>{try{let O=await W.get("/account/usage");return v(O.body,O.requestId)}catch(O){if(O instanceof q)return V(O);throw O}}),$.register({name:"typescape_account_plan",description:"Get account plan details (plan name/id, status, and limits metadata).",inputSchema:F6},async()=>{try{let O=await W.get("/account/plan");return v(O.body,O.requestId)}catch(O){if(O instanceof q)return V(O);throw O}}),$.register({name:"typescape_get_capabilities",description:"Get authenticated capabilities and effective feature flags. Returns the same payload shape as GET /v1/me/capabilities.",inputSchema:K6},async()=>{try{let O=await W.get("/me/capabilities");return v(O.body,O.requestId)}catch(O){if(O instanceof q)return V(O);throw O}});let Q1={type:"object",properties:{repo_id:{type:"string",description:"Repository identifier"},git_sha:{type:"string",description:"Git commit SHA for the snapshot"}},required:["repo_id","git_sha"]};$.register({name:"typescape_get_snapshot",description:"Get corpus snapshot metadata for a Git repo at a specific commit. Returns snapshot status, config hash, and source type. Requires features.corpus_snapshots to be enabled.",inputSchema:Q1},async(O)=>{let Q=O;try{if(!(await A()).corpus_snapshots)return I("corpus_snapshots")}catch(G){if(G instanceof q)return V(G);throw G}if(!Q.repo_id)return V(new q(400,"missing_param","Missing required parameter: repo_id","local"));if(!Q.git_sha)return V(new q(400,"missing_param","Missing required parameter: git_sha","local"));try{let G=await W.get(`/repos/${encodeURIComponent(Q.repo_id)}/snapshots/${encodeURIComponent(Q.git_sha)}`);return v(G.body,G.requestId)}catch(G){if(G instanceof q)return V(G);throw G}});let Z1={type:"object",properties:{repo_id:{type:"string",description:"Repository identifier"},git_sha:{type:"string",description:"Git commit SHA for the snapshot"},path:{type:"string",description:"Target file path to query backlinks for"},anchor:{type:"string",description:"Optional anchor within the file to narrow backlinks"}},required:["repo_id","git_sha","path"]};$.register({name:"typescape_list_backlinks",description:"List inbound backlinks for a target file (and optional anchor) within a corpus snapshot. Returns deterministic, authoritative data. Requires features.corpus_snapshots to be enabled.",inputSchema:Z1},async(O)=>{let Q=O;try{if(!(await A()).corpus_snapshots)return I("corpus_snapshots")}catch(G){if(G instanceof q)return V(G);throw G}if(!Q.repo_id)return V(new q(400,"missing_param","Missing required parameter: repo_id","local"));if(!Q.git_sha)return V(new q(400,"missing_param","Missing required parameter: git_sha","local"));if(!Q.path)return V(new q(400,"missing_param","Missing required parameter: path","local"));try{let G=new URLSearchParams({path:Q.path});if(Q.anchor)G.set("anchor",Q.anchor);let z=await W.get(`/repos/${encodeURIComponent(Q.repo_id)}/snapshots/${encodeURIComponent(Q.git_sha)}/backlinks?${G}`);return v(z.body,z.requestId)}catch(G){if(G instanceof q)return V(G);throw G}});let D4={type:"object",properties:{session_id:{type:"string",description:"Session identifier to compute impact radius for"}},required:["session_id"]};$.register({name:"typescape_get_impact",description:"Compute the impact radius for a session: which other files are affected by changes to the session's target file (via backlinks). Returns deterministic, authoritative data. Requires features.corpus_snapshots to be enabled.",inputSchema:D4},async(O)=>{let Q=O;try{if(!(await A()).corpus_snapshots)return I("corpus_snapshots")}catch(G){if(G instanceof q)return V(G);throw G}if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));try{let G=await W.get(`/sessions/${encodeURIComponent(Q.session_id)}/impact`);return v(G.body,G.requestId)}catch(G){if(G instanceof q)return V(G);throw G}});let R4={type:"object",properties:{repo_id:{type:"string",description:"Repository identifier"},file_path:{type:"string",description:"Optional file path to scope steering rules (returns only rules matching this path)"},format:{type:"string",enum:["structured","prompt_fragment"],description:'Output format: "structured" returns governed JSON rules (authoritative), "prompt_fragment" returns pre-computed Markdown text within token budget (may include non-authoritative assistive fields). Default: prompt_fragment.'},token_budget:{type:"number",description:"Maximum token count for prompt_fragment format (100-10000, default 2000)",minimum:100,maximum:1e4}},required:["repo_id"]};$.register({name:"typescape_get_steering",description:'Get active steering rules for a repository. format="structured" returns governed, human-approved rules (authoritative). format="prompt_fragment" returns pre-computed text within configured token budget. Requires steering to be enabled.',inputSchema:R4},async(O)=>{let Q=O;try{if(!(await A()).steering)return I("steering")}catch(z){if(z instanceof q)return V(z);throw z}if(!Q.repo_id)return V(new q(400,"missing_param","Missing required parameter: repo_id","local"));let G=Q.format??"prompt_fragment";try{let z=new URLSearchParams({format:G==="structured"?"structured.v1":"prompt_fragment.v1"});if(Q.file_path)z.set("file_path",Q.file_path);if(Q.token_budget!==void 0&&Q.token_budget!==null)z.set("token_budget",String(Q.token_budget));let F=await W.get(`/repos/${encodeURIComponent(Q.repo_id)}/steering-pack?${z}`),U=F.body;if(G==="prompt_fragment"&&U.prompt_fragment)U.non_authoritative=!0;return v(U,F.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let N4={type:"object",properties:{source_type:{type:"string",enum:["thread","doc_review","automation","admin"],description:"How this guideline was discovered"},title:{type:"string",description:"Short title for the proposed guideline"},content:{type:"string",description:"The proposed guideline text"},rationale:{type:"string",description:"Why this should become a guideline"},target_document:{type:"string",description:"Target canonical document path"},priority:{type:"string",enum:["low","medium","high","critical"],description:"Priority level (default: medium)"},thread_id:{type:"string",description:"Source thread ID (required when source_type is 'thread')"},tags:{type:"array",items:{type:"string"},description:"Classification tags"}},required:["source_type","title","content"]};$.register({name:"typescape_create_gci",description:"Create a guideline change item from observed patterns, thread feedback, or automated analysis. GCIs flow through the steering governance pipeline. Requires features.steering.",inputSchema:N4},async(O)=>{let Q=O;try{if(!(await A()).steering)return I("steering")}catch(z){if(z instanceof q)return V(z);throw z}if(!Q.source_type)return V(new q(400,"missing_param","Missing required parameter: source_type","local"));if(!Q.title)return V(new q(400,"missing_param","Missing required parameter: title","local"));if(!Q.content)return V(new q(400,"missing_param","Missing required parameter: content","local"));if(Q.source_type==="thread"&&!Q.thread_id)return V(new q(422,"invalid_argument","thread_id is required when source_type is 'thread'","local"));let G={source_type:Q.source_type,title:Q.title,content:Q.content};if(Q.rationale!==void 0)G.rationale=Q.rationale;if(Q.target_document!==void 0)G.target_document=Q.target_document;if(Q.priority!==void 0)G.priority=Q.priority;if(Q.thread_id!==void 0)G.thread_id=Q.thread_id;if(Q.tags!==void 0)G.tags=Q.tags;try{let z=Q.thread_id?"/steering/gcis/from-thread":"/steering/gcis",F=await W.post(z,{body:G});return v(F.body,F.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let A4={type:"object",properties:{status:{type:"string",enum:["pending","in_review","needs_revision","approved","rejected","published"],description:"Filter by lifecycle status (default: pending)"},limit:{type:"number",default:20,description:"Maximum number of results"}}};$.register({name:"typescape_list_gcis",description:"List guideline change items filtered by status. Use to monitor the guidelines pipeline. Requires features.steering.",inputSchema:A4},async(O)=>{let Q=O;try{if(!(await A()).steering)return I("steering")}catch(G){if(G instanceof q)return V(G);throw G}try{let G={};if(Q.status)G.status=Q.status;if(Q.limit!==void 0&&Q.limit!==null)G.limit=String(Q.limit);let z=new URLSearchParams(G).toString(),F=await W.get(`/steering/gcis${z?`?${z}`:""}`);return v(F.body,F.requestId)}catch(G){if(G instanceof q)return V(G);throw G}});let _4={type:"object",properties:{status:{type:"string",enum:["proposed","accepted","rejected","superseded"],description:"Filter by status (default: all)"},kind:{type:"string",enum:["terminology","style","structure","claim_policy","evidence_policy","voice","constraint"],description:"Filter by rule kind"},limit:{type:"number",default:20,description:"Maximum number of results"}}};$.register({name:"typescape_list_proposals",description:"List steering rule proposals. Proposals require operator approval before becoming active. Requires features.steering.",inputSchema:_4},async(O)=>{let Q=O;try{if(!(await A()).steering)return I("steering")}catch(G){if(G instanceof q)return V(G);throw G}try{let G={};if(Q.status)G.status=Q.status;if(Q.kind)G.kind=Q.kind;if(Q.limit!==void 0&&Q.limit!==null)G.limit=String(Q.limit);let z=new URLSearchParams(G).toString(),F=await W.get(`/steering/proposals${z?`?${z}`:""}`);return v(F.body,F.requestId)}catch(G){if(G instanceof q)return V(G);throw G}});let S4={type:"object",properties:{include_degraded:{type:"boolean",default:!0,description:"Include degraded rule details"}}};$.register({name:"typescape_steering_dashboard",description:"Get aggregate steering health metrics: active rule count, average health, degraded rules. Requires features.steering.",inputSchema:S4},async(O)=>{let Q=O;try{if(!(await A()).steering)return I("steering")}catch(G){if(G instanceof q)return V(G);throw G}try{let G=await W.get("/steering/dashboard/summary"),z={...G.body};if(Q.include_degraded!==!1){let F=await W.get("/steering/dashboard/degradation");z.degraded_rules=F.body.degraded_rules??[]}return v(z,G.requestId)}catch(G){if(G instanceof q)return V(G);throw G}});let E4={type:"object",properties:{gci_id:{type:"string",description:"GCI ID to promote (must be in 'approved' status)"},kind:{type:"string",enum:["terminology","style","structure","claim_policy","evidence_policy","voice","constraint"],description:"Rule kind for the proposal"},scope:{type:"string",description:"File path glob scope (e.g., 'docs/api/**')"},content_override:{type:"string",description:"Formal rule content override"}},required:["gci_id"]};$.register({name:"typescape_promote_gci",description:"Convert an approved GCI into a steering proposal for operator acceptance. Requires features.steering.",inputSchema:E4},async(O)=>{let Q=O;try{if(!(await A()).steering)return I("steering")}catch(z){if(z instanceof q)return V(z);throw z}if(!Q.gci_id)return V(new q(400,"missing_param","Missing required parameter: gci_id","local"));let G={};if(Q.kind!==void 0)G.kind=Q.kind;if(Q.scope!==void 0)G.scope=Q.scope;if(Q.content_override!==void 0)G.content_override=Q.content_override;try{let z=await W.post(`/steering/gcis/${encodeURIComponent(Q.gci_id)}/publish`,{body:G});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let v4={type:"object",properties:{proposal_id:{type:"string",description:"Proposal ID to act on"},decision:{type:"string",enum:["accept","reject","deprecate"],description:"Decision to apply"},notes:{type:"string",description:"Decision rationale (required for reject)"}},required:["proposal_id","decision"]};$.register({name:"typescape_decide_proposal",description:"Accept, reject, or deprecate a steering proposal. Accepting activates the rule immediately. Requires features.steering.",inputSchema:v4},async(O)=>{let Q=O;try{if(!(await A()).steering)return I("steering")}catch(U){if(U instanceof q)return V(U);throw U}if(!Q.proposal_id)return V(new q(400,"missing_param","Missing required parameter: proposal_id","local"));if(!Q.decision)return V(new q(400,"missing_param","Missing required parameter: decision","local"));if(Q.decision==="reject"&&!Q.notes)return V(new q(422,"invalid_argument","notes is required when decision is 'reject'","local"));let z={accept:"activate",reject:"reject",deprecate:"deprecate"}[Q.decision],F={};if(Q.notes!==void 0)F.notes=Q.notes;try{let U=await W.post(`/steering/proposals/${encodeURIComponent(Q.proposal_id)}/${z}`,{body:F});return v(U.body,U.requestId)}catch(U){if(U instanceof q)return V(U);throw U}});let k4={name:"typescape_list_repos",description:"List connected repositories in the workspace. Returns paginated list of repos with their origin URLs and metadata.",inputSchema:{type:"object",properties:{include_archived:{type:"boolean",description:"Include archived repositories (default: false)"},limit:{type:"number",description:"Maximum repos to return (1-100, default: 50)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}}};$.register(k4,async(O)=>{let Q=O,G={};if(Q.include_archived)G.include_archived="true";if(Q.limit!==void 0)G.limit=String(Q.limit);if(Q.cursor)G.cursor=Q.cursor;try{let z=await W.get("/repos",{query:G});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let C4={name:"typescape_connect_repo",description:"Connect a Git repository by its origin URL. If the URL is a GitHub repo and a GitHub App installation exists, it will be automatically linked for branch/file browsing.",inputSchema:{type:"object",properties:{origin_url:{type:"string",description:"Git remote URL (HTTPS or SSH), e.g. https://github.com/acme/docs"},display_name:{type:"string",description:"Human-readable display name (optional, auto-derived from URL)"}},required:["origin_url"]}};$.register(C4,async(O)=>{let Q=O;if(!Q.origin_url)return V(new q(400,"missing_param","Missing required parameter: origin_url","local"));let G={origin_url:Q.origin_url};if(Q.display_name)G.display_name=Q.display_name;try{let z=await W.post("/repos",{body:G});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let f4={name:"typescape_repo_branches",description:"List branches for a connected repository. Requires a GitHub App installation to be linked to the repo. Returns branch names and their head SHAs.",inputSchema:{type:"object",properties:{repo_id:{type:"string",description:"Repository ID (e.g. repo_abc123)"}},required:["repo_id"]}};$.register(f4,async(O)=>{let Q=O;if(!Q.repo_id)return V(new q(400,"missing_param","Missing required parameter: repo_id","local"));try{let G=await W.get(`/repos/${encodeURIComponent(Q.repo_id)}/branches`);return v(G.body,G.requestId)}catch(G){if(G instanceof q)return V(G);throw G}});let b4=5242880,P4=new Set(["image/png","image/jpeg","image/gif","image/webp"]),I4={name:"typescape_upload_reviewer_asset",description:"Upload a reviewer asset (image) to a session. Accepts base64-encoded image data (PNG, JPEG, GIF, WebP). Maximum size: 5MB. For larger files, use the CLI or web UI.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID to upload the asset to"},base64_content:{type:"string",description:"Base64-encoded image data"},mime_type:{type:"string",enum:["image/png","image/jpeg","image/gif","image/webp"],description:"MIME type of the image"},alt_text:{type:"string",description:"Alt text for the image (optional)"},filename:{type:"string",description:"Original filename (optional)"}},required:["session_id","base64_content","mime_type"]}};$.register(I4,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.base64_content)return V(new q(400,"missing_param","Missing required parameter: base64_content","local"));if(!Q.mime_type)return V(new q(400,"missing_param","Missing required parameter: mime_type","local"));if(!P4.has(Q.mime_type))return V(new q(415,"unsupported_media_type",`Unsupported MIME type "${Q.mime_type}". Allowed: PNG, JPEG, GIF, WebP.`,"local"));if(!L4.test(Q.base64_content))return V(new q(400,"invalid_base64","base64_content is not valid base64-encoded data","local"));let G;try{let U=Buffer.from(Q.base64_content,"base64");G=new Uint8Array(U)}catch{return V(new q(400,"invalid_base64","Failed to decode base64_content","local"))}if(G.byteLength>b4){let U=(G.byteLength/1048576).toFixed(1);return V(new q(413,"asset_too_large",`Image is ${U}MB, exceeding the 5MB MCP limit. Use the CLI ("typescape asset upload") or web UI for larger files.`,"local"))}let z=new Blob([G],{type:Q.mime_type}),F=new FormData;if(F.append("file",z,Q.filename||`upload.${v6(Q.mime_type)}`),F.append("mime_type",Q.mime_type),Q.alt_text)F.append("alt_text",Q.alt_text);try{let U=await W.postFormData(`/sessions/${encodeURIComponent(Q.session_id)}/reviewer-assets`,F);return v(U.body,U.requestId)}catch(U){if(U instanceof q)return V(U);throw U}}),$.register({name:"typescape_create_collection",description:"Create a new collection to group related review sessions. Requires collections_enabled feature flag. Returns the created collection with its ID.",inputSchema:S6},async(O)=>{let Q=O;if(!Q.name)return V(new q(400,"missing_param","Missing required parameter: name","local"));try{if(!(await A()).collections_enabled)return I("collections_enabled")}catch(z){if(z instanceof q)return V(z);throw z}let G={name:Q.name};if(Q.description!==void 0)G.description=Q.description;if(Q.color!==void 0)G.color=Q.color;try{let z=await W.post("/collections",{body:G});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}}),$.register({name:"typescape_add_session_to_collection",description:"Add a review session to an existing collection. Idempotent: re-adding an already-present session is a no-op. Requires collections_enabled feature flag.",inputSchema:E6},async(O)=>{let Q=O;if(!Q.collection_id)return V(new q(400,"missing_param","Missing required parameter: collection_id","local"));if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));try{if(!(await A()).collections_enabled)return I("collections_enabled")}catch(G){if(G instanceof q)return V(G);throw G}try{let G=await W.post(`/collections/${encodeURIComponent(Q.collection_id)}/sessions`,{body:{session_id:Q.session_id}});return v(G.body,G.requestId)}catch(G){if(G instanceof q)return V(G);throw G}})}function v6($){switch($){case"image/png":return"png";case"image/jpeg":return"jpg";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}var U4={TYPESCAPE_API_KEY:"Operator API token for authenticating with the Typescape API",TYPESCAPE_BASE_URL:"Base URL of the Typescape API server (e.g., https://review.example.com)"};function k6(){let $=process.env.TYPESCAPE_API_KEY,W=process.env.TYPESCAPE_BASE_URL,X=[];if(!$)X.push(`TYPESCAPE_API_KEY: ${U4.TYPESCAPE_API_KEY}`);if(!W)X.push(`TYPESCAPE_BASE_URL: ${U4.TYPESCAPE_BASE_URL}`);if(X.length>0){console.error("Error: Missing required environment variables:");for(let J of X)console.error(` - ${J}`);process.exit(1)}return{apiKey:$,baseUrl:W}}function C6($,W=e1){if(!$||$.trim().length===0)return{timeoutMs:W,warning:null};let X=$.trim();if(/^\d+$/.test(X)){let J=Number(X);if(J>=1000)return{timeoutMs:J,warning:null}}return{timeoutMs:W,warning:`Warning: Invalid TYPESCAPE_TIMEOUT_MS='${$}'. Using default ${W}ms.`}}async function f6(){let{apiKey:$,baseUrl:W}=k6(),X=process.env.TYPESCAPE_TIMEOUT_MS,J=C6(X,e1),Y=J.timeoutMs;if(J.warning)console.warn(J.warning);let w=m0(W,$,Y),B=h0();K4(B,w),await V4(B)}if(import.meta.main)f6().catch(($)=>{console.error("Fatal error:",$ instanceof Error?$.message:String($)),process.exit(1)});export{C6 as resolveTimeoutMs};
|
|
2
|
+
var x4=Object.create;var{getPrototypeOf:h4,defineProperty:h0,getOwnPropertyNames:Z4}=Object;var m4=Object.prototype.hasOwnProperty;function y4($){return this[$]}var l4,c4,Z0=($,W,X)=>{var J=$!=null&&typeof $==="object";if(J){var Y=W?l4??=new WeakMap:c4??=new WeakMap,w=Y.get($);if(w)return w}X=$!=null?x4(h4($)):{};let B=W||!$||!$.__esModule?h0(X,"default",{value:$,enumerable:!0}):X;for(let M of Z4($))if(!m4.call(B,M))h0(B,M,{get:y4.bind($,M),enumerable:!0});if(J)Y.set($,B);return B};var u4=($,W)=>()=>(W||$((W={exports:{}}).exports,W),W.exports);var F0=u4((x6,n4)=>{n4.exports={name:"@typescape-ai/mcp",version:"1.9.4",description:"Typescape MCP Server - Model Context Protocol integration for AI agents",type:"module",bin:{"typescape-mcp":"./dist/mcp.js"},files:["dist","README.md"],exports:{".":"./dist/mcp.js"},publishConfig:{access:"public"},scripts:{build:"bun build src/index.ts --outfile=dist/mcp.js --target=bun --bundle --minify",dev:"bun run --watch src/index.ts",test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src",prepublishOnly:"bun run build"},dependencies:{},devDependencies:{"@modelcontextprotocol/sdk":"1.0.4","@types/bun":"1.1.14","@typescape/schemas":"workspace:*",zod:"4.3.0"},engines:{bun:">=1.0.0"},keywords:["typescape","mcp","model-context-protocol","ai","claude","review","bun"],repository:{type:"git",url:"https://github.com/voidserf/typescape-docs.git",directory:"apps/mcp"},license:"MIT"}});function m0(){let $=new Map;return{register(W,X){$.set(W.name,{definition:W,handler:X})},getTools(){return Array.from($.values()).map((W)=>W.definition)},getHandler(W){return $.get(W)?.handler}}}var d4=await Promise.resolve().then(() => Z0(F0(),1)),y0=`typescape-mcp/${d4.version}`;class q extends Error{status;code;requestId;details;fixHint;constructor($,W,X,J,Y,w){super(X);this.status=$;this.code=W;this.requestId=J;this.details=Y;this.fixHint=w;this.name="ApiError"}}var e1=30000;function l0($,W,X=e1){let Y=$.replace(/\/$/,"");async function w(B,M,j={}){let N=`${Y}/v1${M}`;if(j.query&&Object.keys(j.query).length>0){let A=new URLSearchParams(j.query);N+=`?${A.toString()}`}let b={Authorization:`Bearer ${W}`,Accept:"application/json","User-Agent":y0,...j.headers};if(j.body!==void 0)b["Content-Type"]="application/json";let T;try{T=await fetch(N,{method:B,headers:b,body:j.body!==void 0?JSON.stringify(j.body):void 0,signal:AbortSignal.timeout(X)})}catch(A){if(A instanceof DOMException&&(A.name==="TimeoutError"||A.name==="AbortError")){let Z1=Math.round(X/1000);throw new q(0,"request_timeout",`Request timed out after ${Z1}s. Check your network connection and server URL.`,"unknown")}let J1=A instanceof Error?A.message:String(A);throw new q(0,"network_error",`Network error: ${J1}`,"unknown")}let m;if((T.headers.get("Content-Type")||"").includes("application/json"))try{m=await T.json()}catch{m={}}else m={};let y=m?.request_id||T.headers.get("X-Request-Id")||"unknown";if(!T.ok){let A=m,x=A.error?.code||"api_error",J1=A.error?.message||`API request failed with status ${T.status}`;throw new q(T.status,x,J1,y,A.error?.details,A.error?.fix_hint)}return{status:T.status,body:m,requestId:y}}return{async get(B,M){return w("GET",B,M)},async post(B,M){return w("POST",B,M)},async postFormData(B,M,j){let N=`${Y}/v1${B}`;if(j?.query&&Object.keys(j.query).length>0){let A=new URLSearchParams(j.query);N+=`?${A.toString()}`}let b={Authorization:`Bearer ${W}`,Accept:"application/json","User-Agent":y0,...j?.headers},T;try{T=await fetch(N,{method:"POST",headers:b,body:M,signal:AbortSignal.timeout(X)})}catch(A){if(A instanceof DOMException&&(A.name==="TimeoutError"||A.name==="AbortError")){let Z1=Math.round(X/1000);throw new q(0,"request_timeout",`Request timed out after ${Z1}s. Check your network connection and server URL.`,"unknown")}let J1=A instanceof Error?A.message:String(A);throw new q(0,"network_error",`Network error: ${J1}`,"unknown")}let m;if((T.headers.get("Content-Type")||"").includes("application/json"))try{m=await T.json()}catch{m={}}else m={};let y=m?.request_id||T.headers.get("X-Request-Id")||"unknown";if(!T.ok){let A=m,x=A.error?.code||"api_error",J1=A.error?.message||`API request failed with status ${T.status}`;throw new q(T.status,x,J1,y,A.error?.details,A.error?.fix_hint)}return{status:T.status,body:m,requestId:y}},request:w}}var P;(function($){$.assertEqual=(Y)=>Y;function W(Y){}$.assertIs=W;function X(Y){throw Error()}$.assertNever=X,$.arrayToEnum=(Y)=>{let w={};for(let B of Y)w[B]=B;return w},$.getValidEnumValues=(Y)=>{let w=$.objectKeys(Y).filter((M)=>typeof Y[Y[M]]!=="number"),B={};for(let M of w)B[M]=Y[M];return $.objectValues(B)},$.objectValues=(Y)=>{return $.objectKeys(Y).map(function(w){return Y[w]})},$.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let w=[];for(let B in Y)if(Object.prototype.hasOwnProperty.call(Y,B))w.push(B);return w},$.find=(Y,w)=>{for(let B of Y)if(w(B))return B;return},$.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&isFinite(Y)&&Math.floor(Y)===Y;function J(Y,w=" | "){return Y.map((B)=>typeof B==="string"?`'${B}'`:B).join(w)}$.joinValues=J,$.jsonStringifyReplacer=(Y,w)=>{if(typeof w==="bigint")return w.toString();return w}})(P||(P={}));var U0;(function($){$.mergeShapes=(W,X)=>{return{...W,...X}}})(U0||(U0={}));var D=P.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),w1=($)=>{switch(typeof $){case"undefined":return D.undefined;case"string":return D.string;case"number":return isNaN($)?D.nan:D.number;case"boolean":return D.boolean;case"function":return D.function;case"bigint":return D.bigint;case"symbol":return D.symbol;case"object":if(Array.isArray($))return D.array;if($===null)return D.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return D.promise;if(typeof Map<"u"&&$ instanceof Map)return D.map;if(typeof Set<"u"&&$ instanceof Set)return D.set;if(typeof Date<"u"&&$ instanceof Date)return D.date;return D.object;default:return D.unknown}},F=P.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"]),p4=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class d extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(X)=>{this.issues=[...this.issues,X]},this.addIssues=(X=[])=>{this.issues=[...this.issues,...X]};let W=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,W);else this.__proto__=W;this.name="ZodError",this.issues=$}format($){let W=$||function(Y){return Y.message},X={_errors:[]},J=(Y)=>{for(let w of Y.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)X._errors.push(W(w));else{let B=X,M=0;while(M<w.path.length){let j=w.path[M];if(M!==w.path.length-1)B[j]=B[j]||{_errors:[]};else B[j]=B[j]||{_errors:[]},B[j]._errors.push(W(w));B=B[j],M++}}};return J(this),X}static assert($){if(!($ instanceof d))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,P.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(W)=>W.message){let W={},X=[];for(let J of this.issues)if(J.path.length>0)W[J.path[0]]=W[J.path[0]]||[],W[J.path[0]].push($(J));else X.push($(J));return{formErrors:X,fieldErrors:W}}get formErrors(){return this.flatten()}}d.create=($)=>{return new d($)};var E1=($,W)=>{let X;switch($.code){case F.invalid_type:if($.received===D.undefined)X="Required";else X=`Expected ${$.expected}, received ${$.received}`;break;case F.invalid_literal:X=`Invalid literal value, expected ${JSON.stringify($.expected,P.jsonStringifyReplacer)}`;break;case F.unrecognized_keys:X=`Unrecognized key(s) in object: ${P.joinValues($.keys,", ")}`;break;case F.invalid_union:X="Invalid input";break;case F.invalid_union_discriminator:X=`Invalid discriminator value. Expected ${P.joinValues($.options)}`;break;case F.invalid_enum_value:X=`Invalid enum value. Expected ${P.joinValues($.options)}, received '${$.received}'`;break;case F.invalid_arguments:X="Invalid function arguments";break;case F.invalid_return_type:X="Invalid function return type";break;case F.invalid_date:X="Invalid date";break;case F.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(X=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")X=`${X} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)X=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)X=`Invalid input: must end with "${$.validation.endsWith}"`;else P.assertNever($.validation);else if($.validation!=="regex")X=`Invalid ${$.validation}`;else X="Invalid";break;case F.too_small:if($.type==="array")X=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")X=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")X=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")X=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else X="Invalid input";break;case F.too_big:if($.type==="array")X=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")X=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")X=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")X=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")X=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else X="Invalid input";break;case F.custom:X="Invalid input";break;case F.invalid_intersection_types:X="Intersection results could not be merged";break;case F.not_multiple_of:X=`Number must be a multiple of ${$.multipleOf}`;break;case F.not_finite:X="Number must be finite";break;default:X=W.defaultError,P.assertNever($)}return{message:X}},n0=E1;function i4($){n0=$}function $0(){return n0}var W0=($)=>{let{data:W,path:X,errorMaps:J,issueData:Y}=$,w=[...X,...Y.path||[]],B={...Y,path:w};if(Y.message!==void 0)return{...Y,path:w,message:Y.message};let M="",j=J.filter((N)=>!!N).slice().reverse();for(let N of j)M=N(B,{data:W,defaultError:M}).message;return{...Y,path:w,message:M}},o4=[];function U($,W){let X=$0(),J=W0({issueData:W,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,X,X===E1?void 0:E1].filter((Y)=>!!Y)});$.common.issues.push(J)}class c{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,W){let X=[];for(let J of W){if(J.status==="aborted")return E;if(J.status==="dirty")$.dirty();X.push(J.value)}return{status:$.value,value:X}}static async mergeObjectAsync($,W){let X=[];for(let J of W){let Y=await J.key,w=await J.value;X.push({key:Y,value:w})}return c.mergeObjectSync($,X)}static mergeObjectSync($,W){let X={};for(let J of W){let{key:Y,value:w}=J;if(Y.status==="aborted")return E;if(w.status==="aborted")return E;if(Y.status==="dirty")$.dirty();if(w.status==="dirty")$.dirty();if(Y.value!=="__proto__"&&(typeof w.value<"u"||J.alwaysSet))X[Y.value]=w.value}return{status:$.value,value:X}}}var E=Object.freeze({status:"aborted"}),_1=($)=>({status:"dirty",value:$}),u=($)=>({status:"valid",value:$}),D0=($)=>$.status==="aborted",N0=($)=>$.status==="dirty",L1=($)=>$.status==="valid",c1=($)=>typeof Promise<"u"&&$ instanceof Promise;function X0($,W,X,J){if(X==="a"&&!J)throw TypeError("Private accessor was defined without a getter");if(typeof W==="function"?$!==W||!J:!W.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?J:X==="a"?J.call($):J?J.value:W.get($)}function d0($,W,X,J,Y){if(J==="m")throw TypeError("Private method is not writable");if(J==="a"&&!Y)throw TypeError("Private accessor was defined without a setter");if(typeof W==="function"?$!==W||!Y:!W.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return J==="a"?Y.call($,X):Y?Y.value=X:W.set($,X),X}var R;(function($){$.errToObj=(W)=>typeof W==="string"?{message:W}:W||{},$.toString=(W)=>typeof W==="string"?W:W===null||W===void 0?void 0:W.message})(R||(R={}));var y1,l1;class s{constructor($,W,X,J){this._cachedPath=[],this.parent=$,this.data=W,this._path=X,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 c0=($,W)=>{if(L1(W))return{success:!0,data:W.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let X=new d($.common.issues);return this._error=X,this._error}}}};function k($){if(!$)return{};let{errorMap:W,invalid_type_error:X,required_error:J,description:Y}=$;if(W&&(X||J))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(W)return{errorMap:W,description:Y};return{errorMap:(B,M)=>{var j,N;let{message:b}=$;if(B.code==="invalid_enum_value")return{message:b!==null&&b!==void 0?b:M.defaultError};if(typeof M.data>"u")return{message:(j=b!==null&&b!==void 0?b:J)!==null&&j!==void 0?j:M.defaultError};if(B.code!=="invalid_type")return{message:M.defaultError};return{message:(N=b!==null&&b!==void 0?b:X)!==null&&N!==void 0?N:M.defaultError}},description:Y}}class C{get description(){return this._def.description}_getType($){return w1($.data)}_getOrReturnCtx($,W){return W||{common:$.parent.common,data:$.data,parsedType:w1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new c,ctx:{common:$.parent.common,data:$.data,parsedType:w1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let W=this._parse($);if(c1(W))throw Error("Synchronous parse encountered promise.");return W}_parseAsync($){let W=this._parse($);return Promise.resolve(W)}parse($,W){let X=this.safeParse($,W);if(X.success)return X.data;throw X.error}safeParse($,W){var X;let J={common:{issues:[],async:(X=W===null||W===void 0?void 0:W.async)!==null&&X!==void 0?X:!1,contextualErrorMap:W===null||W===void 0?void 0:W.errorMap},path:(W===null||W===void 0?void 0:W.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:w1($)},Y=this._parseSync({data:$,path:J.path,parent:J});return c0(J,Y)}"~validate"($){var W,X;let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:w1($)};if(!this["~standard"].async)try{let Y=this._parseSync({data:$,path:[],parent:J});return L1(Y)?{value:Y.value}:{issues:J.common.issues}}catch(Y){if((X=(W=Y===null||Y===void 0?void 0:Y.message)===null||W===void 0?void 0:W.toLowerCase())===null||X===void 0?void 0:X.includes("encountered"))this["~standard"].async=!0;J.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:J}).then((Y)=>L1(Y)?{value:Y.value}:{issues:J.common.issues})}async parseAsync($,W){let X=await this.safeParseAsync($,W);if(X.success)return X.data;throw X.error}async safeParseAsync($,W){let X={common:{issues:[],contextualErrorMap:W===null||W===void 0?void 0:W.errorMap,async:!0},path:(W===null||W===void 0?void 0:W.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:w1($)},J=this._parse({data:$,path:X.path,parent:X}),Y=await(c1(J)?J:Promise.resolve(J));return c0(X,Y)}refine($,W){let X=(J)=>{if(typeof W==="string"||typeof W>"u")return{message:W};else if(typeof W==="function")return W(J);else return W};return this._refinement((J,Y)=>{let w=$(J),B=()=>Y.addIssue({code:F.custom,...X(J)});if(typeof Promise<"u"&&w instanceof Promise)return w.then((M)=>{if(!M)return B(),!1;else return!0});if(!w)return B(),!1;else return!0})}refinement($,W){return this._refinement((X,J)=>{if(!$(X))return J.addIssue(typeof W==="function"?W(X,J):W),!1;else return!0})}_refinement($){return new o({schema:this,typeName:S.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:(W)=>this["~validate"](W)}}optional(){return r.create(this,this._def)}nullable(){return B1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return t.create(this)}promise(){return D1.create(this,this._def)}or($){return f1.create([this,$],this._def)}and($){return b1.create(this,$,this._def)}transform($){return new o({...k(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:$}})}default($){let W=typeof $==="function"?$:()=>$;return new g1({...k(this._def),innerType:this,defaultValue:W,typeName:S.ZodDefault})}brand(){return new Y0({typeName:S.ZodBranded,type:this,...k(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new x1({...k(this._def),innerType:this,catchValue:W,typeName:S.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return o1.create(this,$)}readonly(){return h1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var a4=/^c[^\s-]{8,}$/i,t4=/^[0-9a-z]+$/,r4=/^[0-9A-HJKMNP-TV-Z]{26}$/i,s4=/^[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,e4=/^[a-z0-9_-]{21}$/i,$9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,W9=/^[-+]?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)?)??$/,X9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Q9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",K0,Y9=/^(?:(?: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])$/,J9=/^(?:(?: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])$/,H9=/^(([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])$/,z9=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,w9=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,p0="((\\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])))",B9=new RegExp(`^${p0}$`);function i0($){let W="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if($.precision)W=`${W}\\.\\d{${$.precision}}`;else if($.precision==null)W=`${W}(\\.\\d+)?`;return W}function q9($){return new RegExp(`^${i0($)}$`)}function o0($){let W=`${p0}T${i0($)}`,X=[];if(X.push($.local?"Z?":"Z"),$.offset)X.push("([+-]\\d{2}:?\\d{2})");return W=`${W}(${X.join("|")})`,new RegExp(`^${W}$`)}function V9($,W){if((W==="v4"||!W)&&Y9.test($))return!0;if((W==="v6"||!W)&&H9.test($))return!0;return!1}function M9($,W){if(!$9.test($))return!1;try{let[X]=$.split("."),J=X.replace(/-/g,"+").replace(/_/g,"/").padEnd(X.length+(4-X.length%4)%4,"="),Y=JSON.parse(atob(J));if(typeof Y!=="object"||Y===null)return!1;if(!Y.typ||!Y.alg)return!1;if(W&&Y.alg!==W)return!1;return!0}catch(X){return!1}}function O9($,W){if((W==="v4"||!W)&&J9.test($))return!0;if((W==="v6"||!W)&&G9.test($))return!0;return!1}class a extends C{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==D.string){let Y=this._getOrReturnCtx($);return U(Y,{code:F.invalid_type,expected:D.string,received:Y.parsedType}),E}let X=new c,J=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.length<Y.value)J=this._getOrReturnCtx($,J),U(J,{code:F.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if($.data.length>Y.value)J=this._getOrReturnCtx($,J),U(J,{code:F.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="length"){let w=$.data.length>Y.value,B=$.data.length<Y.value;if(w||B){if(J=this._getOrReturnCtx($,J),w)U(J,{code:F.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(B)U(J,{code:F.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});X.dirty()}}else if(Y.kind==="email"){if(!X9.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"email",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="emoji"){if(!K0)K0=new RegExp(Q9,"u");if(!K0.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"emoji",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="uuid"){if(!s4.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"uuid",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="nanoid"){if(!e4.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"nanoid",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="cuid"){if(!a4.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"cuid",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="cuid2"){if(!t4.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"cuid2",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="ulid"){if(!r4.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"ulid",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="url")try{new URL($.data)}catch(w){J=this._getOrReturnCtx($,J),U(J,{validation:"url",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"regex",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="trim")$.data=$.data.trim();else if(Y.kind==="includes"){if(!$.data.includes(Y.value,Y.position))J=this._getOrReturnCtx($,J),U(J,{code:F.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),X.dirty()}else if(Y.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(Y.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(Y.kind==="startsWith"){if(!$.data.startsWith(Y.value))J=this._getOrReturnCtx($,J),U(J,{code:F.invalid_string,validation:{startsWith:Y.value},message:Y.message}),X.dirty()}else if(Y.kind==="endsWith"){if(!$.data.endsWith(Y.value))J=this._getOrReturnCtx($,J),U(J,{code:F.invalid_string,validation:{endsWith:Y.value},message:Y.message}),X.dirty()}else if(Y.kind==="datetime"){if(!o0(Y).test($.data))J=this._getOrReturnCtx($,J),U(J,{code:F.invalid_string,validation:"datetime",message:Y.message}),X.dirty()}else if(Y.kind==="date"){if(!B9.test($.data))J=this._getOrReturnCtx($,J),U(J,{code:F.invalid_string,validation:"date",message:Y.message}),X.dirty()}else if(Y.kind==="time"){if(!q9(Y).test($.data))J=this._getOrReturnCtx($,J),U(J,{code:F.invalid_string,validation:"time",message:Y.message}),X.dirty()}else if(Y.kind==="duration"){if(!W9.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"duration",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="ip"){if(!V9($.data,Y.version))J=this._getOrReturnCtx($,J),U(J,{validation:"ip",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="jwt"){if(!M9($.data,Y.alg))J=this._getOrReturnCtx($,J),U(J,{validation:"jwt",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="cidr"){if(!O9($.data,Y.version))J=this._getOrReturnCtx($,J),U(J,{validation:"cidr",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="base64"){if(!z9.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"base64",code:F.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="base64url"){if(!w9.test($.data))J=this._getOrReturnCtx($,J),U(J,{validation:"base64url",code:F.invalid_string,message:Y.message}),X.dirty()}else P.assertNever(Y);return{status:X.value,value:$.data}}_regex($,W,X){return this.refinement((J)=>$.test(J),{validation:W,code:F.invalid_string,...R.errToObj(X)})}_addCheck($){return new a({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...R.errToObj($)})}url($){return this._addCheck({kind:"url",...R.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...R.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...R.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...R.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...R.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...R.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...R.errToObj($)})}base64($){return this._addCheck({kind:"base64",...R.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...R.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...R.errToObj($)})}ip($){return this._addCheck({kind:"ip",...R.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...R.errToObj($)})}datetime($){var W,X;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)>"u"?null:$===null||$===void 0?void 0:$.precision,offset:(W=$===null||$===void 0?void 0:$.offset)!==null&&W!==void 0?W:!1,local:(X=$===null||$===void 0?void 0:$.local)!==null&&X!==void 0?X:!1,...R.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)>"u"?null:$===null||$===void 0?void 0:$.precision,...R.errToObj($===null||$===void 0?void 0:$.message)})}duration($){return this._addCheck({kind:"duration",...R.errToObj($)})}regex($,W){return this._addCheck({kind:"regex",regex:$,...R.errToObj(W)})}includes($,W){return this._addCheck({kind:"includes",value:$,position:W===null||W===void 0?void 0:W.position,...R.errToObj(W===null||W===void 0?void 0:W.message)})}startsWith($,W){return this._addCheck({kind:"startsWith",value:$,...R.errToObj(W)})}endsWith($,W){return this._addCheck({kind:"endsWith",value:$,...R.errToObj(W)})}min($,W){return this._addCheck({kind:"min",value:$,...R.errToObj(W)})}max($,W){return this._addCheck({kind:"max",value:$,...R.errToObj(W)})}length($,W){return this._addCheck({kind:"length",value:$,...R.errToObj(W)})}nonempty($){return this.min(1,R.errToObj($))}trim(){return new a({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new a({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new a({...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 W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxLength(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}a.create=($)=>{var W;return new a({checks:[],typeName:S.ZodString,coerce:(W=$===null||$===void 0?void 0:$.coerce)!==null&&W!==void 0?W:!1,...k($)})};function j9($,W){let X=($.toString().split(".")[1]||"").length,J=(W.toString().split(".")[1]||"").length,Y=X>J?X:J,w=parseInt($.toFixed(Y).replace(".","")),B=parseInt(W.toFixed(Y).replace(".",""));return w%B/Math.pow(10,Y)}class V1 extends C{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($)!==D.number){let Y=this._getOrReturnCtx($);return U(Y,{code:F.invalid_type,expected:D.number,received:Y.parsedType}),E}let X=void 0,J=new c;for(let Y of this._def.checks)if(Y.kind==="int"){if(!P.isInteger($.data))X=this._getOrReturnCtx($,X),U(X,{code:F.invalid_type,expected:"integer",received:"float",message:Y.message}),J.dirty()}else if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)X=this._getOrReturnCtx($,X),U(X,{code:F.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),J.dirty()}else if(Y.kind==="max"){if(Y.inclusive?$.data>Y.value:$.data>=Y.value)X=this._getOrReturnCtx($,X),U(X,{code:F.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),J.dirty()}else if(Y.kind==="multipleOf"){if(j9($.data,Y.value)!==0)X=this._getOrReturnCtx($,X),U(X,{code:F.not_multiple_of,multipleOf:Y.value,message:Y.message}),J.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite($.data))X=this._getOrReturnCtx($,X),U(X,{code:F.not_finite,message:Y.message}),J.dirty()}else P.assertNever(Y);return{status:J.value,value:$.data}}gte($,W){return this.setLimit("min",$,!0,R.toString(W))}gt($,W){return this.setLimit("min",$,!1,R.toString(W))}lte($,W){return this.setLimit("max",$,!0,R.toString(W))}lt($,W){return this.setLimit("max",$,!1,R.toString(W))}setLimit($,W,X,J){return new V1({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:X,message:R.toString(J)}]})}_addCheck($){return new V1({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:R.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:R.toString(W)})}finite($){return this._addCheck({kind:"finite",message:R.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString($)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&P.isInteger($.value))}get isFinite(){let $=null,W=null;for(let X of this._def.checks)if(X.kind==="finite"||X.kind==="int"||X.kind==="multipleOf")return!0;else if(X.kind==="min"){if(W===null||X.value>W)W=X.value}else if(X.kind==="max"){if($===null||X.value<$)$=X.value}return Number.isFinite(W)&&Number.isFinite($)}}V1.create=($)=>{return new V1({checks:[],typeName:S.ZodNumber,coerce:($===null||$===void 0?void 0:$.coerce)||!1,...k($)})};class M1 extends C{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch(Y){return this._getInvalidInput($)}if(this._getType($)!==D.bigint)return this._getInvalidInput($);let X=void 0,J=new c;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)X=this._getOrReturnCtx($,X),U(X,{code:F.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),J.dirty()}else if(Y.kind==="max"){if(Y.inclusive?$.data>Y.value:$.data>=Y.value)X=this._getOrReturnCtx($,X),U(X,{code:F.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),J.dirty()}else if(Y.kind==="multipleOf"){if($.data%Y.value!==BigInt(0))X=this._getOrReturnCtx($,X),U(X,{code:F.not_multiple_of,multipleOf:Y.value,message:Y.message}),J.dirty()}else P.assertNever(Y);return{status:J.value,value:$.data}}_getInvalidInput($){let W=this._getOrReturnCtx($);return U(W,{code:F.invalid_type,expected:D.bigint,received:W.parsedType}),E}gte($,W){return this.setLimit("min",$,!0,R.toString(W))}gt($,W){return this.setLimit("min",$,!1,R.toString(W))}lte($,W){return this.setLimit("max",$,!0,R.toString(W))}lt($,W){return this.setLimit("max",$,!1,R.toString(W))}setLimit($,W,X,J){return new M1({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:X,message:R.toString(J)}]})}_addCheck($){return new M1({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:R.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:R.toString(W)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}M1.create=($)=>{var W;return new M1({checks:[],typeName:S.ZodBigInt,coerce:(W=$===null||$===void 0?void 0:$.coerce)!==null&&W!==void 0?W:!1,...k($)})};class v1 extends C{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==D.boolean){let X=this._getOrReturnCtx($);return U(X,{code:F.invalid_type,expected:D.boolean,received:X.parsedType}),E}return u($.data)}}v1.create=($)=>{return new v1({typeName:S.ZodBoolean,coerce:($===null||$===void 0?void 0:$.coerce)||!1,...k($)})};class F1 extends C{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==D.date){let Y=this._getOrReturnCtx($);return U(Y,{code:F.invalid_type,expected:D.date,received:Y.parsedType}),E}if(isNaN($.data.getTime())){let Y=this._getOrReturnCtx($);return U(Y,{code:F.invalid_date}),E}let X=new c,J=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.getTime()<Y.value)J=this._getOrReturnCtx($,J),U(J,{code:F.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),X.dirty()}else if(Y.kind==="max"){if($.data.getTime()>Y.value)J=this._getOrReturnCtx($,J),U(J,{code:F.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),X.dirty()}else P.assertNever(Y);return{status:X.value,value:new Date($.data.getTime())}}_addCheck($){return new F1({...this._def,checks:[...this._def.checks,$]})}min($,W){return this._addCheck({kind:"min",value:$.getTime(),message:R.toString(W)})}max($,W){return this._addCheck({kind:"max",value:$.getTime(),message:R.toString(W)})}get minDate(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $!=null?new Date($):null}}F1.create=($)=>{return new F1({checks:[],coerce:($===null||$===void 0?void 0:$.coerce)||!1,typeName:S.ZodDate,...k($)})};class u1 extends C{_parse($){if(this._getType($)!==D.symbol){let X=this._getOrReturnCtx($);return U(X,{code:F.invalid_type,expected:D.symbol,received:X.parsedType}),E}return u($.data)}}u1.create=($)=>{return new u1({typeName:S.ZodSymbol,...k($)})};class k1 extends C{_parse($){if(this._getType($)!==D.undefined){let X=this._getOrReturnCtx($);return U(X,{code:F.invalid_type,expected:D.undefined,received:X.parsedType}),E}return u($.data)}}k1.create=($)=>{return new k1({typeName:S.ZodUndefined,...k($)})};class C1 extends C{_parse($){if(this._getType($)!==D.null){let X=this._getOrReturnCtx($);return U(X,{code:F.invalid_type,expected:D.null,received:X.parsedType}),E}return u($.data)}}C1.create=($)=>{return new C1({typeName:S.ZodNull,...k($)})};class K1 extends C{constructor(){super(...arguments);this._any=!0}_parse($){return u($.data)}}K1.create=($)=>{return new K1({typeName:S.ZodAny,...k($)})};class q1 extends C{constructor(){super(...arguments);this._unknown=!0}_parse($){return u($.data)}}q1.create=($)=>{return new q1({typeName:S.ZodUnknown,...k($)})};class X1 extends C{_parse($){let W=this._getOrReturnCtx($);return U(W,{code:F.invalid_type,expected:D.never,received:W.parsedType}),E}}X1.create=($)=>{return new X1({typeName:S.ZodNever,...k($)})};class n1 extends C{_parse($){if(this._getType($)!==D.undefined){let X=this._getOrReturnCtx($);return U(X,{code:F.invalid_type,expected:D.void,received:X.parsedType}),E}return u($.data)}}n1.create=($)=>{return new n1({typeName:S.ZodVoid,...k($)})};class t extends C{_parse($){let{ctx:W,status:X}=this._processInputParams($),J=this._def;if(W.parsedType!==D.array)return U(W,{code:F.invalid_type,expected:D.array,received:W.parsedType}),E;if(J.exactLength!==null){let w=W.data.length>J.exactLength.value,B=W.data.length<J.exactLength.value;if(w||B)U(W,{code:w?F.too_big:F.too_small,minimum:B?J.exactLength.value:void 0,maximum:w?J.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:J.exactLength.message}),X.dirty()}if(J.minLength!==null){if(W.data.length<J.minLength.value)U(W,{code:F.too_small,minimum:J.minLength.value,type:"array",inclusive:!0,exact:!1,message:J.minLength.message}),X.dirty()}if(J.maxLength!==null){if(W.data.length>J.maxLength.value)U(W,{code:F.too_big,maximum:J.maxLength.value,type:"array",inclusive:!0,exact:!1,message:J.maxLength.message}),X.dirty()}if(W.common.async)return Promise.all([...W.data].map((w,B)=>{return J.type._parseAsync(new s(W,w,W.path,B))})).then((w)=>{return c.mergeArray(X,w)});let Y=[...W.data].map((w,B)=>{return J.type._parseSync(new s(W,w,W.path,B))});return c.mergeArray(X,Y)}get element(){return this._def.type}min($,W){return new t({...this._def,minLength:{value:$,message:R.toString(W)}})}max($,W){return new t({...this._def,maxLength:{value:$,message:R.toString(W)}})}length($,W){return new t({...this._def,exactLength:{value:$,message:R.toString(W)}})}nonempty($){return this.min(1,$)}}t.create=($,W)=>{return new t({type:$,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...k(W)})};function A1($){if($ instanceof Z){let W={};for(let X in $.shape){let J=$.shape[X];W[X]=r.create(A1(J))}return new Z({...$._def,shape:()=>W})}else if($ instanceof t)return new t({...$._def,type:A1($.element)});else if($ instanceof r)return r.create(A1($.unwrap()));else if($ instanceof B1)return B1.create(A1($.unwrap()));else if($ instanceof Q1)return Q1.create($.items.map((W)=>A1(W)));else return $}class Z extends C{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(),W=P.objectKeys($);return this._cached={shape:$,keys:W}}_parse($){if(this._getType($)!==D.object){let j=this._getOrReturnCtx($);return U(j,{code:F.invalid_type,expected:D.object,received:j.parsedType}),E}let{status:X,ctx:J}=this._processInputParams($),{shape:Y,keys:w}=this._getCached(),B=[];if(!(this._def.catchall instanceof X1&&this._def.unknownKeys==="strip")){for(let j in J.data)if(!w.includes(j))B.push(j)}let M=[];for(let j of w){let N=Y[j],b=J.data[j];M.push({key:{status:"valid",value:j},value:N._parse(new s(J,b,J.path,j)),alwaysSet:j in J.data})}if(this._def.catchall instanceof X1){let j=this._def.unknownKeys;if(j==="passthrough")for(let N of B)M.push({key:{status:"valid",value:N},value:{status:"valid",value:J.data[N]}});else if(j==="strict"){if(B.length>0)U(J,{code:F.unrecognized_keys,keys:B}),X.dirty()}else if(j==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let j=this._def.catchall;for(let N of B){let b=J.data[N];M.push({key:{status:"valid",value:N},value:j._parse(new s(J,b,J.path,N)),alwaysSet:N in J.data})}}if(J.common.async)return Promise.resolve().then(async()=>{let j=[];for(let N of M){let b=await N.key,T=await N.value;j.push({key:b,value:T,alwaysSet:N.alwaysSet})}return j}).then((j)=>{return c.mergeObjectSync(X,j)});else return c.mergeObjectSync(X,M)}get shape(){return this._def.shape()}strict($){return R.errToObj,new Z({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(W,X)=>{var J,Y,w,B;let M=(w=(Y=(J=this._def).errorMap)===null||Y===void 0?void 0:Y.call(J,W,X).message)!==null&&w!==void 0?w:X.defaultError;if(W.code==="unrecognized_keys")return{message:(B=R.errToObj($).message)!==null&&B!==void 0?B:M};return{message:M}}}:{}})}strip(){return new Z({...this._def,unknownKeys:"strip"})}passthrough(){return new Z({...this._def,unknownKeys:"passthrough"})}extend($){return new Z({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new Z({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:S.ZodObject})}setKey($,W){return this.augment({[$]:W})}catchall($){return new Z({...this._def,catchall:$})}pick($){let W={};return P.objectKeys($).forEach((X)=>{if($[X]&&this.shape[X])W[X]=this.shape[X]}),new Z({...this._def,shape:()=>W})}omit($){let W={};return P.objectKeys(this.shape).forEach((X)=>{if(!$[X])W[X]=this.shape[X]}),new Z({...this._def,shape:()=>W})}deepPartial(){return A1(this)}partial($){let W={};return P.objectKeys(this.shape).forEach((X)=>{let J=this.shape[X];if($&&!$[X])W[X]=J;else W[X]=J.optional()}),new Z({...this._def,shape:()=>W})}required($){let W={};return P.objectKeys(this.shape).forEach((X)=>{if($&&!$[X])W[X]=this.shape[X];else{let Y=this.shape[X];while(Y instanceof r)Y=Y._def.innerType;W[X]=Y}}),new Z({...this._def,shape:()=>W})}keyof(){return a0(P.objectKeys(this.shape))}}Z.create=($,W)=>{return new Z({shape:()=>$,unknownKeys:"strip",catchall:X1.create(),typeName:S.ZodObject,...k(W)})};Z.strictCreate=($,W)=>{return new Z({shape:()=>$,unknownKeys:"strict",catchall:X1.create(),typeName:S.ZodObject,...k(W)})};Z.lazycreate=($,W)=>{return new Z({shape:$,unknownKeys:"strip",catchall:X1.create(),typeName:S.ZodObject,...k(W)})};class f1 extends C{_parse($){let{ctx:W}=this._processInputParams($),X=this._def.options;function J(Y){for(let B of Y)if(B.result.status==="valid")return B.result;for(let B of Y)if(B.result.status==="dirty")return W.common.issues.push(...B.ctx.common.issues),B.result;let w=Y.map((B)=>new d(B.ctx.common.issues));return U(W,{code:F.invalid_union,unionErrors:w}),E}if(W.common.async)return Promise.all(X.map(async(Y)=>{let w={...W,common:{...W.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:W.data,path:W.path,parent:w}),ctx:w}})).then(J);else{let Y=void 0,w=[];for(let M of X){let j={...W,common:{...W.common,issues:[]},parent:null},N=M._parseSync({data:W.data,path:W.path,parent:j});if(N.status==="valid")return N;else if(N.status==="dirty"&&!Y)Y={result:N,ctx:j};if(j.common.issues.length)w.push(j.common.issues)}if(Y)return W.common.issues.push(...Y.ctx.common.issues),Y.result;let B=w.map((M)=>new d(M));return U(W,{code:F.invalid_union,unionErrors:B}),E}}get options(){return this._def.options}}f1.create=($,W)=>{return new f1({options:$,typeName:S.ZodUnion,...k(W)})};var z1=($)=>{if($ instanceof P1)return z1($.schema);else if($ instanceof o)return z1($.innerType());else if($ instanceof I1)return[$.value];else if($ instanceof O1)return $.options;else if($ instanceof T1)return P.objectValues($.enum);else if($ instanceof g1)return z1($._def.innerType);else if($ instanceof k1)return[void 0];else if($ instanceof C1)return[null];else if($ instanceof r)return[void 0,...z1($.unwrap())];else if($ instanceof B1)return[null,...z1($.unwrap())];else if($ instanceof Y0)return z1($.unwrap());else if($ instanceof h1)return z1($.unwrap());else if($ instanceof x1)return z1($._def.innerType);else return[]};class Q0 extends C{_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==D.object)return U(W,{code:F.invalid_type,expected:D.object,received:W.parsedType}),E;let X=this.discriminator,J=W.data[X],Y=this.optionsMap.get(J);if(!Y)return U(W,{code:F.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[X]}),E;if(W.common.async)return Y._parseAsync({data:W.data,path:W.path,parent:W});else return Y._parseSync({data:W.data,path:W.path,parent:W})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,W,X){let J=new Map;for(let Y of W){let w=z1(Y.shape[$]);if(!w.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let B of w){if(J.has(B))throw Error(`Discriminator property ${String($)} has duplicate value ${String(B)}`);J.set(B,Y)}}return new Q0({typeName:S.ZodDiscriminatedUnion,discriminator:$,options:W,optionsMap:J,...k(X)})}}function R0($,W){let X=w1($),J=w1(W);if($===W)return{valid:!0,data:$};else if(X===D.object&&J===D.object){let Y=P.objectKeys(W),w=P.objectKeys($).filter((M)=>Y.indexOf(M)!==-1),B={...$,...W};for(let M of w){let j=R0($[M],W[M]);if(!j.valid)return{valid:!1};B[M]=j.data}return{valid:!0,data:B}}else if(X===D.array&&J===D.array){if($.length!==W.length)return{valid:!1};let Y=[];for(let w=0;w<$.length;w++){let B=$[w],M=W[w],j=R0(B,M);if(!j.valid)return{valid:!1};Y.push(j.data)}return{valid:!0,data:Y}}else if(X===D.date&&J===D.date&&+$===+W)return{valid:!0,data:$};else return{valid:!1}}class b1 extends C{_parse($){let{status:W,ctx:X}=this._processInputParams($),J=(Y,w)=>{if(D0(Y)||D0(w))return E;let B=R0(Y.value,w.value);if(!B.valid)return U(X,{code:F.invalid_intersection_types}),E;if(N0(Y)||N0(w))W.dirty();return{status:W.value,value:B.data}};if(X.common.async)return Promise.all([this._def.left._parseAsync({data:X.data,path:X.path,parent:X}),this._def.right._parseAsync({data:X.data,path:X.path,parent:X})]).then(([Y,w])=>J(Y,w));else return J(this._def.left._parseSync({data:X.data,path:X.path,parent:X}),this._def.right._parseSync({data:X.data,path:X.path,parent:X}))}}b1.create=($,W,X)=>{return new b1({left:$,right:W,typeName:S.ZodIntersection,...k(X)})};class Q1 extends C{_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==D.array)return U(X,{code:F.invalid_type,expected:D.array,received:X.parsedType}),E;if(X.data.length<this._def.items.length)return U(X,{code:F.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;if(!this._def.rest&&X.data.length>this._def.items.length)U(X,{code:F.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W.dirty();let Y=[...X.data].map((w,B)=>{let M=this._def.items[B]||this._def.rest;if(!M)return null;return M._parse(new s(X,w,X.path,B))}).filter((w)=>!!w);if(X.common.async)return Promise.all(Y).then((w)=>{return c.mergeArray(W,w)});else return c.mergeArray(W,Y)}get items(){return this._def.items}rest($){return new Q1({...this._def,rest:$})}}Q1.create=($,W)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Q1({items:$,typeName:S.ZodTuple,rest:null,...k(W)})};class d1 extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==D.object)return U(X,{code:F.invalid_type,expected:D.object,received:X.parsedType}),E;let J=[],Y=this._def.keyType,w=this._def.valueType;for(let B in X.data)J.push({key:Y._parse(new s(X,B,X.path,B)),value:w._parse(new s(X,X.data[B],X.path,B)),alwaysSet:B in X.data});if(X.common.async)return c.mergeObjectAsync(W,J);else return c.mergeObjectSync(W,J)}get element(){return this._def.valueType}static create($,W,X){if(W instanceof C)return new d1({keyType:$,valueType:W,typeName:S.ZodRecord,...k(X)});return new d1({keyType:a.create(),valueType:$,typeName:S.ZodRecord,...k(W)})}}class p1 extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==D.map)return U(X,{code:F.invalid_type,expected:D.map,received:X.parsedType}),E;let J=this._def.keyType,Y=this._def.valueType,w=[...X.data.entries()].map(([B,M],j)=>{return{key:J._parse(new s(X,B,X.path,[j,"key"])),value:Y._parse(new s(X,M,X.path,[j,"value"]))}});if(X.common.async){let B=new Map;return Promise.resolve().then(async()=>{for(let M of w){let j=await M.key,N=await M.value;if(j.status==="aborted"||N.status==="aborted")return E;if(j.status==="dirty"||N.status==="dirty")W.dirty();B.set(j.value,N.value)}return{status:W.value,value:B}})}else{let B=new Map;for(let M of w){let{key:j,value:N}=M;if(j.status==="aborted"||N.status==="aborted")return E;if(j.status==="dirty"||N.status==="dirty")W.dirty();B.set(j.value,N.value)}return{status:W.value,value:B}}}}p1.create=($,W,X)=>{return new p1({valueType:W,keyType:$,typeName:S.ZodMap,...k(X)})};class U1 extends C{_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==D.set)return U(X,{code:F.invalid_type,expected:D.set,received:X.parsedType}),E;let J=this._def;if(J.minSize!==null){if(X.data.size<J.minSize.value)U(X,{code:F.too_small,minimum:J.minSize.value,type:"set",inclusive:!0,exact:!1,message:J.minSize.message}),W.dirty()}if(J.maxSize!==null){if(X.data.size>J.maxSize.value)U(X,{code:F.too_big,maximum:J.maxSize.value,type:"set",inclusive:!0,exact:!1,message:J.maxSize.message}),W.dirty()}let Y=this._def.valueType;function w(M){let j=new Set;for(let N of M){if(N.status==="aborted")return E;if(N.status==="dirty")W.dirty();j.add(N.value)}return{status:W.value,value:j}}let B=[...X.data.values()].map((M,j)=>Y._parse(new s(X,M,X.path,j)));if(X.common.async)return Promise.all(B).then((M)=>w(M));else return w(B)}min($,W){return new U1({...this._def,minSize:{value:$,message:R.toString(W)}})}max($,W){return new U1({...this._def,maxSize:{value:$,message:R.toString(W)}})}size($,W){return this.min($,W).max($,W)}nonempty($){return this.min(1,$)}}U1.create=($,W)=>{return new U1({valueType:$,minSize:null,maxSize:null,typeName:S.ZodSet,...k(W)})};class S1 extends C{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==D.function)return U(W,{code:F.invalid_type,expected:D.function,received:W.parsedType}),E;function X(B,M){return W0({data:B,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,$0(),E1].filter((j)=>!!j),issueData:{code:F.invalid_arguments,argumentsError:M}})}function J(B,M){return W0({data:B,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,$0(),E1].filter((j)=>!!j),issueData:{code:F.invalid_return_type,returnTypeError:M}})}let Y={errorMap:W.common.contextualErrorMap},w=W.data;if(this._def.returns instanceof D1){let B=this;return u(async function(...M){let j=new d([]),N=await B._def.args.parseAsync(M,Y).catch((m)=>{throw j.addIssue(X(M,m)),j}),b=await Reflect.apply(w,this,N);return await B._def.returns._def.type.parseAsync(b,Y).catch((m)=>{throw j.addIssue(J(b,m)),j})})}else{let B=this;return u(function(...M){let j=B._def.args.safeParse(M,Y);if(!j.success)throw new d([X(M,j.error)]);let N=Reflect.apply(w,this,j.data),b=B._def.returns.safeParse(N,Y);if(!b.success)throw new d([J(N,b.error)]);return b.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new S1({...this._def,args:Q1.create($).rest(q1.create())})}returns($){return new S1({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,W,X){return new S1({args:$?$:Q1.create([]).rest(q1.create()),returns:W||q1.create(),typeName:S.ZodFunction,...k(X)})}}class P1 extends C{get schema(){return this._def.getter()}_parse($){let{ctx:W}=this._processInputParams($);return this._def.getter()._parse({data:W.data,path:W.path,parent:W})}}P1.create=($,W)=>{return new P1({getter:$,typeName:S.ZodLazy,...k(W)})};class I1 extends C{_parse($){if($.data!==this._def.value){let W=this._getOrReturnCtx($);return U(W,{received:W.data,code:F.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:$.data}}get value(){return this._def.value}}I1.create=($,W)=>{return new I1({value:$,typeName:S.ZodLiteral,...k(W)})};function a0($,W){return new O1({values:$,typeName:S.ZodEnum,...k(W)})}class O1 extends C{constructor(){super(...arguments);y1.set(this,void 0)}_parse($){if(typeof $.data!=="string"){let W=this._getOrReturnCtx($),X=this._def.values;return U(W,{expected:P.joinValues(X),received:W.parsedType,code:F.invalid_type}),E}if(!X0(this,y1,"f"))d0(this,y1,new Set(this._def.values),"f");if(!X0(this,y1,"f").has($.data)){let W=this._getOrReturnCtx($),X=this._def.values;return U(W,{received:W.data,code:F.invalid_enum_value,options:X}),E}return u($.data)}get options(){return this._def.values}get enum(){let $={};for(let W of this._def.values)$[W]=W;return $}get Values(){let $={};for(let W of this._def.values)$[W]=W;return $}get Enum(){let $={};for(let W of this._def.values)$[W]=W;return $}extract($,W=this._def){return O1.create($,{...this._def,...W})}exclude($,W=this._def){return O1.create(this.options.filter((X)=>!$.includes(X)),{...this._def,...W})}}y1=new WeakMap;O1.create=a0;class T1 extends C{constructor(){super(...arguments);l1.set(this,void 0)}_parse($){let W=P.getValidEnumValues(this._def.values),X=this._getOrReturnCtx($);if(X.parsedType!==D.string&&X.parsedType!==D.number){let J=P.objectValues(W);return U(X,{expected:P.joinValues(J),received:X.parsedType,code:F.invalid_type}),E}if(!X0(this,l1,"f"))d0(this,l1,new Set(P.getValidEnumValues(this._def.values)),"f");if(!X0(this,l1,"f").has($.data)){let J=P.objectValues(W);return U(X,{received:X.data,code:F.invalid_enum_value,options:J}),E}return u($.data)}get enum(){return this._def.values}}l1=new WeakMap;T1.create=($,W)=>{return new T1({values:$,typeName:S.ZodNativeEnum,...k(W)})};class D1 extends C{unwrap(){return this._def.type}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==D.promise&&W.common.async===!1)return U(W,{code:F.invalid_type,expected:D.promise,received:W.parsedType}),E;let X=W.parsedType===D.promise?W.data:Promise.resolve(W.data);return u(X.then((J)=>{return this._def.type.parseAsync(J,{path:W.path,errorMap:W.common.contextualErrorMap})}))}}D1.create=($,W)=>{return new D1({type:$,typeName:S.ZodPromise,...k(W)})};class o extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:W,ctx:X}=this._processInputParams($),J=this._def.effect||null,Y={addIssue:(w)=>{if(U(X,w),w.fatal)W.abort();else W.dirty()},get path(){return X.path}};if(Y.addIssue=Y.addIssue.bind(Y),J.type==="preprocess"){let w=J.transform(X.data,Y);if(X.common.async)return Promise.resolve(w).then(async(B)=>{if(W.value==="aborted")return E;let M=await this._def.schema._parseAsync({data:B,path:X.path,parent:X});if(M.status==="aborted")return E;if(M.status==="dirty")return _1(M.value);if(W.value==="dirty")return _1(M.value);return M});else{if(W.value==="aborted")return E;let B=this._def.schema._parseSync({data:w,path:X.path,parent:X});if(B.status==="aborted")return E;if(B.status==="dirty")return _1(B.value);if(W.value==="dirty")return _1(B.value);return B}}if(J.type==="refinement"){let w=(B)=>{let M=J.refinement(B,Y);if(X.common.async)return Promise.resolve(M);if(M instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return B};if(X.common.async===!1){let B=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(B.status==="aborted")return E;if(B.status==="dirty")W.dirty();return w(B.value),{status:W.value,value:B.value}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((B)=>{if(B.status==="aborted")return E;if(B.status==="dirty")W.dirty();return w(B.value).then(()=>{return{status:W.value,value:B.value}})})}if(J.type==="transform")if(X.common.async===!1){let w=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(!L1(w))return w;let B=J.transform(w.value,Y);if(B instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:W.value,value:B}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((w)=>{if(!L1(w))return w;return Promise.resolve(J.transform(w.value,Y)).then((B)=>({status:W.value,value:B}))});P.assertNever(J)}}o.create=($,W,X)=>{return new o({schema:$,typeName:S.ZodEffects,effect:W,...k(X)})};o.createWithPreprocess=($,W,X)=>{return new o({schema:W,effect:{type:"preprocess",transform:$},typeName:S.ZodEffects,...k(X)})};class r extends C{_parse($){if(this._getType($)===D.undefined)return u(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}r.create=($,W)=>{return new r({innerType:$,typeName:S.ZodOptional,...k(W)})};class B1 extends C{_parse($){if(this._getType($)===D.null)return u(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}B1.create=($,W)=>{return new B1({innerType:$,typeName:S.ZodNullable,...k(W)})};class g1 extends C{_parse($){let{ctx:W}=this._processInputParams($),X=W.data;if(W.parsedType===D.undefined)X=this._def.defaultValue();return this._def.innerType._parse({data:X,path:W.path,parent:W})}removeDefault(){return this._def.innerType}}g1.create=($,W)=>{return new g1({innerType:$,typeName:S.ZodDefault,defaultValue:typeof W.default==="function"?W.default:()=>W.default,...k(W)})};class x1 extends C{_parse($){let{ctx:W}=this._processInputParams($),X={...W,common:{...W.common,issues:[]}},J=this._def.innerType._parse({data:X.data,path:X.path,parent:{...X}});if(c1(J))return J.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new d(X.common.issues)},input:X.data})}});else return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new d(X.common.issues)},input:X.data})}}removeCatch(){return this._def.innerType}}x1.create=($,W)=>{return new x1({innerType:$,typeName:S.ZodCatch,catchValue:typeof W.catch==="function"?W.catch:()=>W.catch,...k(W)})};class i1 extends C{_parse($){if(this._getType($)!==D.nan){let X=this._getOrReturnCtx($);return U(X,{code:F.invalid_type,expected:D.nan,received:X.parsedType}),E}return{status:"valid",value:$.data}}}i1.create=($)=>{return new i1({typeName:S.ZodNaN,...k($)})};var L9=Symbol("zod_brand");class Y0 extends C{_parse($){let{ctx:W}=this._processInputParams($),X=W.data;return this._def.type._parse({data:X,path:W.path,parent:W})}unwrap(){return this._def.type}}class o1 extends C{_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:X.data,path:X.path,parent:X});if(Y.status==="aborted")return E;if(Y.status==="dirty")return W.dirty(),_1(Y.value);else return this._def.out._parseAsync({data:Y.value,path:X.path,parent:X})})();else{let J=this._def.in._parseSync({data:X.data,path:X.path,parent:X});if(J.status==="aborted")return E;if(J.status==="dirty")return W.dirty(),{status:"dirty",value:J.value};else return this._def.out._parseSync({data:J.value,path:X.path,parent:X})}}static create($,W){return new o1({in:$,out:W,typeName:S.ZodPipeline})}}class h1 extends C{_parse($){let W=this._def.innerType._parse($),X=(J)=>{if(L1(J))J.value=Object.freeze(J.value);return J};return c1(W)?W.then((J)=>X(J)):X(W)}unwrap(){return this._def.innerType}}h1.create=($,W)=>{return new h1({innerType:$,typeName:S.ZodReadonly,...k(W)})};function t0($,W={},X){if($)return K1.create().superRefine((J,Y)=>{var w,B;if(!$(J)){let M=typeof W==="function"?W(J):typeof W==="string"?{message:W}:W,j=(B=(w=M.fatal)!==null&&w!==void 0?w:X)!==null&&B!==void 0?B:!0,N=typeof M==="string"?{message:M}:M;Y.addIssue({code:"custom",...N,fatal:j})}});return K1.create()}var F9={object:Z.lazycreate},S;(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"})(S||(S={}));var K9=($,W={message:`Input not instance of ${$.name}`})=>t0((X)=>X instanceof $,W),r0=a.create,s0=V1.create,U9=i1.create,D9=M1.create,e0=v1.create,N9=F1.create,R9=u1.create,A9=k1.create,_9=C1.create,S9=K1.create,E9=q1.create,v9=X1.create,k9=n1.create,C9=t.create,f9=Z.create,b9=Z.strictCreate,P9=f1.create,I9=Q0.create,T9=b1.create,g9=Q1.create,x9=d1.create,h9=p1.create,Z9=U1.create,m9=S1.create,y9=P1.create,l9=I1.create,c9=O1.create,u9=T1.create,n9=D1.create,u0=o.create,d9=r.create,p9=B1.create,i9=o.createWithPreprocess,o9=o1.create,a9=()=>r0().optional(),t9=()=>s0().optional(),r9=()=>e0().optional(),s9={string:($)=>a.create({...$,coerce:!0}),number:($)=>V1.create({...$,coerce:!0}),boolean:($)=>v1.create({...$,coerce:!0}),bigint:($)=>M1.create({...$,coerce:!0}),date:($)=>F1.create({...$,coerce:!0})},e9=E,G=Object.freeze({__proto__:null,defaultErrorMap:E1,setErrorMap:i4,getErrorMap:$0,makeIssue:W0,EMPTY_PATH:o4,addIssueToContext:U,ParseStatus:c,INVALID:E,DIRTY:_1,OK:u,isAborted:D0,isDirty:N0,isValid:L1,isAsync:c1,get util(){return P},get objectUtil(){return U0},ZodParsedType:D,getParsedType:w1,ZodType:C,datetimeRegex:o0,ZodString:a,ZodNumber:V1,ZodBigInt:M1,ZodBoolean:v1,ZodDate:F1,ZodSymbol:u1,ZodUndefined:k1,ZodNull:C1,ZodAny:K1,ZodUnknown:q1,ZodNever:X1,ZodVoid:n1,ZodArray:t,ZodObject:Z,ZodUnion:f1,ZodDiscriminatedUnion:Q0,ZodIntersection:b1,ZodTuple:Q1,ZodRecord:d1,ZodMap:p1,ZodSet:U1,ZodFunction:S1,ZodLazy:P1,ZodLiteral:I1,ZodEnum:O1,ZodNativeEnum:T1,ZodPromise:D1,ZodEffects:o,ZodTransformer:o,ZodOptional:r,ZodNullable:B1,ZodDefault:g1,ZodCatch:x1,ZodNaN:i1,BRAND:L9,ZodBranded:Y0,ZodPipeline:o1,ZodReadonly:h1,custom:t0,Schema:C,ZodSchema:C,late:F9,get ZodFirstPartyTypeKind(){return S},coerce:s9,any:S9,array:C9,bigint:D9,boolean:e0,date:N9,discriminatedUnion:I9,effect:u0,enum:c9,function:m9,instanceof:K9,intersection:T9,lazy:y9,literal:l9,map:h9,nan:U9,nativeEnum:u9,never:v9,null:_9,nullable:p9,number:s0,object:f9,oboolean:r9,onumber:t9,optional:d9,ostring:a9,pipeline:o9,preprocess:i9,promise:n9,record:x9,set:Z9,strictObject:b9,string:r0,symbol:R9,transformer:u0,tuple:g9,undefined:A9,union:P9,unknown:E9,void:k9,NEVER:e9,ZodIssueCode:F,quotelessJson:p4,ZodError:d});var A0="2024-11-05",$4=[A0,"2024-10-07"],J0="2.0",W4=G.union([G.string(),G.number().int()]),X4=G.string(),e=G.object({_meta:G.optional(G.object({progressToken:G.optional(W4)}).passthrough())}).passthrough(),p=G.object({method:G.string(),params:G.optional(e)}),a1=G.object({_meta:G.optional(G.object({}).passthrough())}).passthrough(),Y1=G.object({method:G.string(),params:G.optional(a1)}),$1=G.object({_meta:G.optional(G.object({}).passthrough())}).passthrough(),H0=G.union([G.string(),G.number().int()]),$2=G.object({jsonrpc:G.literal(J0),id:H0}).merge(p).strict(),W2=G.object({jsonrpc:G.literal(J0)}).merge(Y1).strict(),X2=G.object({jsonrpc:G.literal(J0),id:H0,result:$1}).strict(),N1;(function($){$[$.ConnectionClosed=-1]="ConnectionClosed",$[$.RequestTimeout=-2]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError"})(N1||(N1={}));var Q2=G.object({jsonrpc:G.literal(J0),id:H0,error:G.object({code:G.number().int(),message:G.string(),data:G.optional(G.unknown())})}).strict(),Q4=G.union([$2,W2,X2,Q2]),G0=$1.strict(),z0=Y1.extend({method:G.literal("notifications/cancelled"),params:a1.extend({requestId:H0,reason:G.string().optional()})}),Y4=G.object({name:G.string(),version:G.string()}).passthrough(),Y2=G.object({experimental:G.optional(G.object({}).passthrough()),sampling:G.optional(G.object({}).passthrough()),roots:G.optional(G.object({listChanged:G.optional(G.boolean())}).passthrough())}).passthrough(),_0=p.extend({method:G.literal("initialize"),params:e.extend({protocolVersion:G.string(),capabilities:Y2,clientInfo:Y4})}),J2=G.object({experimental:G.optional(G.object({}).passthrough()),logging:G.optional(G.object({}).passthrough()),prompts:G.optional(G.object({listChanged:G.optional(G.boolean())}).passthrough()),resources:G.optional(G.object({subscribe:G.optional(G.boolean()),listChanged:G.optional(G.boolean())}).passthrough()),tools:G.optional(G.object({listChanged:G.optional(G.boolean())}).passthrough())}).passthrough(),H2=$1.extend({protocolVersion:G.string(),capabilities:J2,serverInfo:Y4}),S0=Y1.extend({method:G.literal("notifications/initialized")}),w0=p.extend({method:G.literal("ping")}),G2=G.object({progress:G.number(),total:G.optional(G.number())}).passthrough(),B0=Y1.extend({method:G.literal("notifications/progress"),params:a1.merge(G2).extend({progressToken:W4})}),q0=p.extend({params:e.extend({cursor:G.optional(X4)}).optional()}),V0=$1.extend({nextCursor:G.optional(X4)}),J4=G.object({uri:G.string(),mimeType:G.optional(G.string())}).passthrough(),H4=J4.extend({text:G.string()}),G4=J4.extend({blob:G.string().base64()}),z2=G.object({uri:G.string(),name:G.string(),description:G.optional(G.string()),mimeType:G.optional(G.string())}).passthrough(),w2=G.object({uriTemplate:G.string(),name:G.string(),description:G.optional(G.string()),mimeType:G.optional(G.string())}).passthrough(),B2=q0.extend({method:G.literal("resources/list")}),q2=V0.extend({resources:G.array(z2)}),V2=q0.extend({method:G.literal("resources/templates/list")}),M2=V0.extend({resourceTemplates:G.array(w2)}),O2=p.extend({method:G.literal("resources/read"),params:e.extend({uri:G.string()})}),j2=$1.extend({contents:G.array(G.union([H4,G4]))}),L2=Y1.extend({method:G.literal("notifications/resources/list_changed")}),F2=p.extend({method:G.literal("resources/subscribe"),params:e.extend({uri:G.string()})}),K2=p.extend({method:G.literal("resources/unsubscribe"),params:e.extend({uri:G.string()})}),U2=Y1.extend({method:G.literal("notifications/resources/updated"),params:a1.extend({uri:G.string()})}),D2=G.object({name:G.string(),description:G.optional(G.string()),required:G.optional(G.boolean())}).passthrough(),N2=G.object({name:G.string(),description:G.optional(G.string()),arguments:G.optional(G.array(D2))}).passthrough(),R2=q0.extend({method:G.literal("prompts/list")}),A2=V0.extend({prompts:G.array(N2)}),_2=p.extend({method:G.literal("prompts/get"),params:e.extend({name:G.string(),arguments:G.optional(G.record(G.string()))})}),M0=G.object({type:G.literal("text"),text:G.string()}).passthrough(),O0=G.object({type:G.literal("image"),data:G.string().base64(),mimeType:G.string()}).passthrough(),z4=G.object({type:G.literal("resource"),resource:G.union([H4,G4])}).passthrough(),S2=G.object({role:G.enum(["user","assistant"]),content:G.union([M0,O0,z4])}).passthrough(),E2=$1.extend({description:G.optional(G.string()),messages:G.array(S2)}),v2=Y1.extend({method:G.literal("notifications/prompts/list_changed")}),k2=G.object({name:G.string(),description:G.optional(G.string()),inputSchema:G.object({type:G.literal("object"),properties:G.optional(G.object({}).passthrough())}).passthrough()}).passthrough(),E0=q0.extend({method:G.literal("tools/list")}),C2=V0.extend({tools:G.array(k2)}),w4=$1.extend({content:G.array(G.union([M0,O0,z4])),isError:G.boolean().default(!1).optional()}),y6=w4.or($1.extend({toolResult:G.unknown()})),v0=p.extend({method:G.literal("tools/call"),params:e.extend({name:G.string(),arguments:G.optional(G.record(G.unknown()))})}),f2=Y1.extend({method:G.literal("notifications/tools/list_changed")}),B4=G.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),b2=p.extend({method:G.literal("logging/setLevel"),params:e.extend({level:B4})}),P2=Y1.extend({method:G.literal("notifications/message"),params:a1.extend({level:B4,logger:G.optional(G.string()),data:G.unknown()})}),I2=G.object({name:G.string().optional()}).passthrough(),T2=G.object({hints:G.optional(G.array(I2)),costPriority:G.optional(G.number().min(0).max(1)),speedPriority:G.optional(G.number().min(0).max(1)),intelligencePriority:G.optional(G.number().min(0).max(1))}).passthrough(),g2=G.object({role:G.enum(["user","assistant"]),content:G.union([M0,O0])}).passthrough(),x2=p.extend({method:G.literal("sampling/createMessage"),params:e.extend({messages:G.array(g2),systemPrompt:G.optional(G.string()),includeContext:G.optional(G.enum(["none","thisServer","allServers"])),temperature:G.optional(G.number()),maxTokens:G.number().int(),stopSequences:G.optional(G.array(G.string())),metadata:G.optional(G.object({}).passthrough()),modelPreferences:G.optional(T2)})}),k0=$1.extend({model:G.string(),stopReason:G.optional(G.enum(["endTurn","stopSequence","maxTokens"]).or(G.string())),role:G.enum(["user","assistant"]),content:G.discriminatedUnion("type",[M0,O0])}),h2=G.object({type:G.literal("ref/resource"),uri:G.string()}).passthrough(),Z2=G.object({type:G.literal("ref/prompt"),name:G.string()}).passthrough(),m2=p.extend({method:G.literal("completion/complete"),params:e.extend({ref:G.union([Z2,h2]),argument:G.object({name:G.string(),value:G.string()}).passthrough()})}),y2=$1.extend({completion:G.object({values:G.array(G.string()).max(100),total:G.optional(G.number().int()),hasMore:G.optional(G.boolean())}).passthrough()}),l2=G.object({uri:G.string().startsWith("file://"),name:G.optional(G.string())}).passthrough(),c2=p.extend({method:G.literal("roots/list")}),C0=$1.extend({roots:G.array(l2)}),u2=Y1.extend({method:G.literal("notifications/roots/list_changed")}),l6=G.union([w0,_0,m2,b2,_2,R2,B2,V2,O2,F2,K2,v0,E0]),c6=G.union([z0,B0,S0,u2]),u6=G.union([G0,k0,C0]),n6=G.union([w0,x2,c2]),d6=G.union([z0,B0,P2,U2,L2,f2,v2]),p6=G.union([G0,H2,y2,E2,A2,q2,M2,j2,w4,C2]);class t1 extends Error{constructor($,W,X){super(`MCP error ${$}: ${W}`);this.code=$,this.data=X}}var n2=60000;class f0{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(z0,(W)=>{let X=this._requestHandlerAbortControllers.get(W.params.requestId);X===null||X===void 0||X.abort(W.params.reason)}),this.setNotificationHandler(B0,(W)=>{this._onprogress(W)}),this.setRequestHandler(w0,(W)=>({}))}async connect($){this._transport=$,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=(W)=>{this._onerror(W)},this._transport.onmessage=(W)=>{if(!("method"in W))this._onresponse(W);else if("id"in W)this._onrequest(W);else this._onnotification(W)},await this._transport.start()}_onclose(){var $;let W=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,($=this.onclose)===null||$===void 0||$.call(this);let X=new t1(N1.ConnectionClosed,"Connection closed");for(let J of W.values())J(X)}_onerror($){var W;(W=this.onerror)===null||W===void 0||W.call(this,$)}_onnotification($){var W;let X=(W=this._notificationHandlers.get($.method))!==null&&W!==void 0?W:this.fallbackNotificationHandler;if(X===void 0)return;Promise.resolve().then(()=>X($)).catch((J)=>this._onerror(Error(`Uncaught error in notification handler: ${J}`)))}_onrequest($){var W,X;let J=(W=this._requestHandlers.get($.method))!==null&&W!==void 0?W:this.fallbackRequestHandler;if(J===void 0){(X=this._transport)===null||X===void 0||X.send({jsonrpc:"2.0",id:$.id,error:{code:N1.MethodNotFound,message:"Method not found"}}).catch((w)=>this._onerror(Error(`Failed to send an error response: ${w}`)));return}let Y=new AbortController;this._requestHandlerAbortControllers.set($.id,Y),Promise.resolve().then(()=>J($,{signal:Y.signal})).then((w)=>{var B;if(Y.signal.aborted)return;return(B=this._transport)===null||B===void 0?void 0:B.send({result:w,jsonrpc:"2.0",id:$.id})},(w)=>{var B,M;if(Y.signal.aborted)return;return(B=this._transport)===null||B===void 0?void 0:B.send({jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(w.code)?w.code:N1.InternalError,message:(M=w.message)!==null&&M!==void 0?M:"Internal error"}})}).catch((w)=>this._onerror(Error(`Failed to send response: ${w}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:W,...X}=$.params,J=this._progressHandlers.get(Number(W));if(J===void 0){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}J(X)}_onresponse($){let W=$.id,X=this._responseHandlers.get(Number(W));if(X===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}if(this._responseHandlers.delete(Number(W)),this._progressHandlers.delete(Number(W)),"result"in $)X($);else{let J=new t1($.error.code,$.error.message,$.error.data);X(J)}}get transport(){return this._transport}async close(){var $;await(($=this._transport)===null||$===void 0?void 0:$.close())}request($,W,X){return new Promise((J,Y)=>{var w,B,M,j;if(!this._transport){Y(Error("Not connected"));return}if(((w=this._options)===null||w===void 0?void 0:w.enforceStrictCapabilities)===!0)this.assertCapabilityForMethod($.method);(B=X===null||X===void 0?void 0:X.signal)===null||B===void 0||B.throwIfAborted();let N=this._requestMessageId++,b={...$,jsonrpc:"2.0",id:N};if(X===null||X===void 0?void 0:X.onprogress)this._progressHandlers.set(N,X.onprogress),b.params={...$.params,_meta:{progressToken:N}};let T=void 0;this._responseHandlers.set(N,(y)=>{var A;if(T!==void 0)clearTimeout(T);if((A=X===null||X===void 0?void 0:X.signal)===null||A===void 0?void 0:A.aborted)return;if(y instanceof Error)return Y(y);try{let x=W.parse(y.result);J(x)}catch(x){Y(x)}});let m=(y)=>{var A;this._responseHandlers.delete(N),this._progressHandlers.delete(N),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:N,reason:String(y)}}).catch((x)=>this._onerror(Error(`Failed to send cancellation: ${x}`))),Y(y)};(M=X===null||X===void 0?void 0:X.signal)===null||M===void 0||M.addEventListener("abort",()=>{var y;if(T!==void 0)clearTimeout(T);m((y=X===null||X===void 0?void 0:X.signal)===null||y===void 0?void 0:y.reason)});let W1=(j=X===null||X===void 0?void 0:X.timeout)!==null&&j!==void 0?j:n2;T=setTimeout(()=>m(new t1(N1.RequestTimeout,"Request timed out",{timeout:W1})),W1),this._transport.send(b).catch((y)=>{if(T!==void 0)clearTimeout(T);Y(y)})})}async notification($){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let W={...$,jsonrpc:"2.0"};await this._transport.send(W)}setRequestHandler($,W){let X=$.shape.method.value;this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(J,Y)=>Promise.resolve(W($.parse(J),Y)))}removeRequestHandler($){this._requestHandlers.delete($)}setNotificationHandler($,W){this._notificationHandlers.set($.shape.method.value,(X)=>Promise.resolve(W($.parse(X))))}removeNotificationHandler($){this._notificationHandlers.delete($)}}class b0 extends f0{constructor($,W){super(W);this._serverInfo=$,this._capabilities=W.capabilities,this.setRequestHandler(_0,(X)=>this._oninitialize(X)),this.setNotificationHandler(S0,()=>{var X;return(X=this.oninitialized)===null||X===void 0?void 0:X.call(this)})}assertCapabilityForMethod($){var W,X;switch($){case"sampling/createMessage":if(!((W=this._clientCapabilities)===null||W===void 0?void 0:W.sampling))throw Error(`Client does not support sampling (required for ${$})`);break;case"roots/list":if(!((X=this._clientCapabilities)===null||X===void 0?void 0:X.roots))throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw 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 Error(`Server does not support sampling (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"ping":case"initialize":break}}async _oninitialize($){let W=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:$4.includes(W)?W:A0,capabilities:this.getCapabilities(),serverInfo:this._serverInfo}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},G0)}async createMessage($,W){return this.request({method:"sampling/createMessage",params:$},k0,W)}async listRoots($,W){return this.request({method:"roots/list",params:$},C0,W)}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 V4 from"process";class P0{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 W=this._buffer.toString("utf8",0,$);return this._buffer=this._buffer.subarray($+1),d2(W)}clear(){this._buffer=void 0}}function d2($){return Q4.parse(JSON.parse($))}function q4($){return JSON.stringify($)+`
|
|
4
|
+
`}class I0{constructor($=V4.stdin,W=V4.stdout){this._stdin=$,this._stdout=W,this._readBuffer=new P0,this._started=!1,this._ondata=(X)=>{this._readBuffer.append(X),this.processReadBuffer()},this._onerror=(X)=>{var J;(J=this.onerror)===null||J===void 0||J.call(this,X)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){var $,W;while(!0)try{let X=this._readBuffer.readMessage();if(X===null)break;($=this.onmessage)===null||$===void 0||$.call(this,X)}catch(X){(W=this.onerror)===null||W===void 0||W.call(this,X)}}async close(){var $;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._readBuffer.clear(),($=this.onclose)===null||$===void 0||$.call(this)}send($){return new Promise((W)=>{let X=q4($);if(this._stdout.write(X))W();else this._stdout.once("drain",W)})}}var p2=await Promise.resolve().then(() => Z0(F0(),1)),M4=p2.version;async function O4($){let W=new b0({name:"typescape",version:M4},{capabilities:{tools:{}}});W.setRequestHandler(E0,async()=>{return{tools:$.getTools().map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}))}}),W.setRequestHandler(v0,async(J)=>{let{name:Y,arguments:w}=J.params,B=$.getHandler(Y);if(!B)return{content:[{type:"text",text:`Unknown tool: ${Y}`}],isError:!0};try{let M=await B(w||{});return{content:M.content.map((j)=>({type:j.type,text:j.text})),isError:M.isError}}catch(M){return{content:[{type:"text",text:`Error: ${M instanceof Error?M.message:String(M)}`}],isError:!0}}});let X=new I0;await W.connect(X),console.error(`Typescape MCP server v${M4} started`)}var T0=["file","doc","pr","custom"],i2=new Set(T0),o2=1e7,K4=/^[A-Za-z0-9+/]*={0,2}$/,j4="inline_assets_enabled",a2={type:"object",properties:{repo_id:{type:"string",description:"Repository identifier (short slug, e.g. 'typescape'; not a GitHub path like 'org/repo')"},git_sha:{type:"string",description:"Concrete 40-hex Git commit SHA (agent must resolve; no symbolic refs)"},file_path:{type:"string",description:"Path to the source document"},project_id:{type:"string",description:"Upload project ID for upload-backed sessions (requires upload_batch_id)"},upload_batch_id:{type:"string",description:"Upload batch ID for upload-backed sessions (requires project_id)"},title:{type:"string",description:"Session title (optional)"},participants:{type:"array",items:{type:"object",properties:{email:{type:"string"},name:{type:"string"},role:{type:"string",enum:["reviewer","approver","observer","owner"]},scopes:{type:"array",minItems:1,items:{type:"string",enum:["read","comment","approve","admin"]}}},required:["email","role"]},description:"Participants to invite (optional). Scopes are optional and default by role."},reviewer_emails:{type:"array",items:{type:"string"},description:"Legacy alias for participants. Each email is invited as a reviewer."},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"},expected_version:{type:"string",description:"Expected version for optimistic concurrency (If-Match header, optional)"},identity_restriction:{type:"string",enum:["open","participants_only","domain"],description:'Identity verification mode for OTP step-up. "open" (default): any email accepted. "participants_only": only invited participant emails. "domain": only emails from allowed_email_domains.'},allowed_email_domains:{type:"array",items:{type:"string"},description:'Allowed email domains when identity_restriction is "domain" (e.g., ["acme.com", "example.org"])'},operator_name:{type:"string",maxLength:200,description:"Name of the operator initiating the review (optional)"},focus_areas:{type:"array",items:{type:"string",maxLength:100},maxItems:10,description:"Areas the reviewer should focus on (optional)"},framing:{type:"string",maxLength:1000,description:"Context framing text shown to reviewers (optional)"},carry_forward_threads:{type:"boolean",description:"Whether to carry forward threads from the superseded session (optional)"},carry_forward_filter:{type:"string",enum:["all","blocking","needs_changes"],description:"Filter for which threads to carry forward (optional)"},content_body:{type:"string",maxLength:1048576,description:"Inline Markdown content (alternative to repo_id+git_sha). Creates an upload-backed session automatically."},inline_assets:{oneOf:[{type:"object",additionalProperties:{oneOf:[{type:"string"},{type:"object",properties:{base64:{type:"string"},content_base64:{type:"string"},content:{type:"string"},data:{type:"string"}},additionalProperties:!0}]}},{type:"array",items:{type:"object",properties:{path:{type:"string"},file_path:{type:"string"},filename:{type:"string"},file_name:{type:"string"},name:{type:"string"},base64:{type:"string"},content_base64:{type:"string"},content:{type:"string"},data:{type:"string"}},additionalProperties:!0}}],description:'Companion assets as either a map of relative path => base64 content, or a list of asset objects. Map example: { "images/fig.png": "iVBORw0KGgo..." }. Array example: [{ "path": "images/fig.png", "base64": "iVBORw0KGgo..." }]. Total decoded size must be <= 10MB.'},document_type:{type:"string",enum:["markdown","image_set","pdf"],description:'Document type (default: "markdown"). Use "image_set" for image-only review sessions or "pdf" for PDF review sessions.'},filenames:{type:"array",items:{type:"string"},minItems:1,maxItems:100,description:'Ordered list of image filenames (required when document_type is "image_set"). Each filename must be a relative path. Supported formats: PNG, JPEG, WebP, GIF, SVG.'}},required:["file_path"]},t2={type:"object",properties:{session_id:{type:"string",description:"ID of the session to supersede (the predecessor, e.g., sess_01HXYZ...)"},git_sha:{type:"string",description:"Concrete 40-hex Git commit SHA for the new revision (agent must resolve; no symbolic refs)"},content_body:{type:"string",description:"Inline Markdown content for upload-backed supersede sessions (alternative to git_sha/upload_batch_id)"},project_id:{type:"string",description:"Upload project ID for upload-backed supersede sessions (required with upload_batch_id)"},upload_batch_id:{type:"string",description:"Upload batch ID for upload-backed supersede sessions (alternative to git_sha/content_body)"},file_path:{type:"string",description:"Path to the source document (optional; defaults to predecessor's file_path)"},document_type:{type:"string",enum:["markdown","image_set","pdf"],description:"Document type for supersede (optional; defaults to predecessor document_type)"},filename:{type:"string",description:"PDF filename for document_type=pdf supersedes (optional; defaults to file_path)"},filenames:{type:"array",items:{type:"string"},minItems:1,description:"Ordered image filenames for document_type=image_set supersedes"},title:{type:"string",description:"Title for the new session (optional; defaults to predecessor's title)"},changes_summary:{type:"string",maxLength:5000,description:"Summary of changes for round-transition emails and the superseded banner (optional)"},resolutions:{type:"array",items:{type:"object",properties:{thread_id:{type:"string",description:"Thread ID from the predecessor session"},disposition:{type:"string",enum:["fixed","wont_fix","duplicate","by_design"],description:"How the thread was resolved"},evidence:{type:"string",maxLength:2000,description:"Optional evidence or explanation for the resolution"}},required:["thread_id","disposition"]},description:"Resolution manifest for threads from the predecessor session (optional)"},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"}},required:["session_id"]},r2={type:"object",properties:{session_id:{type:"string",description:"Session ID to export (e.g., sess_01HXYZ...)"},schema:{type:"string",default:"v1",description:"Export schema version (default: v1)"},view:{type:"string",description:"Export view variant (optional). Values: redacted, response_matrix.v1, delta_review.v1"},expected_version:{type:"string",description:"Expected version for optimistic concurrency (If-Match header, optional)"}},required:["session_id"]},s2={type:"object",properties:{repo_id:{type:"string",description:"Filter sessions by repository identifier (short slug, e.g. 'typescape'; optional)"},state:{type:"string",description:"Filter by session state: active, closed, archived (optional)"},file_paths:{type:"string",description:"Comma-separated list of file paths to filter by (optional)"},cursor:{type:"string",description:"Pagination cursor from previous response (optional)"},limit:{type:"number",description:"Maximum number of sessions to return (optional, default: 20)"},root_session_id:{type:"string",description:"Filter by supersede chain root session ID (optional, e.g., sess_...)"},supersedes_session_id:{type:"string",description:"Filter by immediate predecessor session ID (optional, e.g., sess_...)"},has_successor:{type:"boolean",description:"If true, return only sessions that have been superseded; if false, only chain heads (optional)"}},required:[]},e2={type:"object",properties:{session_id:{type:"string",description:"Session ID to retrieve (e.g., sess_01HXYZ...)"}},required:["session_id"]},$6={type:"object",properties:{session_id:{type:"string",description:"Session ID to render (e.g., sess_01HXYZ...)"},include_plaintext:{type:"boolean",description:"Include plaintext representation alongside HTML (optional, default: false)"}},required:["session_id"]},W6={type:"object",properties:{session_id:{type:"string",description:"Session ID to list threads for (e.g., sess_01HXYZ...)"},block_id:{type:"string",description:"Filter threads by block_id anchor (optional)"},status:{type:"string",description:"Filter threads by status: open, resolved, all (optional, default: all)"},cursor:{type:"string",description:"Pagination cursor from previous response (optional)"},limit:{type:"number",description:"Maximum number of threads to return (optional, default: 50)"}},required:["session_id"]},X6={type:"object",properties:{session_id:{type:"string",description:"Session ID to export response matrix for (e.g., sess_01HXYZ...)"}},required:["session_id"]};function v($,W){return{content:[{type:"text",text:JSON.stringify({...$,request_id:W},null,2)}]}}function V($){let W=$.status===0||$.status>=500||$.status===429;return{content:[{type:"text",text:JSON.stringify({error:{code:$.code,message:$.message,retryable:W,request_id:$.requestId,...$.details?{details:$.details}:{},...$.fixHint?{fix_hint:$.fixHint}:{}}},null,2)}],isError:!0}}function j0($){if(!$||typeof $!=="object"||Array.isArray($))return{};let W=$,X=W.data;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return W}function L4($){if(typeof $==="string"){let Y=$.trim();return Y.length>0?Y:null}if(!$||typeof $!=="object"||Array.isArray($))return null;let W=$,X=W.base64??W.content_base64??W.content??W.data??W.bytes;if(typeof X!=="string")return null;let J=X.trim();return J.length>0?J:null}function F4($,W){if(typeof $==="string"){let Y=$.trim();return Y.length>0?Y:null}if(!$||typeof $!=="object"||Array.isArray($))return W??null;let X=$,J=X.path??X.file_path??X.filename??X.file_name??X.name;if(typeof J==="string"&&J.trim().length>0)return J.trim();return W??null}function Q6($,W){if($===void 0||$===null)return{assets:{}};let X={};if(Array.isArray($)){for(let[Y,w]of $.entries()){let B=F4(w,W),M=L4(w);if(!B||!M)return{error:new q(422,"invalid_argument",`inline_assets[${Y}] requires both a path and base64 payload`,"local")};X[B]=M}return{assets:X}}if(typeof $!=="object")return{error:new q(422,"invalid_argument","inline_assets must be an object map or array","local")};let J=Object.entries($);for(let[Y,w]of J){let B=J.length===1&&/^[0-9]+$/.test(Y)&&typeof W==="string"&&W.trim().length>0?W.trim():Y,M=w&&typeof w==="object"&&!Array.isArray(w)?F4(w,B):B,j=L4(w);if(!M||!j)return{error:new q(422,"invalid_argument",`inline_assets entry '${Y}' requires base64 content`,"local")};X[M]=j}return{assets:X}}function Y6($){if(!$||$.length===0)return"Asset path is empty";if($.includes("\x00"))return"Asset path contains NUL byte";let W=$.replace(/\\/g,"/");if(W.startsWith("/"))return"Asset path must be relative (no leading /)";let X=W.split("/");for(let J of X)if(J==="..")return"Asset path must not contain '..' segments";return null}function U4($){let W=$.replace(/\s+/g,"");if(W.length===0)return new Uint8Array;if(W.length%4!==0||!K4.test(W))return null;let X=Buffer.from(W,"base64"),J=W.replace(/=+$/,""),Y=X.toString("base64").replace(/=+$/,"");if(J!==Y)return null;return Uint8Array.from(X)}function J6($){if($.code!=="feature_disabled")return!1;let W=$.details?.feature;if(typeof W==="string"&&W.toLowerCase()===j4)return!0;return`${$.message} ${$.fixHint??""}`.toLowerCase().includes(j4)}function H6($){let X=$.replace(/\\/g,"/").split("/"),J=X[X.length-1];return J&&J.length>0?J:"asset.bin"}async function G6($,W,X){let J=X&&X.trim().length>0?`MCP ${X.trim()}`:`MCP inline upload ${Date.now()}`,Y=await $.post("/projects",{body:{name:J}});if(!Y.body.id||Y.body.id.length===0)throw new q(502,"invalid_upstream_response","Upload project creation did not return project id",Y.requestId);let w=new FormData,B=Object.entries(W).sort(([j],[N])=>j.localeCompare(N));for(let[j,N]of B){let b=U4(N);if(b===null)throw new q(422,"invalid_argument",`Invalid base64 content for asset: ${j}`,"local");w.append(j,new Blob([b]),H6(j))}let M=await $.postFormData(`/projects/${encodeURIComponent(Y.body.id)}/upload`,w);if(!M.body.upload_batch_id||M.body.upload_batch_id.length===0)throw new q(502,"invalid_upstream_response","Upload batch response did not include upload_batch_id",M.requestId);return{projectId:Y.body.id,uploadBatchId:M.body.upload_batch_id}}function z6($){if($==="approver")return["read","comment","approve"];if($==="observer")return["read"];if($==="owner")return["read","comment","approve","admin"];return["read","comment"]}function w6($){return $.map((W)=>{let X=W.scopes&&W.scopes.length>0?[...new Set(W.scopes)]:z6(W.role);return{email:W.email,...W.name?{name:W.name}:{},role:W.role,scopes:X}})}function B6($,W){let X=[];if(Array.isArray($))X.push(...$);if(Array.isArray(W))for(let w of W){if(typeof w!=="string")continue;let B=w.trim();if(B.length===0)continue;X.push({email:B,role:"reviewer"})}let J=new Set,Y=[];for(let w of X){if(!w||typeof w.email!=="string")continue;let B=w.email.trim();if(B.length===0)continue;let M=B.toLowerCase();if(J.has(M))continue;J.add(M),Y.push({...w,email:B})}return Y}var q6={type:"object",properties:{source_type:{type:"string",enum:["git","upload"],description:"Source type for the review set"},title:{type:"string",description:"Review set title (optional)"},kind:{type:"string",enum:["review_set","release_bundle","packet"],description:"Kind of review set (optional, default: review_set)"},participants:{type:"array",items:{type:"object",properties:{email:{type:"string"},role:{type:"string",enum:["reviewer","approver"]},roles:{type:"array",items:{type:"string",enum:["reviewer","approver"]},minItems:1}},required:["email"]},description:"Participants to invite (optional). Supports role (single) or roles (array)."},sessions:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{session_id:{type:"string"},required:{type:"boolean"}},required:["session_id"],additionalProperties:!1}]},minItems:1,description:"Session IDs (or session entry objects) to include in this review set."},files:{type:"array",items:{type:"object",properties:{repo_id:{type:"string"},git_sha:{type:"string"},project_id:{type:"string"},upload_batch_id:{type:"string"},file_path:{type:"string"},required:{type:"boolean"}},required:["file_path"],additionalProperties:!1},minItems:1,description:"File entries for git or upload source types (must include file_path plus source identifiers)."},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"}},required:["source_type"]},V6={type:"object",properties:{review_set_id:{type:"string",description:"Review set ID to export"},schema:{type:"string",description:"Export schema version (optional, default: v1)"},view:{type:"string",description:"Export view variant (optional). Values: full, redacted, response_matrix.v1, etc."}},required:["review_set_id"]},M6={type:"object",properties:{source_type:{type:"string",enum:["git","upload"],description:"Source type for the review ref"},repo_id:{type:"string",description:"Repository identifier (required for git source_type; short slug, e.g. 'typescape')"},project_id:{type:"string",description:"Project identifier (required for upload source_type; omit for git)"},kind:{type:"string",enum:T0,description:"Review ref kind"},key:{type:"string",description:"Review ref key (e.g., file path, doc slug, PR number, custom name)"},head_session_id:{type:"string",description:"Session ID to use as the initial head (required, e.g., sess_01HXYZ...)"}},required:["source_type","kind","key","head_session_id"]},O6={type:"object",properties:{review_ref_id:{type:"string",description:"Review ref ID to resolve"}},required:["review_ref_id"]},j6={type:"object",properties:{review_ref_id:{type:"string",description:"Review ref ID to advance"},head_session_id:{type:"string",description:"New head session ID to advance to"},expected_head_session_id:{type:"string",description:"Expected current head for optimistic concurrency (optional)"}},required:["review_ref_id","head_session_id"]},L6={type:"object",properties:{session_id:{type:"string",description:"Session ID to request approval for"},approver_emails:{type:"array",items:{type:"string"},description:"Email addresses of approvers"},message:{type:"string",description:"Message to include with the approval request (optional)"},notify:{type:"object",properties:{email:{type:"boolean"},slack:{type:"boolean"}},description:"Notification channels (optional)"},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"}},required:["session_id","approver_emails"]},F6={type:"object",properties:{session_id:{type:"string",description:"Session ID to get status for"},simulate:{type:"boolean",description:"Run policy evaluation without side effects (optional)"},wait:{type:"number",description:"Long-poll timeout in seconds (optional)"}},required:["session_id"]},K6={type:"object",properties:{session_id:{type:"string",description:"Session ID to run checks against"}},required:["session_id"]},U6={type:"object",properties:{},additionalProperties:!1},D6={type:"object",properties:{},additionalProperties:!1},N6={type:"object",properties:{},additionalProperties:!1},R6={type:"object",properties:{session_id:{type:"string",description:"Session ID to create thread in (e.g., sess_01HXYZ...)"},body_md:{type:"string",description:"Thread body in Markdown"},block_id:{type:"string",description:"Block ID to anchor thread to (optional; omit for session-level)"},anchor_block_id:{type:"string",description:"Legacy alias for block_id. When provided, used as block anchor target."},anchor_type:{type:"string",enum:["session","block","range"],description:"Legacy alias for anchor.type. Prefer anchor={type:...} in new integrations."},anchor:{type:"object",properties:{type:{type:"string",enum:["session","block","range"],description:"Anchor type (default: session if no block_id, block if block_id provided)"},start_offset:{type:"number",description:"Start offset for range anchor"},end_offset:{type:"number",description:"End offset for range anchor"}},description:"Anchor details (optional)"},severity:{type:"string",enum:["suggestion","needs_changes","blocking"],description:"Thread severity"},tags:{type:"array",items:{type:"string"},description:"Tags for categorization (optional)"},suggestion:{type:"object",properties:{type:{type:"string",enum:["replace","insert","delete"]}},description:"Suggested change (optional)"},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"}},required:["session_id","body_md"]},A6={type:"object",properties:{session_id:{type:"string",description:"Session ID containing the thread"},thread_id:{type:"string",description:"Thread ID to post comment to"},body_md:{type:"string",description:"Comment body in Markdown"},idempotency_key:{type:"string",description:"Idempotency key for safe retries (optional)"}},required:["session_id","thread_id","body_md"]},_6={type:"object",properties:{session_id:{type:"string",description:"Session ID containing the thread"},thread_id:{type:"string",description:"Thread ID to resolve"},disposition:{type:"object",properties:{state:{type:"string",enum:["accepted_change","rejected_wont_fix","deferred","duplicate","needs_more_info","answered_no_change"],description:"Disposition state"},rationale_md:{type:"string",description:"Rationale in Markdown (optional)"}},required:["state"],description:"Disposition to record with resolution (optional)"},expected_version:{type:"string",description:"Expected version for optimistic concurrency (If-Match header, optional)"},if_match:{type:"string",description:"Alias for expected_version (If-Match header, optional)"}},required:["session_id","thread_id"]},S6={type:"object",properties:{session_id:{type:"string",description:"Session ID containing the thread"},thread_id:{type:"string",description:"Thread ID to reopen"},expected_version:{type:"string",description:"Expected version for optimistic concurrency (If-Match header, optional)"},if_match:{type:"string",description:"Alias for expected_version (If-Match header, optional)"}},required:["session_id","thread_id"]},E6={type:"object",properties:{session_id:{type:"string",description:"Session ID containing the thread"},thread_id:{type:"string",description:"Thread ID to record disposition for"},state:{type:"string",enum:["undecided","accepted_change","rejected_wont_fix","deferred","duplicate","needs_more_info","answered_no_change"],description:"Disposition state"},rationale_md:{type:"string",description:"Rationale in Markdown (optional)"}},required:["session_id","thread_id","state"]},v6={type:"object",properties:{session_id:{type:"string",description:"Session ID containing the thread"},thread_id:{type:"string",description:"Thread ID to attach evidence to"},evidence_type:{type:"string",enum:["commit","proposed_change","pr","attestation","external_ticket","note"],description:"Evidence type (required). Determines which additional fields are relevant."},commit_sha:{type:"string",description:"Git commit SHA (for evidence_type=commit)"},repo_url:{type:"string",description:"Repository URL (for evidence_type=commit)"},message:{type:"string",description:"Commit message (for evidence_type=commit)"},proposed_change_id:{type:"string",description:"Proposed change ID (for evidence_type=proposed_change)"},patch_sha256:{type:"string",description:"Patch SHA256 (for evidence_type=proposed_change)"},pr_url:{type:"string",description:"PR URL (for evidence_type=pr)"},pr_number:{type:"number",description:"PR number (for evidence_type=pr)"},attestation_id:{type:"string",description:"Attestation ID (for evidence_type=attestation)"},attestor:{type:"string",description:"Attestor identity (optional, for attestation type)"},ticket_url:{type:"string",description:"Ticket URL (for evidence_type=external_ticket)"},ticket_id:{type:"string",description:"Ticket ID (for evidence_type=external_ticket)"},system:{type:"string",description:"Ticket system (for evidence_type=external_ticket)"},note_md:{type:"string",description:"Note text (for evidence_type=note)"},body_md:{type:"string",description:"Markdown evidence body (alias for note_md/text; useful for attestation/external_ticket notes)"},dedupe_key:{type:"string",description:"Optional idempotency/deduplication key for evidence attach"}},required:["session_id","thread_id","evidence_type"]},k6={type:"object",properties:{name:{type:"string",description:"Collection name (1-100 characters, unique per tenant among non-archived collections)"},description:{type:"string",description:"Optional Markdown description (max 2000 characters)"},color:{type:"string",description:"Optional hex color (e.g., #12A594)"}},required:["name"]},C6={type:"object",properties:{collection_id:{type:"string",description:"Collection ID (e.g., col_01HXYZ...)"},session_id:{type:"string",description:"Session ID to add (e.g., sess_01HXYZ...)"}},required:["collection_id","session_id"]};function D4($,W){let X={name:"typescape_create_session",description:"Create a new Typescape review session for Markdown, image-set, or PDF content. Supports three source modes: (1) git-backed with repo_id+git_sha, (2) inline with content_body and optional inline_assets (base64), or (3) upload-backed with project_id+upload_batch_id. Returns the session ID and any invitations sent.",inputSchema:a2};$.register(X,async(O)=>{let Q=O,H=Q6(Q.inline_assets,Q.file_path);if("error"in H)return V(H.error);let z=H.assets;if(!Q.file_path)return V(new q(400,"missing_param","Missing required parameter: file_path","local"));let L=typeof Q.repo_id==="string"&&Q.repo_id.length>0,K=typeof Q.git_sha==="string"&&Q.git_sha.length>0,_=typeof Q.project_id==="string"&&Q.project_id.length>0,f=typeof Q.upload_batch_id==="string"&&Q.upload_batch_id.length>0,I=L&&K,g=_&&f,i=!!Q.content_body,n=Object.keys(z).length>0;if(L&&!K||!L&&K)return V(new q(422,"invalid_argument","Both repo_id and git_sha are required for git-backed sessions","local"));if(_&&!f||!_&&f)return V(new q(422,"invalid_argument","Both project_id and upload_batch_id are required for upload-backed sessions","local"));if(Q.document_type!==void 0&&Q.document_type!=="markdown"&&Q.document_type!=="image_set"&&Q.document_type!=="pdf")return V(new q(422,"invalid_argument",`Unsupported document_type: ${Q.document_type}. Supported values: "markdown", "image_set", "pdf".`,"local"));let R1=Q.document_type==="image_set",m1=Q.document_type==="pdf";if(R1){if(!n&&!g)return V(new q(400,"image_set_empty","image_set sessions require inline_assets or upload-batch input (project_id + upload_batch_id)","local"));if(g&&(!Q.filenames||Q.filenames.length===0))return V(new q(400,"missing_param",'document_type "image_set" with upload-batch mode requires filenames.',"local"));let h=new Set([".png",".jpg",".jpeg",".webp",".gif",".svg"]);if(n){for(let H1 of Object.keys(z)){let G1=H1.slice(H1.lastIndexOf(".")).toLowerCase();if(!h.has(G1))return V(new q(422,"unsupported_media_type",`Unsupported image format for image_set: ${H1}. Supported extensions: ${[...h].join(", ")}`,"local"))}if(Object.keys(z).length>100)return V(new q(422,"image_set_limit_exceeded",`Image set has ${Object.keys(z).length} images, exceeding the maximum of 100`,"local"))}}if(m1){if(I)return V(new q(422,"invalid_argument",'document_type "pdf" is only supported with upload-backed sources (inline_assets or project_id+upload_batch_id).',"local"));if(i)return V(new q(422,"invalid_argument",'document_type "pdf" does not support content_body; provide inline_assets with one .pdf file.',"local"));if(!n&&!g)return V(new q(400,"missing_param",'document_type "pdf" requires either inline_assets with one .pdf file, or upload-batch input (project_id + upload_batch_id).',"local"));if(n&&g)return V(new q(422,"invalid_argument",'document_type "pdf" cannot mix inline_assets and upload-batch inputs.',"local"));if(n&&Object.keys(z).length!==1)return V(new q(422,"invalid_argument",'document_type "pdf" requires exactly one inline asset.',"local"));if(n){let[h]=Object.keys(z);if(!h)return V(new q(400,"missing_param",'document_type "pdf" requires inline_assets with exactly one .pdf file.',"local"));if(h.slice(h.lastIndexOf(".")).toLowerCase()!==".pdf")return V(new q(422,"unsupported_media_type",`Unsupported PDF format: ${h}. Supported extension: .pdf`,"local"));if(Q.file_path!==h)return V(new q(422,"invalid_argument",`For document_type "pdf", file_path must match inline_assets key: ${h}`,"local"))}}let g0=[I,i,g].filter(Boolean).length;if(!R1&&!m1&&g0===0)return V(new q(400,"missing_param","Provide one source mode: (repo_id + git_sha), (content_body), or (project_id + upload_batch_id)","local"));if(g0>1)return V(new q(422,"ambiguous_session_input","Cannot mix source modes: choose exactly one of git-backed, inline content_body, or upload-backed.","local"));if(!R1&&Q.filenames&&Q.filenames.length>0)return V(new q(422,"invalid_argument","filenames is only valid when document_type is image_set.","local"));if(Q.identity_restriction==="domain"&&(!Q.allowed_email_domains||Q.allowed_email_domains.length===0))return V(new q(422,"invalid_argument",'allowed_email_domains is required when identity_restriction is "domain"',"local"));if(Object.keys(z).length>0){if(!i&&!R1&&!m1)return V(new q(422,"invalid_argument","inline_assets requires content_body (inline mode)","local"));let h=0;for(let[H1,G1]of Object.entries(z)){let s1=Y6(H1);if(s1)return V(new q(422,"invalid_argument",`${s1}: ${H1}`,"local"));let j1=U4(G1);if(j1===null)return V(new q(422,"invalid_argument",`Invalid base64 content for asset: ${H1}`,"local"));h+=j1.byteLength}if(h>o2)return V(new q(413,"inline_payload_too_large",`Total decoded inline assets (${h} bytes) exceed 10MB limit. Use the Typescape CLI with upload batch for larger payloads.`,"local"))}let l={file_path:Q.file_path};if(I)l.repo_id=Q.repo_id,l.git_sha=Q.git_sha;if(g)l.project_id=Q.project_id,l.upload_batch_id=Q.upload_batch_id;if(i)l.content_body=Q.content_body;if(Object.keys(z).length>0)l.inline_assets=z;let x0=B6(Q.participants,Q.reviewer_emails);if(x0.length>0)l.participants=w6(x0);if(Q.title!==void 0)l.title=Q.title;if(Q.identity_restriction!==void 0)l.identity_restriction=Q.identity_restriction;if(Q.allowed_email_domains!==void 0&&Q.allowed_email_domains.length>0)l.allowed_email_domains=Q.allowed_email_domains;if(Q.operator_name!==void 0)l.operator_name=Q.operator_name;if(Q.focus_areas!==void 0&&Q.focus_areas.length>0)l.focus_areas=Q.focus_areas;if(Q.framing!==void 0)l.framing=Q.framing;if(Q.carry_forward_threads!==void 0)l.carry_forward_threads=Q.carry_forward_threads;if(Q.carry_forward_filter!==void 0)l.carry_forward_filter=Q.carry_forward_filter;if(Q.document_type!==void 0)l.document_type=Q.document_type;if(m1)l.filename=Q.file_path;if(R1){let h=Q.filenames&&Q.filenames.length>0?Q.filenames:Object.keys(z).sort();l.filenames=h}let r1={};if(Q.idempotency_key)r1["Idempotency-Key"]=Q.idempotency_key;if(Q.expected_version)r1["If-Match"]=Q.expected_version;try{let h=await W.post("/sessions",{body:l,headers:r1});return v({session:h.body.session,invitations:h.body.invitations??[]},h.requestId)}catch(h){if(h instanceof q){if(n&&!g&&!I&&!i&&(R1||m1)&&J6(h))try{let{projectId:G1,uploadBatchId:s1}=await G6(W,z,Q.title),j1={...l};delete j1.inline_assets,j1.project_id=G1,j1.upload_batch_id=s1;let L0=await W.post("/sessions",{body:j1,headers:r1});return v({session:L0.body.session,invitations:L0.body.invitations??[]},L0.requestId)}catch(G1){if(G1 instanceof q)return V(G1);throw G1}return V(h)}throw h}});let J={name:"typescape_supersede_session",description:"Create a new Typescape review session pinned to a newer revision, superseding an existing session. The predecessor becomes read-only and unresolved threads are carried forward to the new session. Supports git supersede (git_sha) and upload supersede (content_body or upload_batch_id+project_id).",inputSchema:t2};$.register(J,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));let H=typeof Q.git_sha==="string"&&Q.git_sha.length>0,z=typeof Q.content_body==="string"&&Q.content_body.length>0,L=typeof Q.upload_batch_id==="string"&&Q.upload_batch_id.length>0,K=typeof Q.project_id==="string"&&Q.project_id.length>0;if(K&&!L||!K&&L)return V(new q(422,"invalid_argument","Both project_id and upload_batch_id are required for upload-backed supersede","local"));let _=[H,z,L].filter(Boolean).length;if(_===0)return V(new q(400,"missing_param","One of git_sha, content_body, or upload_batch_id is required","local"));if(_>1)return V(new q(422,"invalid_argument","git_sha, content_body, and upload_batch_id are mutually exclusive","local"));if(H&&!/^[a-f0-9]{40}$/i.test(Q.git_sha))return V(new q(400,"invalid_param",`Invalid git_sha format: must be a 40-character hex string, got "${Q.git_sha}"`,"local"));let f={};if(H)f.git_sha=Q.git_sha.toLowerCase();if(z)f.content_body=Q.content_body;if(L)f.project_id=Q.project_id,f.upload_batch_id=Q.upload_batch_id;if(Q.file_path!==void 0)f.file_path=Q.file_path;if(Q.document_type!==void 0)f.document_type=Q.document_type;if(Q.filename!==void 0)f.filename=Q.filename;else if(Q.document_type==="pdf"&&Q.file_path!==void 0)f.filename=Q.file_path;if(Q.filenames!==void 0&&Q.filenames.length>0)f.filenames=Q.filenames;if(Q.title!==void 0)f.title=Q.title;if(Q.changes_summary!==void 0)f.changes_summary=Q.changes_summary;if(Q.resolutions!==void 0&&Q.resolutions.length>0)f.resolutions=Q.resolutions;let I={};if(Q.idempotency_key)I["Idempotency-Key"]=Q.idempotency_key;try{let g=await W.post(`/sessions/${encodeURIComponent(Q.session_id)}/supersede`,{body:f,headers:I});return v(g.body,g.requestId)}catch(g){if(g instanceof q)return V(g);throw g}});let Y={name:"typescape_export_feedback",description:"Export all feedback from a Typescape review session as structured JSON. Returns the full export document including threads, comments, and anchors.",inputSchema:r2};$.register(Y,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));let H={schema:Q.schema||"v1"};if(Q.view)H.view=Q.view;let z={};if(Q.expected_version)z["If-Match"]=Q.expected_version;try{let L=await W.get(`/sessions/${Q.session_id}/export`,{query:H,headers:z});return v(L.body,L.requestId)}catch(L){if(L instanceof q)return V(L);throw L}});let w={name:"typescape_list_sessions",description:"List Typescape review sessions with optional filters. Returns paginated session summaries. Use cursor from previous response for pagination.",inputSchema:s2};$.register(w,async(O)=>{let Q=O,H={};if(Q.repo_id)H.repo_id=Q.repo_id;if(Q.state)H.state=Q.state;if(Q.file_paths)H.file_paths=Q.file_paths;if(Q.cursor)H.cursor=Q.cursor;if(Q.limit!==void 0)H.limit=String(Q.limit);if(Q.root_session_id)H.root_session_id=Q.root_session_id;if(Q.supersedes_session_id)H.supersedes_session_id=Q.supersedes_session_id;if(Q.has_successor!==void 0)H.has_successor=Q.has_successor?"true":"false";try{let z=await W.get("/sessions",{query:H});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let B={name:"typescape_get_session",description:"Get details of a specific Typescape review session. Returns full session metadata including participants, stats, and provenance.",inputSchema:e2};$.register(B,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));try{let H=await W.get(`/sessions/${Q.session_id}`);return v(H.body,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});let M={name:"typescape_get_render",description:"Get the rendered content of a review session. Returns immutable block-level HTML structure with block_ids for anchoring.",inputSchema:$6},j=new Map;function N(O){let Q=O.indexOf("#");if(Q===-1)throw new q(500,"invalid_review_url","Review link URL is missing fragment token","local");return O.slice(Q+1)}async function b(O){let Q=j.get(O);if(Q&&Q.expiresAtMs>Date.now())return Q.token;let H=await W.get(`/sessions/${O}/participants`,{query:{role:"reviewer"}}),z=H.body.items?.[0]?.participant_id??null;if(!z)z=(await W.get(`/sessions/${O}/participants`,{query:{limit:"1"}})).body.items?.[0]?.participant_id??null;if(!z)throw new q(422,"no_participants","No participants available to mint a render token",H.requestId);let L=await W.post(`/sessions/${O}/links`,{body:{participant_id:z,scope:"read",single_use:!0,url_token_ttl_minutes:60}}),K=L.body.url;if(!K||typeof K!=="string")throw new q(500,"invalid_link_response","Failed to mint review link for render",L.requestId);let _=await W.post("/auth/exchange",{body:{url_token:N(K)}}),f=_.body.session_access_token,I=_.body.expires_in_seconds;if(!f||typeof f!=="string")throw new q(500,"token_exchange_failed","Failed to exchange review link for session access token",_.requestId);let g=typeof I==="number"&&Number.isFinite(I)?Math.max(0,Math.trunc(I)-30)*1000:300000;return j.set(O,{token:f,expiresAtMs:Date.now()+g}),f}$.register(M,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));let H={};if(Q.include_plaintext)H.include_plaintext="true";try{let z=await b(Q.session_id),L=await W.get(`/sessions/${Q.session_id}/render`,{query:H,headers:{Authorization:`Bearer ${z}`}});return v(L.body,L.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let T={name:"typescape_get_threads",description:"List threads (comments) for a review session. Optionally filter by block_id anchor or thread status. Returns paginated thread list with comments.",inputSchema:W6};$.register(T,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));let H={};if(Q.block_id)H.block_id=Q.block_id;if(Q.status)H.status=Q.status;if(Q.cursor)H.cursor=Q.cursor;if(Q.limit!==void 0)H.limit=String(Q.limit);try{let z=await W.get(`/sessions/${Q.session_id}/threads`,{query:H});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let m={name:"typescape_export_response_matrix",description:"Export the response matrix for a review session. Returns per-thread disposition and evidence summary.",inputSchema:X6};$.register(m,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));try{let H=await W.get(`/sessions/${Q.session_id}/export`,{query:{schema:"v1",view:"response_matrix.v1"}});return v(H.body,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}}),$.register({name:"typescape_create_thread",description:"Create a new thread (comment) on a review session. Optionally anchor to a specific block_id. Agent-created threads are tagged source='automation'.",inputSchema:R6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.body_md)return V(new q(400,"missing_param","Missing required parameter: body_md","local"));let H={body_md:Q.body_md,source:"automation"},z=typeof Q.block_id==="string"?Q.block_id.trim():void 0,L=typeof Q.anchor_block_id==="string"?Q.anchor_block_id.trim():void 0,K=z||L;if(K)H.block_id=K;if(Q.anchor!==void 0)H.anchor=Q.anchor;else if(Q.anchor_type)H.anchor={type:Q.anchor_type};else if(K)H.anchor={type:"block"};if(Q.severity!==void 0)H.severity=Q.severity;if(Q.tags!==void 0)H.tags=Q.tags;if(Q.suggestion!==void 0)H.suggestion=Q.suggestion;let _={};if(Q.idempotency_key)_["Idempotency-Key"]=Q.idempotency_key;try{let f=await W.post(`/sessions/${Q.session_id}/threads`,{body:H,headers:_});return v(f.body,f.requestId)}catch(f){if(f instanceof q)return V(f);throw f}}),$.register({name:"typescape_post_comment",description:"Post a comment (reply) to an existing thread. Returns the created comment with its ID.",inputSchema:A6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.thread_id)return V(new q(400,"missing_param","Missing required parameter: thread_id","local"));if(!Q.body_md)return V(new q(400,"missing_param","Missing required parameter: body_md","local"));let H={body_md:Q.body_md,source:"automation"},z={};if(Q.idempotency_key)z["Idempotency-Key"]=Q.idempotency_key;try{let L=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/comments`,{body:H,headers:z});return v(L.body,L.requestId)}catch(L){if(L instanceof q)return V(L);throw L}}),$.register({name:"typescape_resolve_thread",description:"Resolve (close) a thread. Optionally include a disposition. Use expected_version or if_match for optimistic concurrency.",inputSchema:_6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.thread_id)return V(new q(400,"missing_param","Missing required parameter: thread_id","local"));let H={};if(Q.disposition!==void 0)H.disposition=Q.disposition;let z={},L=Q.expected_version??Q.if_match;if(L)z["If-Match"]=L;try{let K=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/resolve`,{body:H,headers:z});return v(K.body,K.requestId)}catch(K){if(K instanceof q)return V(K);throw K}}),$.register({name:"typescape_reopen_thread",description:"Reopen a previously resolved thread. Use expected_version or if_match for optimistic concurrency.",inputSchema:S6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.thread_id)return V(new q(400,"missing_param","Missing required parameter: thread_id","local"));let H={},z={},L=Q.expected_version??Q.if_match;if(L)z["If-Match"]=L;try{let K=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/reopen`,{body:H,headers:z});return v(K.body,K.requestId)}catch(K){if(K instanceof q)return V(K);throw K}}),$.register({name:"typescape_record_disposition",description:"Record a disposition (decision) on a thread. Dispositions track how feedback was addressed. Note: recording a resolving disposition may automatically resolve the thread.",inputSchema:E6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.thread_id)return V(new q(400,"missing_param","Missing required parameter: thread_id","local"));if(!Q.state)return V(new q(400,"missing_param","Missing required parameter: state","local"));let H={state:Q.state};if(Q.rationale_md!==void 0)H.rationale_md=Q.rationale_md;try{let z=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/dispositions`,{body:H});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}}),$.register({name:"typescape_attach_evidence",description:"Attach evidence to a thread. Evidence proves that feedback was addressed (e.g., commit SHA, proposed change, PR URL, or attestation).",inputSchema:v6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.thread_id)return V(new q(400,"missing_param","Missing required parameter: thread_id","local"));let H,z;if(Q.evidence_type){H=Q.evidence_type.trim(),z={};let K=["commit_sha","repo_url","message","proposed_change_id","patch_sha256","pr_url","pr_number","attestation_id","attestor","ticket_url","ticket_id","system","note_md","body_md"];for(let _ of K)if(Q[_]!==void 0)z[_]=Q[_];if(Q.body_md!==void 0)z.text=Q.body_md;else if(Q.note_md!==void 0)z.text=Q.note_md}else if(Q.evidence)H=typeof Q.evidence.type==="string"?Q.evidence.type.trim():"",z={...Q.evidence},delete z.type;else return V(new q(400,"missing_param","Missing required parameter: evidence_type","local"));if(!H)return V(new q(422,"invalid_argument","evidence_type is required","local"));let L={evidence_type:H,evidence_json:z};if(Q.dedupe_key)L.dedupe_key=Q.dedupe_key;try{let K=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/evidence`,{body:L});return v(K.body,K.requestId)}catch(K){if(K instanceof q)return V(K);throw K}});let W1=null,y=300000;async function A(){let O=Date.now();if(W1&&O-W1.fetchedAt<y)return W1.features;try{return W1={features:(await W.get("/me/capabilities")).body.features??{},fetchedAt:O},W1.features}catch(Q){if(Q instanceof q)throw Q;throw Q}}function x(O){return{content:[{type:"text",text:JSON.stringify({error:{code:"feature_disabled",feature:O,message:`Feature '${O}' is not enabled on this server`,request_id:"local"}},null,2)}],isError:!0}}$.register({name:"typescape_create_review_set",description:"Create a new review set (multi-file review pack). Requires features.review_sets to be enabled.",inputSchema:q6},async(O)=>{let Q=O;try{if(!(await A()).review_sets)return x("review_sets")}catch(_){if(_ instanceof q)return V(_);throw _}if(!Q.source_type)return V(new q(400,"missing_param","Missing required parameter: source_type","local"));if(Q.source_type!=="git"&&Q.source_type!=="upload")return V(new q(422,"invalid_argument","source_type must be one of: git, upload","local"));let H=Array.isArray(Q.sessions)&&Q.sessions.length>0,z=Array.isArray(Q.files)&&Q.files.length>0;if(!H&&!z)return V(new q(400,"missing_param","At least one of sessions[] or files[] is required","local"));let L={source_type:Q.source_type};if(Q.title!==void 0)L.title=Q.title;if(Q.kind!==void 0)L.kind=Q.kind;if(H)L.sessions=Q.sessions;if(z)L.files=Q.files;if(Q.participants!==void 0)L.participants=Q.participants.map((_)=>{if(Array.isArray(_.roles)&&_.roles.length>0)return{email:_.email,roles:_.roles};if(_.role)return{email:_.email,roles:[_.role]};return _});let K={};if(Q.idempotency_key)K["Idempotency-Key"]=Q.idempotency_key;try{let _=await W.post("/review-sets",{body:L,headers:K});return v(_.body,_.requestId)}catch(_){if(_ instanceof q)return V(_);throw _}}),$.register({name:"typescape_export_review_set",description:"Export feedback from a review set. Requires features.review_sets to be enabled.",inputSchema:V6},async(O)=>{let Q=O;try{if(!(await A()).review_sets)return x("review_sets")}catch(z){if(z instanceof q)return V(z);throw z}if(!Q.review_set_id)return V(new q(400,"missing_param","Missing required parameter: review_set_id","local"));let H={schema:Q.schema||"v1"};if(Q.view)H.view=Q.view;try{let z=await W.get(`/review-sets/${encodeURIComponent(Q.review_set_id)}/export`,{query:H});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}}),$.register({name:"typescape_create_review_ref",description:"Create a stable review reference that tracks HEAD session for doc/file/PR/custom keys. Always available (core primitive).",inputSchema:M6},async(O)=>{let Q=O;if(!Q.source_type)return V(new q(400,"missing_param","Missing required parameter: source_type","local"));if(!Q.kind)return V(new q(400,"missing_param","Missing required parameter: kind","local"));if(!Q.key)return V(new q(400,"missing_param","Missing required parameter: key","local"));if(!Q.head_session_id)return V(new q(400,"missing_param","Missing required parameter: head_session_id","local"));let H=Q.kind.trim().toLowerCase();if(!i2.has(H))return V(new q(400,"invalid_param",`Invalid parameter: kind must be one of ${T0.join(", ")}`,"local"));let z={source_type:Q.source_type,kind:H,key:Q.key,head_session_id:Q.head_session_id};if(Q.repo_id!==void 0)z.repo_id=Q.repo_id;if(Q.project_id!==void 0)z.project_id=Q.project_id;try{let L=await W.post("/review-refs",{body:z});return v(L.body,L.requestId)}catch(L){if(L instanceof q)return V(L);throw L}}),$.register({name:"typescape_resolve_review_ref",description:"Resolve a review ref to its current head session. Returns the head session ID and pinned content details.",inputSchema:O6},async(O)=>{let Q=O;if(!Q.review_ref_id)return V(new q(400,"missing_param","Missing required parameter: review_ref_id","local"));try{let H=await W.get(`/review-refs/${encodeURIComponent(Q.review_ref_id)}/resolve`);return v(H.body,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}}),$.register({name:"typescape_advance_review_ref",description:"Advance a review ref to a new head session. Use expected_head_session_id for optimistic concurrency.",inputSchema:j6},async(O)=>{let Q=O;if(!Q.review_ref_id)return V(new q(400,"missing_param","Missing required parameter: review_ref_id","local"));if(!Q.head_session_id)return V(new q(400,"missing_param","Missing required parameter: head_session_id","local"));let H={head_session_id:Q.head_session_id};if(Q.expected_head_session_id!==void 0)H.expected_head_session_id=Q.expected_head_session_id;try{let z=await W.post(`/review-refs/${encodeURIComponent(Q.review_ref_id)}/advance`,{body:H});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}}),$.register({name:"typescape_request_approval",description:"Request approval for a review session from specified approvers. Sends notifications via configured channels.",inputSchema:L6},async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.approver_emails||Q.approver_emails.length===0)return V(new q(400,"missing_param","Missing required parameter: approver_emails","local"));let H={approver_emails:Q.approver_emails};if(Q.message!==void 0)H.message=Q.message;if(Q.notify!==void 0)H.notify=Q.notify;let z={};if(Q.idempotency_key)z["Idempotency-Key"]=Q.idempotency_key;try{let L=await W.post(`/sessions/${encodeURIComponent(Q.session_id)}/request-approval`,{body:H,headers:z});return v(L.body,L.requestId)}catch(L){if(L instanceof q)return V(L);throw L}}),$.register({name:"typescape_get_status",description:"Get the policy verdict for a session. Returns pass/fail/needs_review with reasons. Requires features.policy to be enabled.",inputSchema:F6},async(O)=>{let Q=O;try{if(!(await A()).policy)return x("policy")}catch(z){if(z instanceof q)return V(z);throw z}if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));let H={};if(Q.simulate)H.simulate="true";if(Q.wait!==void 0)H.wait=String(Q.wait);try{let z=await W.get(`/sessions/${encodeURIComponent(Q.session_id)}/status`,{query:H});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}}),$.register({name:"typescape_run_checks",description:"Trigger quality checks (DocLint-as-Threads) for a session. Returns the check run ID. Requires features.checks to be enabled.",inputSchema:K6},async(O)=>{let Q=O;try{if(!(await A()).checks)return x("checks")}catch(H){if(H instanceof q)return V(H);throw H}if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));try{let H=await W.post(`/sessions/${encodeURIComponent(Q.session_id)}/run-checks`,{body:{}});return v(H.body,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}}),$.register({name:"typescape_account_usage",description:"Get account usage and quota information (sessions used/limit, remaining, and billing period).",inputSchema:U6},async()=>{try{let O=await W.get("/account/usage");return v(O.body,O.requestId)}catch(O){if(O instanceof q)return V(O);throw O}}),$.register({name:"typescape_account_plan",description:"Get account plan details (plan name/id, status, and limits metadata).",inputSchema:D6},async()=>{try{let O=await W.get("/account/plan");return v(O.body,O.requestId)}catch(O){if(O instanceof q)return V(O);throw O}}),$.register({name:"typescape_get_capabilities",description:"Get authenticated capabilities and effective feature flags. Returns the same payload shape as GET /v1/me/capabilities.",inputSchema:N6},async()=>{try{let O=await W.get("/me/capabilities");return v(O.body,O.requestId)}catch(O){if(O instanceof q)return V(O);throw O}});let J1={type:"object",properties:{repo_id:{type:"string",description:"Repository identifier"},git_sha:{type:"string",description:"Git commit SHA for the snapshot"}},required:["repo_id","git_sha"]};$.register({name:"typescape_get_snapshot",description:"Get corpus snapshot metadata for a Git repo at a specific commit. Returns snapshot status, config hash, and source type. Requires features.corpus_snapshots to be enabled.",inputSchema:J1},async(O)=>{let Q=O;try{if(!(await A()).corpus_snapshots)return x("corpus_snapshots")}catch(H){if(H instanceof q)return V(H);throw H}if(!Q.repo_id)return V(new q(400,"missing_param","Missing required parameter: repo_id","local"));if(!Q.git_sha)return V(new q(400,"missing_param","Missing required parameter: git_sha","local"));try{let H=await W.get(`/repos/${encodeURIComponent(Q.repo_id)}/snapshots/${encodeURIComponent(Q.git_sha)}`);return v(H.body,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});let Z1={type:"object",properties:{repo_id:{type:"string",description:"Repository identifier"},git_sha:{type:"string",description:"Git commit SHA for the snapshot"},path:{type:"string",description:"Target file path to query backlinks for"},anchor:{type:"string",description:"Optional anchor within the file to narrow backlinks"}},required:["repo_id","git_sha","path"]};$.register({name:"typescape_list_backlinks",description:"List inbound backlinks for a target file (and optional anchor) within a corpus snapshot. Returns deterministic, authoritative data. Requires features.corpus_snapshots to be enabled.",inputSchema:Z1},async(O)=>{let Q=O;try{if(!(await A()).corpus_snapshots)return x("corpus_snapshots")}catch(H){if(H instanceof q)return V(H);throw H}if(!Q.repo_id)return V(new q(400,"missing_param","Missing required parameter: repo_id","local"));if(!Q.git_sha)return V(new q(400,"missing_param","Missing required parameter: git_sha","local"));if(!Q.path)return V(new q(400,"missing_param","Missing required parameter: path","local"));try{let H=new URLSearchParams({path:Q.path});if(Q.anchor)H.set("anchor",Q.anchor);let z=await W.get(`/repos/${encodeURIComponent(Q.repo_id)}/snapshots/${encodeURIComponent(Q.git_sha)}/backlinks?${H}`);return v(z.body,z.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});let R4={type:"object",properties:{session_id:{type:"string",description:"Session identifier to compute impact radius for"}},required:["session_id"]};$.register({name:"typescape_get_impact",description:"Compute the impact radius for a session: which other files are affected by changes to the session's target file (via backlinks). Returns deterministic, authoritative data. Requires features.corpus_snapshots to be enabled.",inputSchema:R4},async(O)=>{let Q=O;try{if(!(await A()).corpus_snapshots)return x("corpus_snapshots")}catch(H){if(H instanceof q)return V(H);throw H}if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));try{let H=await W.get(`/sessions/${encodeURIComponent(Q.session_id)}/impact`);return v(H.body,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});let A4={type:"object",properties:{repo_id:{type:"string",description:"Repository identifier"},session_id:{type:"string",description:"Session identifier. Use for upload-backed sessions or when repo_id is not known."},policy_snapshot_id:{type:"string",description:"Optional policy snapshot ID used to compile steering context"},file_path:{type:"string",description:"Optional file path to scope steering rules"},path:{type:"string",description:"Alias for file_path. If both are provided, file_path takes precedence."},format:{type:"string",enum:["structured","prompt_fragment"],description:'Output format: "structured" returns governed JSON rules (authoritative), "prompt_fragment" returns pre-computed Markdown text within token budget (may include non-authoritative assistive fields). Default: prompt_fragment.'},token_budget:{type:"number",description:"Maximum token count for prompt_fragment format (100-10000, default 2000)",minimum:100,maximum:1e4}}};$.register({name:"typescape_get_steering",description:'Get active steering rules for a repository. format="structured" returns governed, human-approved rules (authoritative). format="prompt_fragment" returns pre-computed text within configured token budget. Requires steering to be enabled.',inputSchema:A4},async(O)=>{let Q=O;try{if(!(await A()).steering)return x("steering")}catch(I){if(I instanceof q)return V(I);throw I}let H=typeof Q.repo_id==="string"&&Q.repo_id.length>0,z=typeof Q.session_id==="string"&&Q.session_id.length>0;if(!H&&!z)return V(new q(400,"missing_param","Missing required parameter: repo_id or session_id","local"));let L=Q.format??"prompt_fragment",K=Q.file_path??Q.path,_=(I)=>{let g=new URLSearchParams({format:I});if(K)g.set("file_path",K);if(Q.policy_snapshot_id)g.set("policy_snapshot_id",Q.policy_snapshot_id);if(Q.token_budget!==void 0&&Q.token_budget!==null)g.set("token_budget",String(Q.token_budget));return g},f=(I)=>H?`/repos/${encodeURIComponent(Q.repo_id??"")}/steering-pack?${I}`:`/sessions/${encodeURIComponent(Q.session_id??"")}/steering-pack?${I}`;try{let I=_(L==="structured"?"structured.v1":"prompt_fragment.v1"),g=f(I),i=await W.get(g),n={...j0(i.body)};if(L==="prompt_fragment"&&n.prompt_fragment)n.non_authoritative=!0;return v(n,i.requestId)}catch(I){if(I instanceof q&&L==="structured"&&I.status===422&&I.code==="invalid_argument")try{let g=f(_("prompt_fragment.v1")),i=await W.get(g),n={...j0(i.body),steering_version:"v1",rules:[],non_authoritative:!0,format_fallback:"prompt_fragment"};return v(n,i.requestId)}catch(g){if(g instanceof q)return V(g);throw g}if(I instanceof q)return V(I);throw I}});let _4={type:"object",properties:{source_type:{type:"string",enum:["thread","doc_review","slack","email","interview","automation","admin"],description:"How this guideline was discovered"},source_ref:{type:"string",description:"Stable source reference (URL, message ID, document path). Required for non-thread source types."},source_excerpt:{type:"string",description:"Optional short excerpt from source context"},proposed_type:{type:"string",enum:["claim","knowledge","voice","constraint","steering_rule"],description:"Proposed guideline type (default: constraint for non-thread GCIs)"},proposed_content:{type:"object",additionalProperties:!0,description:"Structured proposed content payload"},related_item_ids:{type:"array",items:{type:"string"},description:"Related GCI IDs"},title:{type:"string",description:"Backward-compatible alias used to populate proposed_content.title"},content:{type:"string",description:"Backward-compatible alias used to populate proposed_content.content"},rationale:{type:"string",description:"Why this should become a guideline"},target_document:{type:"string",description:"Target canonical document path"},priority:{type:"string",enum:["low","medium","high","critical"],description:"Priority level (default: medium)"},thread_id:{type:"string",description:"Source thread ID (required when source_type is 'thread')"},tags:{type:"array",items:{type:"string"},description:"Classification tags"}},required:["source_type"]};$.register({name:"typescape_create_gci",description:"Create a guideline change item from observed patterns, thread feedback, or automated analysis. GCIs flow through the steering governance pipeline. Requires features.steering.",inputSchema:_4},async(O)=>{let Q=O;try{if(!(await A()).steering)return x("steering")}catch(z){if(z instanceof q)return V(z);throw z}if(!Q.source_type)return V(new q(400,"missing_param","Missing required parameter: source_type","local"));if(Q.source_type==="thread"&&!Q.thread_id)return V(new q(422,"invalid_argument","thread_id is required when source_type is 'thread'","local"));let H={...Q.proposed_content??{}};if(Q.title!==void 0&&H.title===void 0)H.title=Q.title;if(Q.content!==void 0&&H.content===void 0)H.content=Q.content;if(Q.target_document!==void 0&&H.target_document===void 0)H.target_document=Q.target_document;if(Q.priority!==void 0&&H.priority===void 0)H.priority=Q.priority;if(Q.tags!==void 0&&H.tags===void 0)H.tags=Q.tags;try{let z=Q.source_type==="thread"?"/steering/gcis/from-thread":"/steering/gcis",L=Q.source_type==="thread"?{thread_id:Q.thread_id,...Q.proposed_type?{proposed_type:Q.proposed_type}:{},...Q.rationale!==void 0?{rationale:Q.rationale}:{},...Object.keys(H).length>0?{proposed_content:H}:{}}:{source_type:Q.source_type,source_ref:Q.source_ref??Q.target_document??Q.title??"mcp:gci",proposed_type:Q.proposed_type??"constraint",proposed_content:H,...Q.source_excerpt!==void 0?{source_excerpt:Q.source_excerpt}:{},...Q.rationale!==void 0?{rationale:Q.rationale}:{},...Q.related_item_ids!==void 0?{related_item_ids:Q.related_item_ids}:{}},K=await W.post(z,{body:L});return v(j0(K.body),K.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let S4={type:"object",properties:{status:{type:"string",enum:["pending","in_review","needs_revision","approved","rejected","published"],description:"Filter by lifecycle status (default: pending)"},limit:{type:"number",default:20,description:"Maximum number of results"}}};$.register({name:"typescape_list_gcis",description:"List guideline change items filtered by status. Use to monitor the guidelines pipeline. Requires features.steering.",inputSchema:S4},async(O)=>{let Q=O;try{if(!(await A()).steering)return x("steering")}catch(H){if(H instanceof q)return V(H);throw H}try{let H={};if(Q.status)H.status=Q.status;if(Q.limit!==void 0&&Q.limit!==null)H.limit=String(Q.limit);let z=new URLSearchParams(H).toString(),L=await W.get(`/steering/gcis${z?`?${z}`:""}`);return v(L.body,L.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});let E4={type:"object",properties:{status:{type:"string",enum:["proposed","accepted","rejected","superseded"],description:"Filter by status (default: all)"},kind:{type:"string",enum:["terminology","style","structure","claim_policy","evidence_policy","voice","constraint"],description:"Filter by rule kind"},limit:{type:"number",default:20,description:"Maximum number of results"}}};$.register({name:"typescape_list_proposals",description:"List steering rule proposals. Proposals require operator approval before becoming active. Requires features.steering.",inputSchema:E4},async(O)=>{let Q=O;try{if(!(await A()).steering)return x("steering")}catch(H){if(H instanceof q)return V(H);throw H}try{let H={};if(Q.status)H.status=Q.status;if(Q.kind)H.kind=Q.kind;if(Q.limit!==void 0&&Q.limit!==null)H.limit=String(Q.limit);let z=new URLSearchParams(H).toString(),L=await W.get(`/steering/proposals${z?`?${z}`:""}`);return v(L.body,L.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});let v4={type:"object",properties:{include_degraded:{type:"boolean",default:!0,description:"Include degraded rule details"}}};$.register({name:"typescape_steering_dashboard",description:"Get aggregate steering health metrics: active rule count, average health, degraded rules. Requires features.steering.",inputSchema:v4},async(O)=>{let Q=O;try{if(!(await A()).steering)return x("steering")}catch(H){if(H instanceof q)return V(H);throw H}try{let H={},z="local";try{let L=await W.get("/steering/dashboard/summary");z=L.requestId,Object.assign(H,j0(L.body))}catch(L){if(!(L instanceof q))throw L;z=L.requestId||z,H.summary_unavailable={code:L.code,message:L.message};try{let K=await W.get("/steering/dashboard/rules?limit=1&offset=0");z=K.requestId;let _=K.body,f=_&&typeof _==="object"&&!Array.isArray(_)?_:{},I=typeof f.total==="number"&&Number.isFinite(f.total)?f.total:Array.isArray(f.data)?f.data.length:0;H.rule_health={total_rules:I}}catch(K){if(K instanceof q)H.rules_fallback_unavailable={code:K.code,message:K.message};else throw K}}if(Q.include_degraded!==!1)try{let K=(await W.get("/steering/dashboard/degradation")).body;if(K&&typeof K==="object"&&!Array.isArray(K)){let _=K;H.degraded_rules=_.degraded_rules??_.data??[]}else H.degraded_rules=[]}catch(L){if(L instanceof q&&(L.status===404||L.code==="not_found")){let K=await W.get("/steering/degradation");H.degraded_rules=K.body.degraded_rules??K.body.items??K.body.data??[]}else if(L instanceof q)H.degraded_rules=[],H.degraded_rules_unavailable={code:L.code,message:L.message};else throw L}return v(H,z)}catch(H){if(H instanceof q)return V(H);throw H}});let k4={type:"object",properties:{gci_id:{type:"string",description:"GCI ID to promote (must be in 'approved' status)"},kind:{type:"string",enum:["terminology","style","structure","claim_policy","evidence_policy","voice","constraint"],description:"Rule kind for the proposal"},scope:{type:"string",description:"File path glob scope (e.g., 'docs/api/**')"},content_override:{type:"string",description:"Formal rule content override"}},required:["gci_id"]};$.register({name:"typescape_promote_gci",description:"Convert an approved GCI into a steering proposal for operator acceptance. Requires features.steering.",inputSchema:k4},async(O)=>{let Q=O;try{if(!(await A()).steering)return x("steering")}catch(z){if(z instanceof q)return V(z);throw z}if(!Q.gci_id)return V(new q(400,"missing_param","Missing required parameter: gci_id","local"));let H={};if(Q.kind!==void 0)H.kind=Q.kind;if(Q.scope!==void 0)H.scope=Q.scope;if(Q.content_override!==void 0)H.content_override=Q.content_override;try{let z=await W.post(`/steering/gcis/${encodeURIComponent(Q.gci_id)}/publish`,{body:H});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let C4={type:"object",properties:{proposal_id:{type:"string",description:"Proposal ID to act on"},decision:{type:"string",enum:["accept","reject","deprecate"],description:"Decision to apply"},notes:{type:"string",description:"Decision rationale (required for reject)"}},required:["proposal_id","decision"]};$.register({name:"typescape_decide_proposal",description:"Accept, reject, or deprecate a steering proposal. Accepting activates the rule immediately. Requires features.steering.",inputSchema:C4},async(O)=>{let Q=O;try{if(!(await A()).steering)return x("steering")}catch(K){if(K instanceof q)return V(K);throw K}if(!Q.proposal_id)return V(new q(400,"missing_param","Missing required parameter: proposal_id","local"));if(!Q.decision)return V(new q(400,"missing_param","Missing required parameter: decision","local"));if(Q.decision==="reject"&&!Q.notes)return V(new q(422,"invalid_argument","notes is required when decision is 'reject'","local"));let z={accept:"activate",reject:"reject",deprecate:"deprecate"}[Q.decision],L={};if(Q.notes!==void 0)L.notes=Q.notes;try{let K=await W.post(`/steering/proposals/${encodeURIComponent(Q.proposal_id)}/${z}`,{body:L});return v(K.body,K.requestId)}catch(K){if(K instanceof q)return V(K);throw K}});let f4={name:"typescape_list_repos",description:"List connected repositories in the workspace. Returns paginated list of repos with their origin URLs and metadata.",inputSchema:{type:"object",properties:{include_archived:{type:"boolean",description:"Include archived repositories (default: false)"},limit:{type:"number",description:"Maximum repos to return (1-100, default: 50)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}}};$.register(f4,async(O)=>{let Q=O,H={};if(Q.include_archived)H.include_archived="true";if(Q.limit!==void 0)H.limit=String(Q.limit);if(Q.cursor)H.cursor=Q.cursor;try{let z=await W.get("/repos",{query:H});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let b4={name:"typescape_connect_repo",description:"Connect a Git repository by its origin URL. If the URL is a GitHub repo and a GitHub App installation exists, it will be automatically linked for branch/file browsing.",inputSchema:{type:"object",properties:{origin_url:{type:"string",description:"Git remote URL (HTTPS or SSH), e.g. https://github.com/acme/docs"},display_name:{type:"string",description:"Human-readable display name (optional, auto-derived from URL)"}},required:["origin_url"]}};$.register(b4,async(O)=>{let Q=O;if(!Q.origin_url)return V(new q(400,"missing_param","Missing required parameter: origin_url","local"));let H={origin_url:Q.origin_url};if(Q.display_name)H.display_name=Q.display_name;try{let z=await W.post("/repos",{body:H});return v(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let P4={name:"typescape_repo_branches",description:"List branches for a connected repository. Requires a GitHub App installation to be linked to the repo. Returns branch names and their head SHAs.",inputSchema:{type:"object",properties:{repo_id:{type:"string",description:"Repository ID (e.g. repo_abc123)"}},required:["repo_id"]}};$.register(P4,async(O)=>{let Q=O;if(!Q.repo_id)return V(new q(400,"missing_param","Missing required parameter: repo_id","local"));try{let H=await W.get(`/repos/${encodeURIComponent(Q.repo_id)}/branches`);return v(H.body,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});let I4=5242880,T4=new Set(["image/png","image/jpeg","image/gif","image/webp"]),g4={name:"typescape_upload_reviewer_asset",description:"Upload a reviewer asset (image) to a session. Accepts base64-encoded image data (PNG, JPEG, GIF, WebP). Maximum size: 5MB. For larger files, use the CLI or web UI.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID to upload the asset to"},base64_content:{type:"string",description:"Base64-encoded image data"},mime_type:{type:"string",enum:["image/png","image/jpeg","image/gif","image/webp"],description:"MIME type of the image"},alt_text:{type:"string",description:"Alt text for the image (optional)"},filename:{type:"string",description:"Original filename (optional)"}},required:["session_id","base64_content","mime_type"]}};$.register(g4,async(O)=>{let Q=O;if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));if(!Q.base64_content)return V(new q(400,"missing_param","Missing required parameter: base64_content","local"));if(!Q.mime_type)return V(new q(400,"missing_param","Missing required parameter: mime_type","local"));if(!T4.has(Q.mime_type))return V(new q(415,"unsupported_media_type",`Unsupported MIME type "${Q.mime_type}". Allowed: PNG, JPEG, GIF, WebP.`,"local"));if(!K4.test(Q.base64_content))return V(new q(400,"invalid_base64","base64_content is not valid base64-encoded data","local"));let H;try{let K=Buffer.from(Q.base64_content,"base64");H=new Uint8Array(K)}catch{return V(new q(400,"invalid_base64","Failed to decode base64_content","local"))}if(H.byteLength>I4){let K=(H.byteLength/1048576).toFixed(1);return V(new q(413,"asset_too_large",`Image is ${K}MB, exceeding the 5MB MCP limit. Use the CLI ("typescape asset upload") or web UI for larger files.`,"local"))}let z=new Blob([H],{type:Q.mime_type}),L=new FormData;if(L.append("file",z,Q.filename||`upload.${f6(Q.mime_type)}`),L.append("mime_type",Q.mime_type),Q.alt_text)L.append("alt_text",Q.alt_text);try{let K=await W.postFormData(`/sessions/${encodeURIComponent(Q.session_id)}/reviewer-assets`,L);return v(K.body,K.requestId)}catch(K){if(K instanceof q)return V(K);throw K}}),$.register({name:"typescape_create_collection",description:"Create a new collection to group related review sessions. Requires collections_enabled feature flag. Returns the created collection with its ID.",inputSchema:k6},async(O)=>{let Q=O;if(!Q.name)return V(new q(400,"missing_param","Missing required parameter: name","local"));try{if(!(await A()).collections_enabled)return x("collections_enabled")}catch(z){if(z instanceof q)return V(z);throw z}let H={name:Q.name};if(Q.description!==void 0)H.description=Q.description;if(Q.color!==void 0)H.color=Q.color;try{let z=await W.post("/collections",{body:H}),L=z.body&&typeof z.body==="object"&&!Array.isArray(z.body)&&z.body.data&&typeof z.body.data==="object"&&!Array.isArray(z.body.data)?z.body.data:z.body;return v(L,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}}),$.register({name:"typescape_add_session_to_collection",description:"Add a review session to an existing collection. Idempotent: re-adding an already-present session is a no-op. Requires collections_enabled feature flag.",inputSchema:C6},async(O)=>{let Q=O;if(!Q.collection_id)return V(new q(400,"missing_param","Missing required parameter: collection_id","local"));if(!Q.session_id)return V(new q(400,"missing_param","Missing required parameter: session_id","local"));try{if(!(await A()).collections_enabled)return x("collections_enabled")}catch(H){if(H instanceof q)return V(H);throw H}try{let H=await W.post(`/collections/${encodeURIComponent(Q.collection_id)}/sessions`,{body:{session_id:Q.session_id}}),z=H.body&&typeof H.body==="object"&&!Array.isArray(H.body)&&H.body.data&&typeof H.body.data==="object"&&!Array.isArray(H.body.data)?H.body.data:H.body;return v(z,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}})}function f6($){switch($){case"image/png":return"png";case"image/jpeg":return"jpg";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}var N4={TYPESCAPE_API_KEY:"Operator API token for authenticating with the Typescape API",TYPESCAPE_BASE_URL:"Base URL of the Typescape API server (e.g., https://review.example.com)"};function b6(){let $=process.env.TYPESCAPE_API_KEY,W=process.env.TYPESCAPE_BASE_URL,X=[];if(!$)X.push(`TYPESCAPE_API_KEY: ${N4.TYPESCAPE_API_KEY}`);if(!W)X.push(`TYPESCAPE_BASE_URL: ${N4.TYPESCAPE_BASE_URL}`);if(X.length>0){console.error("Error: Missing required environment variables:");for(let J of X)console.error(` - ${J}`);process.exit(1)}return{apiKey:$,baseUrl:W}}function P6($,W=e1){if(!$||$.trim().length===0)return{timeoutMs:W,warning:null};let X=$.trim();if(/^\d+$/.test(X)){let J=Number(X);if(J>=1000)return{timeoutMs:J,warning:null}}return{timeoutMs:W,warning:`Warning: Invalid TYPESCAPE_TIMEOUT_MS='${$}'. Using default ${W}ms.`}}async function I6(){let{apiKey:$,baseUrl:W}=b6(),X=process.env.TYPESCAPE_TIMEOUT_MS,J=P6(X,e1),Y=J.timeoutMs;if(J.warning)console.warn(J.warning);let w=l0(W,$,Y),B=m0();D4(B,w),await O4(B)}if(import.meta.main)I6().catch(($)=>{console.error("Fatal error:",$ instanceof Error?$.message:String($)),process.exit(1)});export{P6 as resolveTimeoutMs};
|