@typescape-ai/mcp 1.9.3 → 1.9.5
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((I3,c4)=>{c4.exports={name:"@typescape-ai/mcp",version:"1.9.3",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 C={Authorization:`Bearer ${W}`,Accept:"application/json","User-Agent":Z0,...j.headers};if(j.body!==void 0)C["Content-Type"]="application/json";let I;try{I=await fetch(R,{method:B,headers:C,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((I.headers.get("Content-Type")||"").includes("application/json"))try{h=await I.json()}catch{h={}}else h={};let Z=h?.request_id||I.headers.get("X-Request-Id")||"unknown";if(!I.ok){let A=h,T=A.error?.code||"api_error",Q1=A.error?.message||`API request failed with status ${I.status}`;throw new q(I.status,T,Q1,Z,A.error?.details,A.error?.fix_hint)}return{status:I.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 C={Authorization:`Bearer ${W}`,Accept:"application/json","User-Agent":Z0,...j?.headers},I;try{I=await fetch(R,{method:"POST",headers:C,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((I.headers.get("Content-Type")||"").includes("application/json"))try{h=await I.json()}catch{h={}}else h={};let Z=h?.request_id||I.headers.get("X-Request-Id")||"unknown";if(!I.ok){let A=h,T=A.error?.code||"api_error",Q1=A.error?.message||`API request failed with status ${I.status}`;throw new q(I.status,T,Q1,Z,A.error?.details,A.error?.fix_hint)}return{status:I.status,body:h,requestId:Z}},request:w}}var f;(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}})(f||(f={}));var K0;(function($){$.mergeShapes=(W,X)=>{return{...W,...X}}})(K0||(K0={}));var D=f.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=f.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,f.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,f.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:X=`Unrecognized key(s) in object: ${f.joinValues($.keys,", ")}`;break;case L.invalid_union:X="Invalid input";break;case L.invalid_union_discriminator:X=`Invalid discriminator value. Expected ${f.joinValues($.options)}`;break;case L.invalid_enum_value:X=`Invalid enum value. Expected ${f.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 f.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,f.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 v($){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:C}=$;if(B.code==="invalid_enum_value")return{message:C!==null&&C!==void 0?C:M.defaultError};if(typeof M.data>"u")return{message:(j=C!==null&&C!==void 0?C:J)!==null&&j!==void 0?j:M.defaultError};if(B.code!=="invalid_type")return{message:M.defaultError};return{message:(R=C!==null&&C!==void 0?C:X)!==null&&R!==void 0?R:M.defaultError}},description:Y}}class b{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 C1.create([this,$],this._def)}and($){return f1.create(this,$,this._def)}transform($){return new d({...v(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:$}})}default($){let W=typeof $==="function"?$:()=>$;return new g1({...v(this._def),innerType:this,defaultValue:W,typeName:_.ZodDefault})}brand(){return new Y0({typeName:_.ZodBranded,type:this,...v(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new x1({...v(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)?)??$/,$9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,W9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",F0,X9=/^(?:(?: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])$/,Q9=/^(?:(?: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])$/,Y9=/^(([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]))$/,J9=/^(([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])$/,H9=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,G9=/^([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])))",z9=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 w9($){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 B9($,W){if((W==="v4"||!W)&&X9.test($))return!0;if((W==="v6"||!W)&&Y9.test($))return!0;return!1}function q9($,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 V9($,W){if((W==="v4"||!W)&&Q9.test($))return!0;if((W==="v6"||!W)&&J9.test($))return!0;return!1}class i extends b{_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(!$9.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(W9,"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(!z9.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(!w9(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(!B9($.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(!q9($.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(!V9($.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(!H9.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(!G9.test($.data))J=this._getOrReturnCtx($,J),K(J,{validation:"base64url",code:L.invalid_string,message:Y.message}),X.dirty()}else f.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,...v($)})};function M9($,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 b{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(!f.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(M9($.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 f.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"&&f.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,...v($)})};class q1 extends b{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 f.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,...v($)})};class v1 extends b{_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,...v($)})};class L1 extends b{_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 f.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,...v($)})};class u1 extends b{_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,...v($)})};class k1 extends b{_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,...v($)})};class b1 extends b{_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)}}b1.create=($)=>{return new b1({typeName:_.ZodNull,...v($)})};class F1 extends b{constructor(){super(...arguments);this._any=!0}_parse($){return c($.data)}}F1.create=($)=>{return new F1({typeName:_.ZodAny,...v($)})};class w1 extends b{constructor(){super(...arguments);this._unknown=!0}_parse($){return c($.data)}}w1.create=($)=>{return new w1({typeName:_.ZodUnknown,...v($)})};class $1 extends b{_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,...v($)})};class n1 extends b{_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,...v($)})};class o extends b{_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,...v(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 b{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=f.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],C=J.data[j];M.push({key:{status:"valid",value:j},value:R._parse(new t(J,C,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 C=J.data[R];M.push({key:{status:"valid",value:R},value:j._parse(new t(J,C,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 C=await R.key,I=await R.value;j.push({key:C,value:I,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 f.objectKeys($).forEach((X)=>{if($[X]&&this.shape[X])W[X]=this.shape[X]}),new x({...this._def,shape:()=>W})}omit($){let W={};return f.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 f.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 f.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(f.objectKeys(this.shape))}}x.create=($,W)=>{return new x({shape:()=>$,unknownKeys:"strip",catchall:$1.create(),typeName:_.ZodObject,...v(W)})};x.strictCreate=($,W)=>{return new x({shape:()=>$,unknownKeys:"strict",catchall:$1.create(),typeName:_.ZodObject,...v(W)})};x.lazycreate=($,W)=>{return new x({shape:$,unknownKeys:"strip",catchall:$1.create(),typeName:_.ZodObject,...v(W)})};class C1 extends b{_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}}C1.create=($,W)=>{return new C1({options:$,typeName:_.ZodUnion,...v(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 f.objectValues($.enum);else if($ instanceof g1)return H1($._def.innerType);else if($ instanceof k1)return[void 0];else if($ instanceof b1)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 b{_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,...v(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=f.objectKeys(W),w=f.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 f1 extends b{_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}))}}f1.create=($,W,X)=>{return new f1({left:$,right:W,typeName:_.ZodIntersection,...v(X)})};class W1 extends b{_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,...v(W)})};class d1 extends b{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 b)return new d1({keyType:$,valueType:W,typeName:_.ZodRecord,...v(X)});return new d1({keyType:i.create(),valueType:$,typeName:_.ZodRecord,...v(W)})}}class p1 extends b{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,...v(X)})};class K1 extends b{_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,...v(W)})};class S1 extends b{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}),C=await Reflect.apply(w,this,R);return await B._def.returns._def.type.parseAsync(C,Y).catch((h)=>{throw j.addIssue(J(C,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),C=B._def.returns.safeParse(R,Y);if(!C.success)throw new u([J(R,C.error)]);return C.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,...v(X)})}}class P1 extends b{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,...v(W)})};class I1 extends b{_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,...v(W)})};function i0($,W){return new V1({values:$,typeName:_.ZodEnum,...v(W)})}class V1 extends b{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:f.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 b{constructor(){super(...arguments);l1.set(this,void 0)}_parse($){let W=f.getValidEnumValues(this._def.values),X=this._getOrReturnCtx($);if(X.parsedType!==D.string&&X.parsedType!==D.number){let J=f.objectValues(W);return K(X,{expected:f.joinValues(J),received:X.parsedType,code:L.invalid_type}),S}if(!X0(this,l1,"f"))u0(this,l1,new Set(f.getValidEnumValues(this._def.values)),"f");if(!X0(this,l1,"f").has($.data)){let J=f.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,...v(W)})};class U1 extends b{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,...v(W)})};class d extends b{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}))});f.assertNever(J)}}d.create=($,W,X)=>{return new d({schema:$,typeName:_.ZodEffects,effect:W,...v(X)})};d.createWithPreprocess=($,W,X)=>{return new d({schema:W,effect:{type:"preprocess",transform:$},typeName:_.ZodEffects,...v(X)})};class a extends b{_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,...v(W)})};class z1 extends b{_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,...v(W)})};class g1 extends b{_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,...v(W)})};class x1 extends b{_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,...v(W)})};class i1 extends b{_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,...v($)})};var O9=Symbol("zod_brand");class Y0 extends b{_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 b{_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 b{_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,...v(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 j9={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 L9=($,W={message:`Input not instance of ${$.name}`})=>o0((X)=>X instanceof $,W),a0=i.create,t0=B1.create,F9=i1.create,K9=q1.create,r0=v1.create,U9=L1.create,D9=u1.create,R9=k1.create,N9=b1.create,A9=F1.create,_9=w1.create,S9=$1.create,E9=n1.create,v9=o.create,k9=x.create,b9=x.strictCreate,C9=C1.create,f9=Q0.create,P9=f1.create,I9=W1.create,T9=d1.create,g9=p1.create,x9=K1.create,h9=S1.create,Z9=P1.create,m9=I1.create,y9=V1.create,l9=T1.create,c9=U1.create,l0=d.create,u9=a.create,n9=z1.create,d9=d.createWithPreprocess,p9=o1.create,i9=()=>a0().optional(),o9=()=>t0().optional(),a9=()=>r0().optional(),t9={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})},r9=S,G=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 f},get objectUtil(){return K0},ZodParsedType:D,getParsedType:G1,ZodType:b,datetimeRegex:p0,ZodString:i,ZodNumber:B1,ZodBigInt:q1,ZodBoolean:v1,ZodDate:L1,ZodSymbol:u1,ZodUndefined:k1,ZodNull:b1,ZodAny:F1,ZodUnknown:w1,ZodNever:$1,ZodVoid:n1,ZodArray:o,ZodObject:x,ZodUnion:C1,ZodDiscriminatedUnion:Q0,ZodIntersection:f1,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:O9,ZodBranded:Y0,ZodPipeline:o1,ZodReadonly:h1,custom:o0,Schema:b,ZodSchema:b,late:j9,get ZodFirstPartyTypeKind(){return _},coerce:t9,any:A9,array:v9,bigint:K9,boolean:r0,date:U9,discriminatedUnion:f9,effect:l0,enum:y9,function:h9,instanceof:L9,intersection:P9,lazy:Z9,literal:m9,map:g9,nan:F9,nativeEnum:l9,never:S9,null:N9,nullable:n9,number:t0,object:k9,oboolean:a9,onumber:o9,optional:u9,ostring:i9,pipeline:p9,preprocess:d9,promise:c9,record:T9,set:x9,strictObject:b9,string:a0,symbol:D9,transformer:l0,tuple:I9,undefined:R9,union:C9,unknown:_9,void:E9,NEVER:r9,ZodIssueCode:L,quotelessJson:n4,ZodError:u});var N0="2024-11-05",s0=[N0,"2024-10-07"],J0="2.0",e0=G.union([G.string(),G.number().int()]),$4=G.string(),r=G.object({_meta:G.optional(G.object({progressToken:G.optional(e0)}).passthrough())}).passthrough(),n=G.object({method:G.string(),params:G.optional(r)}),a1=G.object({_meta:G.optional(G.object({}).passthrough())}).passthrough(),X1=G.object({method:G.string(),params:G.optional(a1)}),s=G.object({_meta:G.optional(G.object({}).passthrough())}).passthrough(),H0=G.union([G.string(),G.number().int()]),s9=G.object({jsonrpc:G.literal(J0),id:H0}).merge(n).strict(),e9=G.object({jsonrpc:G.literal(J0)}).merge(X1).strict(),$2=G.object({jsonrpc:G.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 W2=G.object({jsonrpc:G.literal(J0),id:H0,error:G.object({code:G.number().int(),message:G.string(),data:G.optional(G.unknown())})}).strict(),W4=G.union([s9,e9,$2,W2]),G0=s.strict(),z0=X1.extend({method:G.literal("notifications/cancelled"),params:a1.extend({requestId:H0,reason:G.string().optional()})}),X4=G.object({name:G.string(),version:G.string()}).passthrough(),X2=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(),A0=n.extend({method:G.literal("initialize"),params:r.extend({protocolVersion:G.string(),capabilities:X2,clientInfo:X4})}),Q2=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(),Y2=s.extend({protocolVersion:G.string(),capabilities:Q2,serverInfo:X4}),_0=X1.extend({method:G.literal("notifications/initialized")}),w0=n.extend({method:G.literal("ping")}),J2=G.object({progress:G.number(),total:G.optional(G.number())}).passthrough(),B0=X1.extend({method:G.literal("notifications/progress"),params:a1.merge(J2).extend({progressToken:e0})}),q0=n.extend({params:r.extend({cursor:G.optional($4)}).optional()}),V0=s.extend({nextCursor:G.optional($4)}),Q4=G.object({uri:G.string(),mimeType:G.optional(G.string())}).passthrough(),Y4=Q4.extend({text:G.string()}),J4=Q4.extend({blob:G.string().base64()}),H2=G.object({uri:G.string(),name:G.string(),description:G.optional(G.string()),mimeType:G.optional(G.string())}).passthrough(),G2=G.object({uriTemplate:G.string(),name:G.string(),description:G.optional(G.string()),mimeType:G.optional(G.string())}).passthrough(),z2=q0.extend({method:G.literal("resources/list")}),w2=V0.extend({resources:G.array(H2)}),B2=q0.extend({method:G.literal("resources/templates/list")}),q2=V0.extend({resourceTemplates:G.array(G2)}),V2=n.extend({method:G.literal("resources/read"),params:r.extend({uri:G.string()})}),M2=s.extend({contents:G.array(G.union([Y4,J4]))}),O2=X1.extend({method:G.literal("notifications/resources/list_changed")}),j2=n.extend({method:G.literal("resources/subscribe"),params:r.extend({uri:G.string()})}),L2=n.extend({method:G.literal("resources/unsubscribe"),params:r.extend({uri:G.string()})}),F2=X1.extend({method:G.literal("notifications/resources/updated"),params:a1.extend({uri:G.string()})}),K2=G.object({name:G.string(),description:G.optional(G.string()),required:G.optional(G.boolean())}).passthrough(),U2=G.object({name:G.string(),description:G.optional(G.string()),arguments:G.optional(G.array(K2))}).passthrough(),D2=q0.extend({method:G.literal("prompts/list")}),R2=V0.extend({prompts:G.array(U2)}),N2=n.extend({method:G.literal("prompts/get"),params:r.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(),H4=G.object({type:G.literal("resource"),resource:G.union([Y4,J4])}).passthrough(),A2=G.object({role:G.enum(["user","assistant"]),content:G.union([M0,O0,H4])}).passthrough(),_2=s.extend({description:G.optional(G.string()),messages:G.array(A2)}),S2=X1.extend({method:G.literal("notifications/prompts/list_changed")}),E2=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(),S0=q0.extend({method:G.literal("tools/list")}),v2=V0.extend({tools:G.array(E2)}),G4=s.extend({content:G.array(G.union([M0,O0,H4])),isError:G.boolean().default(!1).optional()}),h3=G4.or(s.extend({toolResult:G.unknown()})),E0=n.extend({method:G.literal("tools/call"),params:r.extend({name:G.string(),arguments:G.optional(G.record(G.unknown()))})}),k2=X1.extend({method:G.literal("notifications/tools/list_changed")}),z4=G.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),b2=n.extend({method:G.literal("logging/setLevel"),params:r.extend({level:z4})}),C2=X1.extend({method:G.literal("notifications/message"),params:a1.extend({level:z4,logger:G.optional(G.string()),data:G.unknown()})}),f2=G.object({name:G.string().optional()}).passthrough(),P2=G.object({hints:G.optional(G.array(f2)),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(),I2=G.object({role:G.enum(["user","assistant"]),content:G.union([M0,O0])}).passthrough(),T2=n.extend({method:G.literal("sampling/createMessage"),params:r.extend({messages:G.array(I2),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(P2)})}),v0=s.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])}),g2=G.object({type:G.literal("ref/resource"),uri:G.string()}).passthrough(),x2=G.object({type:G.literal("ref/prompt"),name:G.string()}).passthrough(),h2=n.extend({method:G.literal("completion/complete"),params:r.extend({ref:G.union([x2,g2]),argument:G.object({name:G.string(),value:G.string()}).passthrough()})}),Z2=s.extend({completion:G.object({values:G.array(G.string()).max(100),total:G.optional(G.number().int()),hasMore:G.optional(G.boolean())}).passthrough()}),m2=G.object({uri:G.string().startsWith("file://"),name:G.optional(G.string())}).passthrough(),y2=n.extend({method:G.literal("roots/list")}),k0=s.extend({roots:G.array(m2)}),l2=X1.extend({method:G.literal("notifications/roots/list_changed")}),Z3=G.union([w0,A0,h2,b2,N2,D2,z2,B2,V2,j2,L2,E0,S0]),m3=G.union([z0,B0,_0,l2]),y3=G.union([G0,v0,k0]),l3=G.union([w0,T2,y2]),c3=G.union([z0,B0,C2,F2,O2,k2,S2]),u3=G.union([G0,Y2,Z2,_2,R2,w2,q2,M2,G4,v2]);class t1 extends Error{constructor($,W,X){super(`MCP error ${$}: ${W}`);this.code=$,this.data=X}}var c2=60000;class b0{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++,C={...$,jsonrpc:"2.0",id:R};if(X===null||X===void 0?void 0:X.onprogress)this._progressHandlers.set(R,X.onprogress),C.params={...$.params,_meta:{progressToken:R}};let I=void 0;this._responseHandlers.set(R,(Z)=>{var A;if(I!==void 0)clearTimeout(I);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 T=W.parse(Z.result);J(T)}catch(T){Y(T)}});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((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`))),Y(Z)};(M=X===null||X===void 0?void 0:X.signal)===null||M===void 0||M.addEventListener("abort",()=>{var Z;if(I!==void 0)clearTimeout(I);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:c2;I=setTimeout(()=>h(new t1(D1.RequestTimeout,"Request timed out",{timeout:e})),e),this._transport.send(C).catch((Z)=>{if(I!==void 0)clearTimeout(I);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 C0 extends b0{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 f0{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 f0,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 n2=await Promise.resolve().then(() => x0(L0(),1)),q4=n2.version;async function V4($){let W=new C0({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"],d2=new Set(I0),p2=1e7,L4=/^[A-Za-z0-9+/]*={0,2}$/,M4="inline_assets_enabled",i2={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"]},o2={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"]},a2={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"]},t2={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:[]},r2={type:"object",properties:{session_id:{type:"string",description:"Session ID to retrieve (e.g., sess_01HXYZ...)"}},required:["session_id"]},s2={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"]},e2={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"]},$3={type:"object",properties:{session_id:{type:"string",description:"Session ID to export response matrix for (e.g., sess_01HXYZ...)"}},required:["session_id"]};function k($,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 W3($,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 X3($){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 Q3($){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 Y3($){let X=$.replace(/\\/g,"/").split("/"),J=X[X.length-1];return J&&J.length>0?J:"asset.bin"}async function J3($,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 C=F4(R);if(C===null)throw new q(422,"invalid_argument",`Invalid base64 content for asset: ${j}`,"local");w.append(j,new Blob([C]),Y3(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 H3($){if($==="approver")return["read","comment","approve"];if($==="observer")return["read"];if($==="owner")return["read","comment","approve","admin"];return["read","comment"]}function G3($){return $.map((W)=>{let X=W.scopes&&W.scopes.length>0?[...new Set(W.scopes)]:H3(W.role);return{email:W.email,...W.name?{name:W.name}:{},role:W.role,scopes:X}})}var z3={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"]},w3={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"]},B3={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"]},q3={type:"object",properties:{review_ref_id:{type:"string",description:"Review ref ID to resolve"}},required:["review_ref_id"]},V3={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"]},M3={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"]},O3={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"]},j3={type:"object",properties:{session_id:{type:"string",description:"Session ID to run checks against"}},required:["session_id"]},L3={type:"object",properties:{},additionalProperties:!1},F3={type:"object",properties:{},additionalProperties:!1},K3={type:"object",properties:{},additionalProperties:!1},U3={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. 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"]},D3={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"]},R3={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"]},N3={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"]},A3={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"]},_3={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"]},S3={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"]},E3={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:i2};$.register(X,async(O)=>{let Q=O,H=W3(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 F=typeof Q.repo_id==="string"&&Q.repo_id.length>0,U=typeof Q.git_sha==="string"&&Q.git_sha.length>0,E=typeof Q.project_id==="string"&&Q.project_id.length>0,P=typeof Q.upload_batch_id==="string"&&Q.upload_batch_id.length>0,p=F&&U,y=E&&P,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(E&&!P||!E&&P)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=X3(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>p2)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=G3(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 k({session:g.body.session,invitations:g.body.invitations??[]},g.requestId)}catch(g){if(g instanceof q){if(M1&&!y&&!p&&!R1&&(N1||m1)&&Q3(g))try{let{projectId:J1,uploadBatchId:s1}=await J3(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 k({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:o2};$.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,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 E=[H,z,F].filter(Boolean).length;if(E===0)return V(new q(400,"missing_param","One of git_sha, content_body, or upload_batch_id is required","local"));if(E>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 P={};if(H)P.git_sha=Q.git_sha.toLowerCase();if(z)P.content_body=Q.content_body;if(F)P.project_id=Q.project_id,P.upload_batch_id=Q.upload_batch_id;if(Q.file_path!==void 0)P.file_path=Q.file_path;if(Q.document_type!==void 0)P.document_type=Q.document_type;if(Q.filename!==void 0)P.filename=Q.filename;else if(Q.document_type==="pdf"&&Q.file_path!==void 0)P.filename=Q.file_path;if(Q.filenames!==void 0&&Q.filenames.length>0)P.filenames=Q.filenames;if(Q.title!==void 0)P.title=Q.title;if(Q.changes_summary!==void 0)P.changes_summary=Q.changes_summary;if(Q.resolutions!==void 0&&Q.resolutions.length>0)P.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:P,headers:p});return k(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:a2};$.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 F=await W.get(`/sessions/${Q.session_id}/export`,{query:H,headers:z});return k(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:t2};$.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 k(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:r2};$.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 k(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:s2},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 C(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 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 E=await W.post("/auth/exchange",{body:{url_token:R(U)}}),P=E.body.session_access_token,p=E.body.expires_in_seconds;if(!P||typeof P!=="string")throw new q(500,"token_exchange_failed","Failed to exchange review link for session access token",E.requestId);let y=typeof p==="number"&&Number.isFinite(p)?Math.max(0,Math.trunc(p)-30)*1000:300000;return j.set(O,{token:P,expiresAtMs:Date.now()+y}),P}$.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 C(Q.session_id),F=await W.get(`/sessions/${Q.session_id}/render`,{query:H,headers:{Authorization:`Bearer ${z}`}});return k(F.body,F.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let I={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:e2};$.register(I,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 k(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:$3};$.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 H=await W.get(`/sessions/${Q.session_id}/export`,{query:{schema:"v1",view:"response_matrix.v1"}});return k(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'. Severity 'blocking' is coerced to 'needs_changes' for automation sources.",inputSchema:U3},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,F=typeof Q.anchor_block_id==="string"?Q.anchor_block_id.trim():void 0,U=z||F;if(U)H.block_id=U;if(Q.anchor!==void 0)H.anchor=Q.anchor;else if(Q.anchor_type)H.anchor={type:Q.anchor_type};else if(U)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 E={};if(Q.idempotency_key)E["Idempotency-Key"]=Q.idempotency_key;try{let P=await W.post(`/sessions/${Q.session_id}/threads`,{body:H,headers:E});return k(P.body,P.requestId)}catch(P){if(P instanceof q)return V(P);throw P}}),$.register({name:"typescape_post_comment",description:"Post a comment (reply) to an existing thread. Returns the created comment with its ID.",inputSchema:D3},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 F=await W.post(`/sessions/${Q.session_id}/threads/${Q.thread_id}/comments`,{body:H,headers:z});return k(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:R3},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={},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:H,headers:z});return k(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:N3},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={},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:H,headers:z});return k(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:A3},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 k(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:_3},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 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 E of U)if(Q[E]!==void 0){let P=E==="note_md"?"text":E;z[P]=Q[E]}}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 F={evidence_type:H,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 k(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 T(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:z3},async(O)=>{let Q=O;try{if(!(await A()).review_sets)return T("review_sets")}catch(E){if(E instanceof q)return V(E);throw E}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 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(H)F.sessions=Q.sessions;if(z)F.files=Q.files;if(Q.participants!==void 0)F.participants=Q.participants.map((E)=>{if(Array.isArray(E.roles)&&E.roles.length>0)return{email:E.email,roles:E.roles};if(E.role)return{email:E.email,roles:[E.role]};return E});let U={};if(Q.idempotency_key)U["Idempotency-Key"]=Q.idempotency_key;try{let E=await W.post("/review-sets",{body:F,headers:U});return k(E.body,E.requestId)}catch(E){if(E instanceof q)return V(E);throw E}}),$.register({name:"typescape_export_review_set",description:"Export feedback from a review set. Requires features.review_sets to be enabled.",inputSchema:w3},async(O)=>{let Q=O;try{if(!(await A()).review_sets)return T("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 k(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:B3},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(!d2.has(H))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: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 F=await W.post("/review-refs",{body:z});return k(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:q3},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 k(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:V3},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 k(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:M3},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 F=await W.post(`/sessions/${encodeURIComponent(Q.session_id)}/request-approval`,{body:H,headers:z});return k(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:O3},async(O)=>{let Q=O;try{if(!(await A()).policy)return T("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 k(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:j3},async(O)=>{let Q=O;try{if(!(await A()).checks)return T("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 k(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:L3},async()=>{try{let O=await W.get("/account/usage");return k(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:F3},async()=>{try{let O=await W.get("/account/plan");return k(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:K3},async()=>{try{let O=await W.get("/me/capabilities");return k(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 T("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 k(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 T("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 k(z.body,z.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});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 T("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 k(H.body,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});let R4={type:"object",properties:{repo_id:{type:"string",description:"Repository identifier"},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}},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 T("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 H=Q.format??"prompt_fragment";try{let z=new URLSearchParams({format:H==="structured"?"structured.v1":"prompt_fragment.v1"}),F=Q.file_path??Q.path;if(F)z.set("file_path",F);if(Q.policy_snapshot_id)z.set("policy_snapshot_id",Q.policy_snapshot_id);if(Q.token_budget!==void 0&&Q.token_budget!==null)z.set("token_budget",String(Q.token_budget));let U=await W.get(`/repos/${encodeURIComponent(Q.repo_id)}/steering-pack?${z}`),E=U.body;if(H==="prompt_fragment"&&E.prompt_fragment)E.non_authoritative=!0;return k(E,U.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","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:N4},async(O)=>{let Q=O;try{if(!(await A()).steering)return T("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",F=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}:{}},U=await W.post(z,{body:F});return k(U.body,U.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 T("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(),F=await W.get(`/steering/gcis${z?`?${z}`:""}`);return k(F.body,F.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});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 T("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(),F=await W.get(`/steering/proposals${z?`?${z}`:""}`);return k(F.body,F.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});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 T("steering")}catch(H){if(H instanceof q)return V(H);throw H}try{let H=await W.get("/steering/dashboard/summary"),z={...H.body};if(Q.include_degraded!==!1)try{let F=await W.get("/steering/dashboard/degradation");z.degraded_rules=F.body.degraded_rules??[]}catch(F){if(F instanceof q&&(F.status===404||F.code==="not_found")){let U=await W.get("/steering/degradation");z.degraded_rules=U.body.degraded_rules??U.body.items??U.body.data??[]}else if(F instanceof q)z.degraded_rules=[],z.degraded_rules_unavailable={code:F.code,message:F.message};else throw F}return k(z,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});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 T("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 k(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 T("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 k(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,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 k(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 k(z.body,z.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let C4={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(C4,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 k(H.body,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}});let f4=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 H;try{let U=Buffer.from(Q.base64_content,"base64");H=new Uint8Array(U)}catch{return V(new q(400,"invalid_base64","Failed to decode base64_content","local"))}if(H.byteLength>f4){let U=(H.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([H],{type:Q.mime_type}),F=new FormData;if(F.append("file",z,Q.filename||`upload.${v3(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 k(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:S3},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 T("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}),F=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 k(F,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:E3},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 T("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 k(z,H.requestId)}catch(H){if(H instanceof q)return V(H);throw H}})}function v3($){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 k3(){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 b3($,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 C3(){let{apiKey:$,baseUrl:W}=k3(),X=process.env.TYPESCAPE_TIMEOUT_MS,J=b3(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)C3().catch(($)=>{console.error("Fatal error:",$ instanceof Error?$.message:String($)),process.exit(1)});export{b3 as resolveTimeoutMs};
|
|
2
|
+
var m4=Object.create;var{getPrototypeOf:y4,defineProperty:y0,getOwnPropertyNames:l4}=Object;var c4=Object.prototype.hasOwnProperty;function u4($){return this[$]}var n4,d4,l0=($,W,X)=>{var J=$!=null&&typeof $==="object";if(J){var Y=W?n4??=new WeakMap:d4??=new WeakMap,w=Y.get($);if(w)return w}X=$!=null?m4(y4($)):{};let B=W||!$||!$.__esModule?y0(X,"default",{value:$,enumerable:!0}):X;for(let M of l4($))if(!c4.call(B,M))y0(B,M,{get:u4.bind($,M),enumerable:!0});if(J)Y.set($,B);return B};var p4=($,W)=>()=>(W||$((W={exports:{}}).exports,W),W.exports);var K0=p4((l6,i4)=>{i4.exports={name:"@typescape-ai/mcp",version:"1.9.5",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 c0(){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 o4=await Promise.resolve().then(() => l0(K0(),1)),u0=`typescape-mcp/${o4.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 $0=30000;function n0($,W,X=$0){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":u0,...j.headers};if(j.body!==void 0)b["Content-Type"]="application/json";let x;try{x=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 m1=Math.round(X/1000);throw new q(0,"request_timeout",`Request timed out after ${m1}s. Check your network connection and server URL.`,"unknown")}let G1=A instanceof Error?A.message:String(A);throw new q(0,"network_error",`Network error: ${G1}`,"unknown")}let m;if((x.headers.get("Content-Type")||"").includes("application/json"))try{m=await x.json()}catch{m={}}else m={};let y=m?.request_id||x.headers.get("X-Request-Id")||"unknown";if(!x.ok){let A=m,h=A.error?.code||"api_error",G1=A.error?.message||`API request failed with status ${x.status}`;throw new q(x.status,h,G1,y,A.error?.details,A.error?.fix_hint)}return{status:x.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":u0,...j?.headers},x;try{x=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 m1=Math.round(X/1000);throw new q(0,"request_timeout",`Request timed out after ${m1}s. Check your network connection and server URL.`,"unknown")}let G1=A instanceof Error?A.message:String(A);throw new q(0,"network_error",`Network error: ${G1}`,"unknown")}let m;if((x.headers.get("Content-Type")||"").includes("application/json"))try{m=await x.json()}catch{m={}}else m={};let y=m?.request_id||x.headers.get("X-Request-Id")||"unknown";if(!x.ok){let A=m,h=A.error?.code||"api_error",G1=A.error?.message||`API request failed with status ${x.status}`;throw new q(x.status,h,G1,y,A.error?.details,A.error?.fix_hint)}return{status:x.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 D0;(function($){$.mergeShapes=(W,X)=>{return{...W,...X}}})(D0||(D0={}));var D=P.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),B1=($)=>{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"]),a4=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class i 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 i))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()}}i.create=($)=>{return new i($)};var v1=($,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}},i0=v1;function t4($){i0=$}function W0(){return i0}var X0=($)=>{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}},r4=[];function U($,W){let X=W0(),J=X0({issueData:W,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,X,X===v1?void 0:v1].filter((Y)=>!!Y)});$.common.issues.push(J)}class n{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 n.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"}),S1=($)=>({status:"dirty",value:$}),d=($)=>({status:"valid",value:$}),N0=($)=>$.status==="aborted",R0=($)=>$.status==="dirty",F1=($)=>$.status==="valid",u1=($)=>typeof Promise<"u"&&$ instanceof Promise;function Q0($,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 o0($,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 l1,c1;class $1{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 d0=($,W)=>{if(F1(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 i($.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 B1($.data)}_getOrReturnCtx($,W){return W||{common:$.parent.common,data:$.data,parsedType:B1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new n,ctx:{common:$.parent.common,data:$.data,parsedType:B1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let W=this._parse($);if(u1(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:B1($)},Y=this._parseSync({data:$,path:J.path,parent:J});return d0(J,Y)}"~validate"($){var W,X;let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:B1($)};if(!this["~standard"].async)try{let Y=this._parseSync({data:$,path:[],parent:J});return F1(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)=>F1(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:B1($)},J=this._parse({data:$,path:X.path,parent:X}),Y=await(u1(J)?J:Promise.resolve(J));return d0(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 t({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 e.create(this,this._def)}nullable(){return q1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return s.create(this)}promise(){return N1.create(this,this._def)}or($){return b1.create([this,$],this._def)}and($){return P1.create(this,$,this._def)}transform($){return new t({...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 J0({typeName:S.ZodBranded,type:this,...k(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new h1({...k(this._def),innerType:this,catchValue:W,typeName:S.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return a1.create(this,$)}readonly(){return Z1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var s4=/^c[^\s-]{8,}$/i,e4=/^[0-9a-z]+$/,$9=/^[0-9A-HJKMNP-TV-Z]{26}$/i,W9=/^[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,X9=/^[a-z0-9_-]{21}$/i,Q9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Y9=/^[-+]?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)?)??$/,J9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,H9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",U0,G9=/^(?:(?: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])$/,z9=/^(?:(?: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])$/,w9=/^(([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]))$/,B9=/^(([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])$/,q9=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,V9=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,a0="((\\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])))",M9=new RegExp(`^${a0}$`);function t0($){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 O9($){return new RegExp(`^${t0($)}$`)}function r0($){let W=`${a0}T${t0($)}`,X=[];if(X.push($.local?"Z?":"Z"),$.offset)X.push("([+-]\\d{2}:?\\d{2})");return W=`${W}(${X.join("|")})`,new RegExp(`^${W}$`)}function j9($,W){if((W==="v4"||!W)&&G9.test($))return!0;if((W==="v6"||!W)&&w9.test($))return!0;return!1}function L9($,W){if(!Q9.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 F9($,W){if((W==="v4"||!W)&&z9.test($))return!0;if((W==="v6"||!W)&&B9.test($))return!0;return!1}class r 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 n,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(!J9.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(!U0)U0=new RegExp(H9,"u");if(!U0.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(!W9.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(!X9.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(!s4.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(!e4.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(!$9.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(!r0(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(!M9.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(!O9(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(!Y9.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(!j9($.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(!L9($.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(!F9($.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(!q9.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(!V9.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 r({...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 r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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 $}}r.create=($)=>{var W;return new r({checks:[],typeName:S.ZodString,coerce:(W=$===null||$===void 0?void 0:$.coerce)!==null&&W!==void 0?W:!1,...k($)})};function K9($,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 M1 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 n;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(K9($.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 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,$]})}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($)}}M1.create=($)=>{return new M1({checks:[],typeName:S.ZodNumber,coerce:($===null||$===void 0?void 0:$.coerce)||!1,...k($)})};class O1 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 n;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 O1({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:X,message:R.toString(J)}]})}_addCheck($){return new O1({...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 $}}O1.create=($)=>{var W;return new O1({checks:[],typeName:S.ZodBigInt,coerce:(W=$===null||$===void 0?void 0:$.coerce)!==null&&W!==void 0?W:!1,...k($)})};class k1 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 d($.data)}}k1.create=($)=>{return new k1({typeName:S.ZodBoolean,coerce:($===null||$===void 0?void 0:$.coerce)||!1,...k($)})};class K1 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 n,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 K1({...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}}K1.create=($)=>{return new K1({checks:[],coerce:($===null||$===void 0?void 0:$.coerce)||!1,typeName:S.ZodDate,...k($)})};class n1 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 d($.data)}}n1.create=($)=>{return new n1({typeName:S.ZodSymbol,...k($)})};class C1 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 d($.data)}}C1.create=($)=>{return new C1({typeName:S.ZodUndefined,...k($)})};class f1 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 d($.data)}}f1.create=($)=>{return new f1({typeName:S.ZodNull,...k($)})};class U1 extends C{constructor(){super(...arguments);this._any=!0}_parse($){return d($.data)}}U1.create=($)=>{return new U1({typeName:S.ZodAny,...k($)})};class V1 extends C{constructor(){super(...arguments);this._unknown=!0}_parse($){return d($.data)}}V1.create=($)=>{return new V1({typeName:S.ZodUnknown,...k($)})};class Y1 extends C{_parse($){let W=this._getOrReturnCtx($);return U(W,{code:F.invalid_type,expected:D.never,received:W.parsedType}),E}}Y1.create=($)=>{return new Y1({typeName:S.ZodNever,...k($)})};class d1 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 d($.data)}}d1.create=($)=>{return new d1({typeName:S.ZodVoid,...k($)})};class s 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 $1(W,w,W.path,B))})).then((w)=>{return n.mergeArray(X,w)});let Y=[...W.data].map((w,B)=>{return J.type._parseSync(new $1(W,w,W.path,B))});return n.mergeArray(X,Y)}get element(){return this._def.type}min($,W){return new s({...this._def,minLength:{value:$,message:R.toString(W)}})}max($,W){return new s({...this._def,maxLength:{value:$,message:R.toString(W)}})}length($,W){return new s({...this._def,exactLength:{value:$,message:R.toString(W)}})}nonempty($){return this.min(1,$)}}s.create=($,W)=>{return new s({type:$,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...k(W)})};function _1($){if($ instanceof Z){let W={};for(let X in $.shape){let J=$.shape[X];W[X]=e.create(_1(J))}return new Z({...$._def,shape:()=>W})}else if($ instanceof s)return new s({...$._def,type:_1($.element)});else if($ instanceof e)return e.create(_1($.unwrap()));else if($ instanceof q1)return q1.create(_1($.unwrap()));else if($ instanceof J1)return J1.create($.items.map((W)=>_1(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 Y1&&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 $1(J,b,J.path,j)),alwaysSet:j in J.data})}if(this._def.catchall instanceof Y1){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 $1(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,x=await N.value;j.push({key:b,value:x,alwaysSet:N.alwaysSet})}return j}).then((j)=>{return n.mergeObjectSync(X,j)});else return n.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 _1(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 e)Y=Y._def.innerType;W[X]=Y}}),new Z({...this._def,shape:()=>W})}keyof(){return s0(P.objectKeys(this.shape))}}Z.create=($,W)=>{return new Z({shape:()=>$,unknownKeys:"strip",catchall:Y1.create(),typeName:S.ZodObject,...k(W)})};Z.strictCreate=($,W)=>{return new Z({shape:()=>$,unknownKeys:"strict",catchall:Y1.create(),typeName:S.ZodObject,...k(W)})};Z.lazycreate=($,W)=>{return new Z({shape:$,unknownKeys:"strip",catchall:Y1.create(),typeName:S.ZodObject,...k(W)})};class b1 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 i(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 i(M));return U(W,{code:F.invalid_union,unionErrors:B}),E}}get options(){return this._def.options}}b1.create=($,W)=>{return new b1({options:$,typeName:S.ZodUnion,...k(W)})};var w1=($)=>{if($ instanceof I1)return w1($.schema);else if($ instanceof t)return w1($.innerType());else if($ instanceof T1)return[$.value];else if($ instanceof j1)return $.options;else if($ instanceof x1)return P.objectValues($.enum);else if($ instanceof g1)return w1($._def.innerType);else if($ instanceof C1)return[void 0];else if($ instanceof f1)return[null];else if($ instanceof e)return[void 0,...w1($.unwrap())];else if($ instanceof q1)return[null,...w1($.unwrap())];else if($ instanceof J0)return w1($.unwrap());else if($ instanceof Z1)return w1($.unwrap());else if($ instanceof h1)return w1($._def.innerType);else return[]};class Y0 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=w1(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 Y0({typeName:S.ZodDiscriminatedUnion,discriminator:$,options:W,optionsMap:J,...k(X)})}}function A0($,W){let X=B1($),J=B1(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=A0($[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=A0(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 P1 extends C{_parse($){let{status:W,ctx:X}=this._processInputParams($),J=(Y,w)=>{if(N0(Y)||N0(w))return E;let B=A0(Y.value,w.value);if(!B.valid)return U(X,{code:F.invalid_intersection_types}),E;if(R0(Y)||R0(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}))}}P1.create=($,W,X)=>{return new P1({left:$,right:W,typeName:S.ZodIntersection,...k(X)})};class J1 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 $1(X,w,X.path,B))}).filter((w)=>!!w);if(X.common.async)return Promise.all(Y).then((w)=>{return n.mergeArray(W,w)});else return n.mergeArray(W,Y)}get items(){return this._def.items}rest($){return new J1({...this._def,rest:$})}}J1.create=($,W)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new J1({items:$,typeName:S.ZodTuple,rest:null,...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.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 $1(X,B,X.path,B)),value:w._parse(new $1(X,X.data[B],X.path,B)),alwaysSet:B in X.data});if(X.common.async)return n.mergeObjectAsync(W,J);else return n.mergeObjectSync(W,J)}get element(){return this._def.valueType}static create($,W,X){if(W instanceof C)return new p1({keyType:$,valueType:W,typeName:S.ZodRecord,...k(X)});return new p1({keyType:r.create(),valueType:$,typeName:S.ZodRecord,...k(W)})}}class i1 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 $1(X,B,X.path,[j,"key"])),value:Y._parse(new $1(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}}}}i1.create=($,W,X)=>{return new i1({valueType:W,keyType:$,typeName:S.ZodMap,...k(X)})};class D1 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 $1(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 D1({...this._def,minSize:{value:$,message:R.toString(W)}})}max($,W){return new D1({...this._def,maxSize:{value:$,message:R.toString(W)}})}size($,W){return this.min($,W).max($,W)}nonempty($){return this.min(1,$)}}D1.create=($,W)=>{return new D1({valueType:$,minSize:null,maxSize:null,typeName:S.ZodSet,...k(W)})};class E1 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 X0({data:B,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,W0(),v1].filter((j)=>!!j),issueData:{code:F.invalid_arguments,argumentsError:M}})}function J(B,M){return X0({data:B,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,W0(),v1].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 N1){let B=this;return d(async function(...M){let j=new i([]),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 d(function(...M){let j=B._def.args.safeParse(M,Y);if(!j.success)throw new i([X(M,j.error)]);let N=Reflect.apply(w,this,j.data),b=B._def.returns.safeParse(N,Y);if(!b.success)throw new i([J(N,b.error)]);return b.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new E1({...this._def,args:J1.create($).rest(V1.create())})}returns($){return new E1({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,W,X){return new E1({args:$?$:J1.create([]).rest(V1.create()),returns:W||V1.create(),typeName:S.ZodFunction,...k(X)})}}class I1 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})}}I1.create=($,W)=>{return new I1({getter:$,typeName:S.ZodLazy,...k(W)})};class T1 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}}T1.create=($,W)=>{return new T1({value:$,typeName:S.ZodLiteral,...k(W)})};function s0($,W){return new j1({values:$,typeName:S.ZodEnum,...k(W)})}class j1 extends C{constructor(){super(...arguments);l1.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(!Q0(this,l1,"f"))o0(this,l1,new Set(this._def.values),"f");if(!Q0(this,l1,"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 d($.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 j1.create($,{...this._def,...W})}exclude($,W=this._def){return j1.create(this.options.filter((X)=>!$.includes(X)),{...this._def,...W})}}l1=new WeakMap;j1.create=s0;class x1 extends C{constructor(){super(...arguments);c1.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(!Q0(this,c1,"f"))o0(this,c1,new Set(P.getValidEnumValues(this._def.values)),"f");if(!Q0(this,c1,"f").has($.data)){let J=P.objectValues(W);return U(X,{received:X.data,code:F.invalid_enum_value,options:J}),E}return d($.data)}get enum(){return this._def.values}}c1=new WeakMap;x1.create=($,W)=>{return new x1({values:$,typeName:S.ZodNativeEnum,...k(W)})};class N1 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 d(X.then((J)=>{return this._def.type.parseAsync(J,{path:W.path,errorMap:W.common.contextualErrorMap})}))}}N1.create=($,W)=>{return new N1({type:$,typeName:S.ZodPromise,...k(W)})};class t 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 S1(M.value);if(W.value==="dirty")return S1(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 S1(B.value);if(W.value==="dirty")return S1(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(!F1(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(!F1(w))return w;return Promise.resolve(J.transform(w.value,Y)).then((B)=>({status:W.value,value:B}))});P.assertNever(J)}}t.create=($,W,X)=>{return new t({schema:$,typeName:S.ZodEffects,effect:W,...k(X)})};t.createWithPreprocess=($,W,X)=>{return new t({schema:W,effect:{type:"preprocess",transform:$},typeName:S.ZodEffects,...k(X)})};class e extends C{_parse($){if(this._getType($)===D.undefined)return d(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}e.create=($,W)=>{return new e({innerType:$,typeName:S.ZodOptional,...k(W)})};class q1 extends C{_parse($){if(this._getType($)===D.null)return d(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}q1.create=($,W)=>{return new q1({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 h1 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(u1(J))return J.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new i(X.common.issues)},input:X.data})}});else return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new i(X.common.issues)},input:X.data})}}removeCatch(){return this._def.innerType}}h1.create=($,W)=>{return new h1({innerType:$,typeName:S.ZodCatch,catchValue:typeof W.catch==="function"?W.catch:()=>W.catch,...k(W)})};class o1 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}}}o1.create=($)=>{return new o1({typeName:S.ZodNaN,...k($)})};var U9=Symbol("zod_brand");class J0 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 a1 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(),S1(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 a1({in:$,out:W,typeName:S.ZodPipeline})}}class Z1 extends C{_parse($){let W=this._def.innerType._parse($),X=(J)=>{if(F1(J))J.value=Object.freeze(J.value);return J};return u1(W)?W.then((J)=>X(J)):X(W)}unwrap(){return this._def.innerType}}Z1.create=($,W)=>{return new Z1({innerType:$,typeName:S.ZodReadonly,...k(W)})};function e0($,W={},X){if($)return U1.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 U1.create()}var D9={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 N9=($,W={message:`Input not instance of ${$.name}`})=>e0((X)=>X instanceof $,W),$4=r.create,W4=M1.create,R9=o1.create,A9=O1.create,X4=k1.create,_9=K1.create,S9=n1.create,E9=C1.create,v9=f1.create,k9=U1.create,C9=V1.create,f9=Y1.create,b9=d1.create,P9=s.create,I9=Z.create,T9=Z.strictCreate,x9=b1.create,g9=Y0.create,h9=P1.create,Z9=J1.create,m9=p1.create,y9=i1.create,l9=D1.create,c9=E1.create,u9=I1.create,n9=T1.create,d9=j1.create,p9=x1.create,i9=N1.create,p0=t.create,o9=e.create,a9=q1.create,t9=t.createWithPreprocess,r9=a1.create,s9=()=>$4().optional(),e9=()=>W4().optional(),$2=()=>X4().optional(),W2={string:($)=>r.create({...$,coerce:!0}),number:($)=>M1.create({...$,coerce:!0}),boolean:($)=>k1.create({...$,coerce:!0}),bigint:($)=>O1.create({...$,coerce:!0}),date:($)=>K1.create({...$,coerce:!0})},X2=E,G=Object.freeze({__proto__:null,defaultErrorMap:v1,setErrorMap:t4,getErrorMap:W0,makeIssue:X0,EMPTY_PATH:r4,addIssueToContext:U,ParseStatus:n,INVALID:E,DIRTY:S1,OK:d,isAborted:N0,isDirty:R0,isValid:F1,isAsync:u1,get util(){return P},get objectUtil(){return D0},ZodParsedType:D,getParsedType:B1,ZodType:C,datetimeRegex:r0,ZodString:r,ZodNumber:M1,ZodBigInt:O1,ZodBoolean:k1,ZodDate:K1,ZodSymbol:n1,ZodUndefined:C1,ZodNull:f1,ZodAny:U1,ZodUnknown:V1,ZodNever:Y1,ZodVoid:d1,ZodArray:s,ZodObject:Z,ZodUnion:b1,ZodDiscriminatedUnion:Y0,ZodIntersection:P1,ZodTuple:J1,ZodRecord:p1,ZodMap:i1,ZodSet:D1,ZodFunction:E1,ZodLazy:I1,ZodLiteral:T1,ZodEnum:j1,ZodNativeEnum:x1,ZodPromise:N1,ZodEffects:t,ZodTransformer:t,ZodOptional:e,ZodNullable:q1,ZodDefault:g1,ZodCatch:h1,ZodNaN:o1,BRAND:U9,ZodBranded:J0,ZodPipeline:a1,ZodReadonly:Z1,custom:e0,Schema:C,ZodSchema:C,late:D9,get ZodFirstPartyTypeKind(){return S},coerce:W2,any:k9,array:P9,bigint:A9,boolean:X4,date:_9,discriminatedUnion:g9,effect:p0,enum:d9,function:c9,instanceof:N9,intersection:h9,lazy:u9,literal:n9,map:y9,nan:R9,nativeEnum:p9,never:f9,null:v9,nullable:a9,number:W4,object:I9,oboolean:$2,onumber:e9,optional:o9,ostring:s9,pipeline:r9,preprocess:t9,promise:i9,record:m9,set:l9,strictObject:T9,string:$4,symbol:S9,transformer:p0,tuple:Z9,undefined:E9,union:x9,unknown:C9,void:b9,NEVER:X2,ZodIssueCode:F,quotelessJson:a4,ZodError:i});var _0="2024-11-05",Q4=[_0,"2024-10-07"],H0="2.0",Y4=G.union([G.string(),G.number().int()]),J4=G.string(),W1=G.object({_meta:G.optional(G.object({progressToken:G.optional(Y4)}).passthrough())}).passthrough(),o=G.object({method:G.string(),params:G.optional(W1)}),t1=G.object({_meta:G.optional(G.object({}).passthrough())}).passthrough(),H1=G.object({method:G.string(),params:G.optional(t1)}),X1=G.object({_meta:G.optional(G.object({}).passthrough())}).passthrough(),G0=G.union([G.string(),G.number().int()]),Q2=G.object({jsonrpc:G.literal(H0),id:G0}).merge(o).strict(),Y2=G.object({jsonrpc:G.literal(H0)}).merge(H1).strict(),J2=G.object({jsonrpc:G.literal(H0),id:G0,result:X1}).strict(),R1;(function($){$[$.ConnectionClosed=-1]="ConnectionClosed",$[$.RequestTimeout=-2]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError"})(R1||(R1={}));var H2=G.object({jsonrpc:G.literal(H0),id:G0,error:G.object({code:G.number().int(),message:G.string(),data:G.optional(G.unknown())})}).strict(),H4=G.union([Q2,Y2,J2,H2]),z0=X1.strict(),w0=H1.extend({method:G.literal("notifications/cancelled"),params:t1.extend({requestId:G0,reason:G.string().optional()})}),G4=G.object({name:G.string(),version:G.string()}).passthrough(),G2=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(),S0=o.extend({method:G.literal("initialize"),params:W1.extend({protocolVersion:G.string(),capabilities:G2,clientInfo:G4})}),z2=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(),w2=X1.extend({protocolVersion:G.string(),capabilities:z2,serverInfo:G4}),E0=H1.extend({method:G.literal("notifications/initialized")}),B0=o.extend({method:G.literal("ping")}),B2=G.object({progress:G.number(),total:G.optional(G.number())}).passthrough(),q0=H1.extend({method:G.literal("notifications/progress"),params:t1.merge(B2).extend({progressToken:Y4})}),V0=o.extend({params:W1.extend({cursor:G.optional(J4)}).optional()}),M0=X1.extend({nextCursor:G.optional(J4)}),z4=G.object({uri:G.string(),mimeType:G.optional(G.string())}).passthrough(),w4=z4.extend({text:G.string()}),B4=z4.extend({blob:G.string().base64()}),q2=G.object({uri:G.string(),name:G.string(),description:G.optional(G.string()),mimeType:G.optional(G.string())}).passthrough(),V2=G.object({uriTemplate:G.string(),name:G.string(),description:G.optional(G.string()),mimeType:G.optional(G.string())}).passthrough(),M2=V0.extend({method:G.literal("resources/list")}),O2=M0.extend({resources:G.array(q2)}),j2=V0.extend({method:G.literal("resources/templates/list")}),L2=M0.extend({resourceTemplates:G.array(V2)}),F2=o.extend({method:G.literal("resources/read"),params:W1.extend({uri:G.string()})}),K2=X1.extend({contents:G.array(G.union([w4,B4]))}),U2=H1.extend({method:G.literal("notifications/resources/list_changed")}),D2=o.extend({method:G.literal("resources/subscribe"),params:W1.extend({uri:G.string()})}),N2=o.extend({method:G.literal("resources/unsubscribe"),params:W1.extend({uri:G.string()})}),R2=H1.extend({method:G.literal("notifications/resources/updated"),params:t1.extend({uri:G.string()})}),A2=G.object({name:G.string(),description:G.optional(G.string()),required:G.optional(G.boolean())}).passthrough(),_2=G.object({name:G.string(),description:G.optional(G.string()),arguments:G.optional(G.array(A2))}).passthrough(),S2=V0.extend({method:G.literal("prompts/list")}),E2=M0.extend({prompts:G.array(_2)}),v2=o.extend({method:G.literal("prompts/get"),params:W1.extend({name:G.string(),arguments:G.optional(G.record(G.string()))})}),O0=G.object({type:G.literal("text"),text:G.string()}).passthrough(),j0=G.object({type:G.literal("image"),data:G.string().base64(),mimeType:G.string()}).passthrough(),q4=G.object({type:G.literal("resource"),resource:G.union([w4,B4])}).passthrough(),k2=G.object({role:G.enum(["user","assistant"]),content:G.union([O0,j0,q4])}).passthrough(),C2=X1.extend({description:G.optional(G.string()),messages:G.array(k2)}),f2=H1.extend({method:G.literal("notifications/prompts/list_changed")}),b2=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(),v0=V0.extend({method:G.literal("tools/list")}),P2=M0.extend({tools:G.array(b2)}),V4=X1.extend({content:G.array(G.union([O0,j0,q4])),isError:G.boolean().default(!1).optional()}),d6=V4.or(X1.extend({toolResult:G.unknown()})),k0=o.extend({method:G.literal("tools/call"),params:W1.extend({name:G.string(),arguments:G.optional(G.record(G.unknown()))})}),I2=H1.extend({method:G.literal("notifications/tools/list_changed")}),M4=G.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),T2=o.extend({method:G.literal("logging/setLevel"),params:W1.extend({level:M4})}),x2=H1.extend({method:G.literal("notifications/message"),params:t1.extend({level:M4,logger:G.optional(G.string()),data:G.unknown()})}),g2=G.object({name:G.string().optional()}).passthrough(),h2=G.object({hints:G.optional(G.array(g2)),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(),Z2=G.object({role:G.enum(["user","assistant"]),content:G.union([O0,j0])}).passthrough(),m2=o.extend({method:G.literal("sampling/createMessage"),params:W1.extend({messages:G.array(Z2),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(h2)})}),C0=X1.extend({model:G.string(),stopReason:G.optional(G.enum(["endTurn","stopSequence","maxTokens"]).or(G.string())),role:G.enum(["user","assistant"]),content:G.discriminatedUnion("type",[O0,j0])}),y2=G.object({type:G.literal("ref/resource"),uri:G.string()}).passthrough(),l2=G.object({type:G.literal("ref/prompt"),name:G.string()}).passthrough(),c2=o.extend({method:G.literal("completion/complete"),params:W1.extend({ref:G.union([l2,y2]),argument:G.object({name:G.string(),value:G.string()}).passthrough()})}),u2=X1.extend({completion:G.object({values:G.array(G.string()).max(100),total:G.optional(G.number().int()),hasMore:G.optional(G.boolean())}).passthrough()}),n2=G.object({uri:G.string().startsWith("file://"),name:G.optional(G.string())}).passthrough(),d2=o.extend({method:G.literal("roots/list")}),f0=X1.extend({roots:G.array(n2)}),p2=H1.extend({method:G.literal("notifications/roots/list_changed")}),p6=G.union([B0,S0,c2,T2,v2,S2,M2,j2,F2,D2,N2,k0,v0]),i6=G.union([w0,q0,E0,p2]),o6=G.union([z0,C0,f0]),a6=G.union([B0,m2,d2]),t6=G.union([w0,q0,x2,R2,U2,I2,f2]),r6=G.union([z0,w2,u2,C2,E2,O2,L2,K2,V4,P2]);class r1 extends Error{constructor($,W,X){super(`MCP error ${$}: ${W}`);this.code=$,this.data=X}}var i2=60000;class b0{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(w0,(W)=>{let X=this._requestHandlerAbortControllers.get(W.params.requestId);X===null||X===void 0||X.abort(W.params.reason)}),this.setNotificationHandler(q0,(W)=>{this._onprogress(W)}),this.setRequestHandler(B0,(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 r1(R1.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:R1.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:R1.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 r1($.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 x=void 0;this._responseHandlers.set(N,(y)=>{var A;if(x!==void 0)clearTimeout(x);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 h=W.parse(y.result);J(h)}catch(h){Y(h)}});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((h)=>this._onerror(Error(`Failed to send cancellation: ${h}`))),Y(y)};(M=X===null||X===void 0?void 0:X.signal)===null||M===void 0||M.addEventListener("abort",()=>{var y;if(x!==void 0)clearTimeout(x);m((y=X===null||X===void 0?void 0:X.signal)===null||y===void 0?void 0:y.reason)});let Q1=(j=X===null||X===void 0?void 0:X.timeout)!==null&&j!==void 0?j:i2;x=setTimeout(()=>m(new r1(R1.RequestTimeout,"Request timed out",{timeout:Q1})),Q1),this._transport.send(b).catch((y)=>{if(x!==void 0)clearTimeout(x);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 P0 extends b0{constructor($,W){super(W);this._serverInfo=$,this._capabilities=W.capabilities,this.setRequestHandler(S0,(X)=>this._oninitialize(X)),this.setNotificationHandler(E0,()=>{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:Q4.includes(W)?W:_0,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"},z0)}async createMessage($,W){return this.request({method:"sampling/createMessage",params:$},C0,W)}async listRoots($,W){return this.request({method:"roots/list",params:$},f0,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 j4 from"process";class I0{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),o2(W)}clear(){this._buffer=void 0}}function o2($){return H4.parse(JSON.parse($))}function O4($){return JSON.stringify($)+`
|
|
4
|
+
`}class T0{constructor($=j4.stdin,W=j4.stdout){this._stdin=$,this._stdout=W,this._readBuffer=new I0,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=O4($);if(this._stdout.write(X))W();else this._stdout.once("drain",W)})}}var a2=await Promise.resolve().then(() => l0(K0(),1)),L4=a2.version;async function F4($){let W=new P0({name:"typescape",version:L4},{capabilities:{tools:{}}});W.setRequestHandler(v0,async()=>{return{tools:$.getTools().map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}))}}),W.setRequestHandler(k0,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 T0;await W.connect(X),console.error(`Typescape MCP server v${L4} started`)}var x0=["file","doc","pr","custom"],t2=new Set(x0),r2=1e7,N4=/^[A-Za-z0-9+/]*={0,2}$/,K4="inline_assets_enabled",s2={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"]},e2={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"]},$6={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"]},W6={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:[]},X6={type:"object",properties:{session_id:{type:"string",description:"Session ID to retrieve (e.g., sess_01HXYZ...)"}},required:["session_id"]},Q6={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"]},Y6={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"]},J6={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 L0($){if(!$||typeof $!=="object"||Array.isArray($))return{};let W=$,X=W.data;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return W}function U4($){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 D4($,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 H6($,W){if($===void 0||$===null)return{assets:{}};let X={};if(Array.isArray($)){for(let[Y,w]of $.entries()){let B=D4(w,W),M=U4(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)?D4(w,B):B,j=U4(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 G6($){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 R4($){let W=$.replace(/\s+/g,"");if(W.length===0)return new Uint8Array;if(W.length%4!==0||!N4.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 z6($){if($.code!=="feature_disabled")return!1;let W=$.details?.feature;if(typeof W==="string"&&W.toLowerCase()===K4)return!0;return`${$.message} ${$.fixHint??""}`.toLowerCase().includes(K4)}function w6($){let X=$.replace(/\\/g,"/").split("/"),J=X[X.length-1];return J&&J.length>0?J:"asset.bin"}async function B6($,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=R4(N);if(b===null)throw new q(422,"invalid_argument",`Invalid base64 content for asset: ${j}`,"local");w.append(j,new Blob([b]),w6(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 q6($){if($==="approver")return["read","comment","approve"];if($==="observer")return["read"];if($==="owner")return["read","comment","approve","admin"];return["read","comment"]}function V6($){return $.map((W)=>{let X=W.scopes&&W.scopes.length>0?[...new Set(W.scopes)]:q6(W.role);return{email:W.email,...W.name?{name:W.name}:{},role:W.role,scopes:X}})}function M6($,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}function O6($){if(!Array.isArray($))return[];let W=new Set,X=[];for(let J of $){if(typeof J!=="string")continue;let Y=J.trim().toLowerCase();if(Y.length===0)continue;if(W.has(Y))continue;W.add(Y),X.push(Y)}return X}function j6($){if(!$||typeof $!=="object"||Array.isArray($))return null;let W=$.id;return typeof W==="string"&&W.length>0?W:null}var L6={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"]},F6={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"]},K6={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:x0,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"]},U6={type:"object",properties:{review_ref_id:{type:"string",description:"Review ref ID to resolve"}},required:["review_ref_id"]},D6={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"]},N6={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"]},R6={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"]},A6={type:"object",properties:{session_id:{type:"string",description:"Session ID to run checks against"}},required:["session_id"]},_6={type:"object",properties:{},additionalProperties:!1},S6={type:"object",properties:{},additionalProperties:!1},E6={type:"object",properties:{},additionalProperties:!1},v6={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"]},k6={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"]},C6={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"]},f6={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"]},b6={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"]},P6={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"]},I6={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"]},T6={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 A4($,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:s2};$.register(X,async(O)=>{let Q=O,H=H6(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,a=!!Q.content_body,p=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 A1=Q.document_type==="image_set",y1=Q.document_type==="pdf";if(A1){if(!p&&!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 T=new Set([".png",".jpg",".jpeg",".webp",".gif",".svg"]);if(p){for(let u of Object.keys(z)){let c=u.slice(u.lastIndexOf(".")).toLowerCase();if(!T.has(c))return V(new q(422,"unsupported_media_type",`Unsupported image format for image_set: ${u}. Supported extensions: ${[...T].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(y1){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(a)return V(new q(422,"invalid_argument",'document_type "pdf" does not support content_body; provide inline_assets with one .pdf file.',"local"));if(!p&&!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(p&&g)return V(new q(422,"invalid_argument",'document_type "pdf" cannot mix inline_assets and upload-batch inputs.',"local"));if(p&&Object.keys(z).length!==1)return V(new q(422,"invalid_argument",'document_type "pdf" requires exactly one inline asset.',"local"));if(p){let[T]=Object.keys(z);if(!T)return V(new q(400,"missing_param",'document_type "pdf" requires inline_assets with exactly one .pdf file.',"local"));if(T.slice(T.lastIndexOf(".")).toLowerCase()!==".pdf")return V(new q(422,"unsupported_media_type",`Unsupported PDF format: ${T}. Supported extension: .pdf`,"local"));if(Q.file_path!==T)return V(new q(422,"invalid_argument",`For document_type "pdf", file_path must match inline_assets key: ${T}`,"local"))}}let g0=[I,a,g].filter(Boolean).length;if(!A1&&!y1&&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(!A1&&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(!a&&!A1&&!y1)return V(new q(422,"invalid_argument","inline_assets requires content_body (inline mode)","local"));let T=0;for(let[u,c]of Object.entries(z)){let L1=G6(u);if(L1)return V(new q(422,"invalid_argument",`${L1}: ${u}`,"local"));let z1=R4(c);if(z1===null)return V(new q(422,"invalid_argument",`Invalid base64 content for asset: ${u}`,"local"));T+=z1.byteLength}if(T>r2)return V(new q(413,"inline_payload_too_large",`Total decoded inline assets (${T} 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(a)l.content_body=Q.content_body;if(Object.keys(z).length>0)l.inline_assets=z;let h0=M6(Q.participants,Q.reviewer_emails);if(h0.length>0)l.participants=V6(h0);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(y1)l.filename=Q.file_path;if(A1){let T=Q.filenames&&Q.filenames.length>0?Q.filenames:Object.keys(z).sort();l.filenames=T}let s1={};if(Q.idempotency_key)s1["Idempotency-Key"]=Q.idempotency_key;if(Q.expected_version)s1["If-Match"]=Q.expected_version;let Z0=O6(Q.reviewer_emails),m0=async(T)=>{if(Z0.length===0||T.invitations.length>0)return{invitations:T.invitations};let u=j6(T.session);if(!u)return{invitations:T.invitations,warning:{code:"missing_session_id",message:"Session created but MCP could not extract session.id to invite reviewer_emails."}};try{let c=await W.post(`/sessions/${encodeURIComponent(u)}/participants`,{body:{participants:Z0.map((z1)=>({email:z1,role:"reviewer"}))}}),L1=Array.isArray(c.body.invitations)?c.body.invitations:[];if(L1.length>0)return{invitations:L1};return{invitations:T.invitations,warning:{code:"reviewer_emails_no_invitations",message:"Session created, but reviewer_emails follow-up invite returned no invitations.",request_id:c.requestId}}}catch(c){if(c instanceof q)return{invitations:T.invitations,warning:{code:"reviewer_emails_invite_failed",message:"Session created, but reviewer_emails follow-up invite failed.",request_id:c.requestId}};throw c}};try{let T=await W.post("/sessions",{body:l,headers:s1}),u=await m0({session:T.body.session,invitations:T.body.invitations??[]});return v({session:T.body.session,invitations:u.invitations,...u.warning?{warnings:[u.warning]}:{}},T.requestId)}catch(T){if(T instanceof q){if(p&&!g&&!I&&!a&&(A1||y1)&&z6(T))try{let{projectId:c,uploadBatchId:L1}=await B6(W,z,Q.title),z1={...l};delete z1.inline_assets,z1.project_id=c,z1.upload_batch_id=L1;let e1=await W.post("/sessions",{body:z1,headers:s1}),F0=await m0({session:e1.body.session,invitations:e1.body.invitations??[]});return v({session:e1.body.session,invitations:F0.invitations,...F0.warning?{warnings:[F0.warning]}:{}},e1.requestId)}catch(c){if(c instanceof q)return V(c);throw c}return V(T)}throw T}});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:e2};$.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:$6};$.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:W6};$.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:X6};$.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:Q6},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 x={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:Y6};$.register(x,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:J6};$.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: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.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:k6},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:C6},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:f6},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:b6},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:P6},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.body=Q.body_md,z.text=Q.body_md;else if(Q.note_md!==void 0)z.body=Q.note_md,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 Q1=null,y=300000;async function A(){let O=Date.now();if(Q1&&O-Q1.fetchedAt<y)return Q1.features;try{return Q1={features:(await W.get("/me/capabilities")).body.features??{},fetchedAt:O},Q1.features}catch(Q){if(Q instanceof q)throw Q;throw Q}}function h(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:L6},async(O)=>{let Q=O;try{if(!(await A()).review_sets)return h("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:F6},async(O)=>{let Q=O;try{if(!(await A()).review_sets)return h("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:K6},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(!t2.has(H))return V(new q(400,"invalid_param",`Invalid parameter: kind must be one of ${x0.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:U6},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:D6},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: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.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:R6},async(O)=>{let Q=O;try{if(!(await A()).policy)return h("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:A6},async(O)=>{let Q=O;try{if(!(await A()).checks)return h("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:_6},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:S6},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:E6},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 G1={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:G1},async(O)=>{let Q=O;try{if(!(await A()).corpus_snapshots)return h("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 m1={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:m1},async(O)=>{let Q=O;try{if(!(await A()).corpus_snapshots)return h("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 S4={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:S4},async(O)=>{let Q=O;try{if(!(await A()).corpus_snapshots)return h("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 E4={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:E4},async(O)=>{let Q=O;try{if(!(await A()).steering)return h("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),a=await W.get(g),p={...L0(a.body)};if(L==="prompt_fragment"&&p.prompt_fragment)p.non_authoritative=!0;return v(p,a.requestId)}catch(I){if(I instanceof q&&L==="structured"&&I.status===422&&I.code==="invalid_argument")try{let g=f(_("prompt_fragment.v1")),a=await W.get(g),p={...L0(a.body),steering_version:"v1",rules:[],non_authoritative:!0,format_fallback:"prompt_fragment"};return v(p,a.requestId)}catch(g){if(g instanceof q)return V(g);throw g}if(I instanceof q)return V(I);throw I}});let v4={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:v4},async(O)=>{let Q=O;try{if(!(await A()).steering)return h("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(L0(K.body),K.requestId)}catch(z){if(z instanceof q)return V(z);throw z}});let k4={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:k4},async(O)=>{let Q=O;try{if(!(await A()).steering)return h("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 C4={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:C4},async(O)=>{let Q=O;try{if(!(await A()).steering)return h("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 f4={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:f4},async(O)=>{let Q=O;try{if(!(await A()).steering)return h("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,L0(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 b4={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:b4},async(O)=>{let Q=O;try{if(!(await A()).steering)return h("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 P4={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:P4},async(O)=>{let Q=O;try{if(!(await A()).steering)return h("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 I4={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(I4,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 T4={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(T4,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 x4={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(x4,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 g4=5242880,h4=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Z4={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(Z4,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(!h4.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(!N4.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>g4){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.${x6(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:I6},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 h("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:T6},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 h("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 x6($){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 _4={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 g6(){let $=process.env.TYPESCAPE_API_KEY,W=process.env.TYPESCAPE_BASE_URL,X=[];if(!$)X.push(`TYPESCAPE_API_KEY: ${_4.TYPESCAPE_API_KEY}`);if(!W)X.push(`TYPESCAPE_BASE_URL: ${_4.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 h6($,W=$0){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 Z6(){let{apiKey:$,baseUrl:W}=g6(),X=process.env.TYPESCAPE_TIMEOUT_MS,J=h6(X,$0),Y=J.timeoutMs;if(J.warning)console.warn(J.warning);let w=n0(W,$,Y),B=c0();A4(B,w),await F4(B)}if(import.meta.main)Z6().catch(($)=>{console.error("Fatal error:",$ instanceof Error?$.message:String($)),process.exit(1)});export{h6 as resolveTimeoutMs};
|