mcp-use 2.12.0 → 2.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,46 +1,39 @@
1
- var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})};var __create,__defProp2,__getOwnPropDesc,__getOwnPropNames2,__getProtoOf,__hasOwnProp,__commonJSMin,__exportAll,__copyProps,__toESM,init_chunk_Br0eD_fh=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs"(){"use strict";__create=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports),__exportAll=(all,symbols)=>{let target={};for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0});return symbols&&__defProp2(target,Symbol.toStringTag,{value:"Module"}),target},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(var keys2=__getOwnPropNames2(from),i=0,n=keys2.length,key;i<n;i++)key=keys2[i],!__hasOwnProp.call(to,key)&&key!==except&&__defProp2(to,key,{get:(k=>from[k]).bind(null,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp2(target,"default",{value:mod,enumerable:!0}):target,mod))}});function declares2019Dialect($schema){return typeof $schema=="string"&&DRAFT_2019_09_URIS.has($schema.replace(/#$/,""))}function declaredDialect(schema2,remedy){if(!("$schema"in schema2)||typeof schema2.$schema!="string")return"2020-12";let declared=schema2.$schema.replace(/#$/,"");if(DRAFT_2020_12_URIS.has(declared))return"2020-12";if(DRAFT_2019_09_URIS.has(declared))return"2019-09";if(DRAFT_07_URIS.has(declared)||DRAFT_06_URIS.has(declared))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema2.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`)}var DRAFT_2020_12_URIS,DRAFT_2019_09_URIS,DRAFT_07_URIS,DRAFT_06_URIS,init_dialects_DoSzNhcb=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs"(){"use strict";DRAFT_2020_12_URIS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),DRAFT_2019_09_URIS=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),DRAFT_07_URIS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),DRAFT_06_URIS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])}});function $constructor(name,initializer3,params){function init(inst,def){if(inst._zod||Object.defineProperty(inst,"_zod",{value:{def,constr:_,traits:new Set},enumerable:!1}),inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer3(inst,def);let proto=_.prototype,keys2=Object.keys(proto);for(let i=0;i<keys2.length;i++){let k=keys2[i];k in inst||(inst[k]=proto[k].bind(inst))}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a3;let inst=params?.Parent?new Definition:this;init(inst,def),(_a3=inst._zod).deferred??(_a3.deferred=[]);for(let fn of inst._zod.deferred)fn();return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_,"name",{value:name}),_}function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}var _a,NEVER,$ZodAsyncError,$ZodEncodeError,globalConfig,init_core=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js"(){"use strict";NEVER=Object.freeze({status:"aborted"});$ZodAsyncError=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}};(_a=globalThis).__zod_globalConfig??(_a.__zod_globalConfig={});globalConfig=globalThis.__zod_globalConfig}});var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_){}function getEnumValues(entries){let numericValues=Object.values(entries).filter(v=>typeof v=="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function joinValues(array4,separator="|"){return array4.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw new Error("cached value already set")}}}function nullish(input){return input==null}function cleanRegex(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){let ratio=val/step,roundedRatio=Math.round(ratio),tolerance=Number.EPSILON*Math.max(Math.abs(ratio),1);return Math.abs(ratio-roundedRatio)<tolerance?0:ratio-roundedRatio}function defineLazy(object5,key,getter){let value;Object.defineProperty(object5,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v){Object.defineProperty(object5,key,{value:v})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema2){return mergeDefs(schema2._zod.def)}function getElementAtPath(obj,path){return path?path.reduce((acc,key)=>acc?.[key],obj):obj}function promiseAllObject(promisesObj){let keys2=Object.keys(promisesObj),promises=keys2.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{let resolvedObj={};for(let i=0;i<keys2.length;i++)resolvedObj[keys2[i]]=results[i];return resolvedObj})}function randomString(length=10){let chars="abcdefghijklmnopqrstuvwxyz",str="";for(let i=0;i<length;i++)str+=chars[Math.floor(Math.random()*chars.length)];return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject(data){return typeof data=="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;let prot=ctor.prototype;return!(isObject(prot)===!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function numKeys(data){let keyCount=0;for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&keyCount++;return keyCount}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){return typeof value=="bigint"?value.toString()+"n":typeof value=="string"?`"${value}"`:`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k=>shape[k]._zod.optin==="optional"&&shape[k]._zod.optout==="optional")}function pick(schema2,mask){let currDef=schema2._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let def=mergeDefs(schema2._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(newShape[key]=currDef.shape[key])}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema2,def)}function omit(schema2,mask){let currDef=schema2._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let def=mergeDefs(schema2._zod.def,{get shape(){let newShape={...schema2._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&delete newShape[key]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema2,def)}function extend(schema2,shape){if(!isPlainObject(shape))throw new Error("Invalid input to extend: expected a plain object");let checks=schema2._zod.def.checks;if(checks&&checks.length>0){let existingShape=schema2._zod.def.shape;for(let key in shape)if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let def=mergeDefs(schema2._zod.def,{get shape(){let _shape={...schema2._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema2,def)}function safeExtend(schema2,shape){if(!isPlainObject(shape))throw new Error("Invalid input to safeExtend: expected a plain object");let def=mergeDefs(schema2._zod.def,{get shape(){let _shape={...schema2._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema2,def)}function merge(a,b){if(a._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let def=mergeDefs(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema2,mask){let checks=schema2._zod.def.checks;if(checks&&checks.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let def=mergeDefs(schema2._zod.def,{get shape(){let oldShape=schema2._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key])}else for(let key in oldShape)shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema2,def)}function required(Class2,schema2,mask){let def=mergeDefs(schema2._zod.def,{get shape(){let oldShape=schema2._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]}))}else for(let key in oldShape)shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]});return assignProp(this,"shape",shape),shape}});return clone(schema2,def)}function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function explicitlyAborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue===!1)return!0;return!1}function prefixIssues(path,issues){return issues.map(iss=>{var _a3;return(_a3=iss).path??(_a3.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message=="string"?message:message?.message}function finalizeIssue(iss,ctx,config2){let message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input",{inst:_inst,continue:_continue,input:_input,...rest}=iss;return rest.path??(rest.path=[]),rest.message=message,ctx?.reportInput&&(rest.input=_input),rest}function getSizableOrigin(input){return input instanceof Set?"set":input instanceof Map?"map":input instanceof File?"file":"unknown"}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args){let[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>Number.isNaN(Number.parseInt(k,10))).map(el=>el[1])}function base64ToUint8Array(base642){let binaryString=atob(base642),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array(base64url2){let base642=base64url2.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base642.length%4)%4);return base64ToUint8Array(base642+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex){let cleanHex=hex.replace(/^0x/,"");if(cleanHex.length%2!==0)throw new Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b=>b.toString(16).padStart(2,"0")).join("")}var EVALUATING,captureStackTrace,allowsEval,getParsedType,propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES,Class,init_util=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js"(){"use strict";init_core();EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let F=Function;return new F(""),!0}catch{return!1}});getParsedType=data=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(data)?"array":data===null?"null":data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?"promise":typeof Map<"u"&&data instanceof Map?"map":typeof Set<"u"&&data instanceof Set?"set":typeof Date<"u"&&data instanceof Date?"date":typeof File<"u"&&data instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Class=class{constructor(..._args){}}}});function flattenError(error3,mapper=issue2=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error3.issues)sub.path.length>0?(fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub))):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error3,mapper=issue2=>issue2.message){let fieldErrors={_errors:[]},processError=(error4,path=[])=>{for(let issue2 of error4.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path,...issue2.path]);else{let fullpath=[...path,...issue2.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;for(;i<fullpath.length;){let el=fullpath[i];i===fullpath.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue2))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}}};return processError(error3),fieldErrors}var initializer,$ZodError,$ZodRealError,init_errors=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js"(){"use strict";init_core();init_util();initializer=(inst,def)=>{inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,{Parent:Error})}});var _parse,_parseAsync,_safeParse,safeParse,_safeParseAsync,safeParseAsync,_encode,_decode,_encodeAsync,_decodeAsync,_safeEncode,_safeDecode,_safeEncodeAsync,_safeDecodeAsync,init_parse=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js"(){"use strict";init_core();init_errors();init_util();_parse=_Err=>(schema2,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee),e}return result.value},_parseAsync=_Err=>async(schema2,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){let e=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee),e}return result.value},_safeParse=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?{success:!1,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParse=_safeParse($ZodRealError),_safeParseAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema2._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?{success:!1,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParseAsync=_safeParseAsync($ZodRealError),_encode=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parse(_Err)(schema2,value,ctx)},_decode=_Err=>(schema2,value,_ctx)=>_parse(_Err)(schema2,value,_ctx),_encodeAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parseAsync(_Err)(schema2,value,ctx)},_decodeAsync=_Err=>async(schema2,value,_ctx)=>_parseAsync(_Err)(schema2,value,_ctx),_safeEncode=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema2,value,ctx)},_safeDecode=_Err=>(schema2,value,_ctx)=>_safeParse(_Err)(schema2,value,_ctx),_safeEncodeAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema2,value,ctx)},_safeDecodeAsync=_Err=>async(schema2,value,_ctx)=>_safeParseAsync(_Err)(schema2,value,_ctx)}});function emoji(){return new RegExp(_emoji,"u")}function timeSource(args){let hhmm="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof args.precision=="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){let time3=timeSource({precision:args.precision}),opts=["Z"];args.local&&opts.push(""),args.offset&&opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let timeRegex=`${time3}(?:${opts.join("|")})`;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}var cuid,cuid2,ulid,xid,ksuid,nanoid,duration,guid,uuid,email,_emoji,ipv4,ipv6,cidrv4,cidrv6,base64,base64url,httpProtocol,e164,dateSource,date,string,bigint,integer,number,boolean,_null,lowercase,uppercase,init_regexes=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js"(){"use strict";cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version2=>version2?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,cidrv4=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\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])))",date=new RegExp(`^${dateSource}$`);string=params=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${regex}$`)},bigint=/^-?\d+n?$/,integer=/^-?\d+$/,number=/^-?\d+(?:\.\d+)?$/,boolean=/^(?:true|false)$/i,_null=/^null$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/}});var $ZodCheck,numericOriginMap,$ZodCheckLessThan,$ZodCheckGreaterThan,$ZodCheckMultipleOf,$ZodCheckNumberFormat,$ZodCheckMaxLength,$ZodCheckMinLength,$ZodCheckLengthEquals,$ZodCheckStringFormat,$ZodCheckRegex,$ZodCheckLowerCase,$ZodCheckUpperCase,$ZodCheckIncludes,$ZodCheckStartsWith,$ZodCheckEndsWith,$ZodCheckOverwrite,init_checks=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js"(){"use strict";init_core();init_regexes();init_util();$ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a3;inst._zod??(inst._zod={}),inst._zod.def=def,(_a3=inst._zod).onattach??(_a3.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;def.value<curr&&(def.inclusive?bag.maximum=def.value:bag.exclusiveMaximum=def.value)}),inst._zod.check=payload=>{(def.inclusive?payload.value<=def.value:payload.value<def.value)||payload.issues.push({origin,code:"too_big",maximum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;def.value>curr&&(def.inclusive?bag.minimum=def.value:bag.exclusiveMinimum=def.value)}),inst._zod.check=payload=>{(def.inclusive?payload.value>=def.value:payload.value>def.value)||payload.issues.push({origin,code:"too_small",minimum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.onattach.push(inst2=>{var _a3;(_a3=inst2._zod.bag).multipleOf??(_a3.multipleOf=def.value)}),inst._zod.check=payload=>{if(typeof payload.value!=typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof payload.value=="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)||payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum,isInt&&(bag.pattern=integer)}),inst._zod.check=payload=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){input>0?payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort}):payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort});return}}input<minimum&&payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort}),input>maximum&&payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;def.maximum<curr&&(inst2._zod.bag.maximum=def.maximum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;def.minimum>curr&&(inst2._zod.bag.minimum=def.minimum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=payload=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a3,_b;$ZodCheck.init(inst,def),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,def.pattern&&(bag.patterns??(bag.patterns=new Set),bag.patterns.add(def.pattern))}),def.pattern?(_a3=inst._zod).check??(_a3.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})}):(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),pattern=new RegExp(typeof def.position=="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.includes(def.includes,def.position)||payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.startsWith(def.prefix)||payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.endsWith(def.suffix)||payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{payload.value=def.tx(payload.value)}})}});var Doc,init_doc=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js"(){"use strict";Doc=class{constructor(args=[]){this.content=[],this.indent=0,this&&(this.args=args)}indented(fn){this.indent+=1,fn(this),this.indent-=1}write(arg){if(typeof arg=="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
2
- `).filter(x=>x),minIndent=Math.min(...lines.map(x=>x.length-x.trimStart().length)),dedented=lines.map(x=>x.slice(minIndent)).map(x=>" ".repeat(this.indent*2)+x);for(let line of dedented)this.content.push(line)}compile(){let F=Function,args=this?.args,lines=[...(this?.content??[""]).map(x=>` ${x}`)];return new F(...args,lines.join(`
3
- `))}}}});var version,init_versions=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js"(){"use strict";version={major:4,minor:4,patch:3}}});function isValidBase64(data){if(data==="")return!0;if(/\s/.test(data)||data.length%4!==0)return!1;try{return atob(data),!0}catch{return!1}}function isValidBase64URL(data){if(!base64url.test(data))return!1;let base642=data.replace(/[-_]/g,c=>c==="-"?"+":"/"),padded=base642.padEnd(Math.ceil(base642.length/4)*4,"=");return isValidBase64(padded)}function isValidJWT(token,algorithm=null){try{let tokensParts=token.split(".");if(tokensParts.length!==3)return!1;let[header]=tokensParts;if(!header)return!1;let parsedHeader=JSON.parse(atob(header));return!("typ"in parsedHeader&&parsedHeader?.typ!=="JWT"||!parsedHeader.alg||algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))}catch{return!1}}function handleArrayResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}function handlePropertyResult(result,final,key,input,isOptionalIn,isOptionalOut){let isPresent=key in input;if(result.issues.length){if(isOptionalIn&&isOptionalOut&&!isPresent)return;final.issues.push(...prefixIssues(key,result.issues))}if(!isPresent&&!isOptionalIn){result.issues.length||final.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[key]});return}result.value===void 0?isPresent&&(final.value[key]=void 0):final.value[key]=result.value}function normalizeDef(def){let keys2=Object.keys(def.shape);for(let k of keys2)if(!def.shape?.[k]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${k}": expected a Zod schema`);let okeys=optionalKeys(def.shape);return{...def,keys:keys2,keySet:new Set(keys2),numKeys:keys2.length,optionalKeys:new Set(okeys)}}function handleCatchall(proms,input,payload,ctx,def,inst){let unrecognized=[],keySet=def.keySet,_catchall=def.catchall._zod,t=_catchall.def.type,isOptionalIn=_catchall.optin==="optional",isOptionalOut=_catchall.optout==="optional";for(let key in input){if(key==="__proto__"||keySet.has(key))continue;if(t==="never"){unrecognized.push(key);continue}let r=_catchall.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut))):handlePropertyResult(r,payload,key,input,isOptionalIn,isOptionalOut)}return unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst}),proms.length?Promise.all(proms).then(()=>payload):payload}function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter(r=>!aborted(r));return nonaborted.length===1?(final.value=nonaborted[0].value,nonaborted[0]):(final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}),final)}function mergeValues(a,b){if(a===b)return{valid:!0,data:a};if(a instanceof Date&&b instanceof Date&&+a==+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};for(let key of sharedKeys){let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue;for(let iss of left.issues)if(iss.code==="unrecognized_keys"){unrecIssue??(unrecIssue=iss);for(let k of iss.keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k).l=!0}else result.issues.push(iss);for(let iss of right.issues)if(iss.code==="unrecognized_keys")for(let k of iss.keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k).r=!0;else result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k])=>k);if(bothKeys.length&&unrecIssue&&result.issues.push({...unrecIssue,keys:bothKeys}),aborted(result))return result;let merged=mergeValues(left.value,right.value);if(!merged.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);return result.value=merged.data,result}function handleOptionalResult(result,input){return input===void 0&&(result.issues.length||result.fallback)?{issues:[],value:void 0}:result}function handleDefaultResult(payload,def){return payload.value===void 0&&(payload.value=def.defaultValue),payload}function handleNonOptionalResult(payload,inst){return!payload.issues.length&&payload.value===void 0&&payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst}),payload}function handlePipeResult(left,next,ctx){return left.issues.length?(left.aborted=!0,left):next._zod.run({value:left.value,issues:left.issues,fallback:left.fallback},ctx)}function handleReadonlyResult(payload){return payload.value=Object.freeze(payload.value),payload}function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};inst._zod.def.params&&(_iss.params=inst._zod.def.params),payload.issues.push(issue(_iss))}}var $ZodType,$ZodString,$ZodStringFormat,$ZodGUID,$ZodUUID,$ZodEmail,$ZodURL,$ZodEmoji,$ZodNanoID,$ZodCUID,$ZodCUID2,$ZodULID,$ZodXID,$ZodKSUID,$ZodISODateTime,$ZodISODate,$ZodISOTime,$ZodISODuration,$ZodIPv4,$ZodIPv6,$ZodCIDRv4,$ZodCIDRv6,$ZodBase64,$ZodBase64URL,$ZodE164,$ZodJWT,$ZodNumber,$ZodNumberFormat,$ZodBoolean,$ZodBigInt,$ZodNull,$ZodAny,$ZodUnknown,$ZodNever,$ZodDate,$ZodArray,$ZodObject,$ZodObjectJIT,$ZodUnion,$ZodDiscriminatedUnion,$ZodIntersection,$ZodRecord,$ZodEnum,$ZodLiteral,$ZodTransform,$ZodOptional,$ZodExactOptional,$ZodNullable,$ZodDefault,$ZodPrefault,$ZodNonOptional,$ZodCatch,$ZodPipe,$ZodPreprocess,$ZodReadonly,$ZodLazy,$ZodCustom,init_schemas=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js"(){"use strict";init_checks();init_core();init_doc();init_parse();init_regexes();init_util();init_versions();init_util();$ZodType=$constructor("$ZodType",(inst,def)=>{var _a3;inst??(inst={}),inst._zod.def=def,inst._zod.bag=inst._zod.bag||{},inst._zod.version=version;let checks=[...inst._zod.def.checks??[]];inst._zod.traits.has("$ZodCheck")&&checks.unshift(inst);for(let ch of checks)for(let fn of ch._zod.onattach)fn(inst);if(checks.length===0)(_a3=inst._zod).deferred??(_a3.deferred=[]),inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse});else{let runChecks=(payload,checks2,ctx)=>{let isAborted=aborted(payload),asyncResult;for(let ch of checks2){if(ch._zod.def.when){if(explicitlyAborted(payload)||!ch._zod.def.when(payload))continue}else if(isAborted)continue;let currLen=payload.issues.length,_=ch._zod.check(payload);if(_ instanceof Promise&&ctx?.async===!1)throw new $ZodAsyncError;if(asyncResult||_ instanceof Promise)asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _,payload.issues.length!==currLen&&(isAborted||(isAborted=aborted(payload,currLen)))});else{if(payload.issues.length===currLen)continue;isAborted||(isAborted=aborted(payload,currLen))}}return asyncResult?asyncResult.then(()=>payload):payload},handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary))return canary.aborted=!0,canary;let checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return checkResult.then(checkResult2=>inst._zod.parse(checkResult2,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks)return inst._zod.parse(payload,ctx);if(ctx.direction==="backward"){let canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:!0});return canary instanceof Promise?canary.then(canary2=>handleCanaryResult(canary2,payload,ctx)):handleCanaryResult(canary,payload,ctx)}let result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return result.then(result2=>runChecks(result2,checks,ctx))}return runChecks(result,checks,ctx)}}defineLazy(inst,"~standard",()=>({validate:value=>{try{let r=safeParse(inst,value);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return safeParseAsync(inst,value).then(r=>r.success?{value:r.data}:{issues:r.error?.issues})}},vendor:"zod",version:1}))}),$ZodString=$constructor("$ZodString",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=[...inst?._zod.bag?.patterns??[]].pop()??string(inst._zod.bag),inst._zod.parse=(payload,_)=>{if(def.coerce)try{payload.value=String(payload.value)}catch{}return typeof payload.value=="string"||payload.issues.push({expected:"string",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodStringFormat=$constructor("$ZodStringFormat",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),$ZodString.init(inst,def)}),$ZodGUID=$constructor("$ZodGUID",(inst,def)=>{def.pattern??(def.pattern=guid),$ZodStringFormat.init(inst,def)}),$ZodUUID=$constructor("$ZodUUID",(inst,def)=>{if(def.version){let v={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[def.version];if(v===void 0)throw new Error(`Invalid UUID version: "${def.version}"`);def.pattern??(def.pattern=uuid(v))}else def.pattern??(def.pattern=uuid());$ZodStringFormat.init(inst,def)}),$ZodEmail=$constructor("$ZodEmail",(inst,def)=>{def.pattern??(def.pattern=email),$ZodStringFormat.init(inst,def)}),$ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{try{let trimmed=payload.value.trim();if(!def.normalize&&def.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(trimmed)){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:payload.value,inst,continue:!def.abort});return}let url2=new URL(trimmed);def.hostname&&(def.hostname.lastIndex=0,def.hostname.test(url2.hostname)||payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort})),def.protocol&&(def.protocol.lastIndex=0,def.protocol.test(url2.protocol.endsWith(":")?url2.protocol.slice(0,-1):url2.protocol)||payload.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort})),def.normalize?payload.value=url2.href:payload.value=trimmed;return}catch{payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(inst,def)=>{def.pattern??(def.pattern=emoji()),$ZodStringFormat.init(inst,def)}),$ZodNanoID=$constructor("$ZodNanoID",(inst,def)=>{def.pattern??(def.pattern=nanoid),$ZodStringFormat.init(inst,def)}),$ZodCUID=$constructor("$ZodCUID",(inst,def)=>{def.pattern??(def.pattern=cuid),$ZodStringFormat.init(inst,def)}),$ZodCUID2=$constructor("$ZodCUID2",(inst,def)=>{def.pattern??(def.pattern=cuid2),$ZodStringFormat.init(inst,def)}),$ZodULID=$constructor("$ZodULID",(inst,def)=>{def.pattern??(def.pattern=ulid),$ZodStringFormat.init(inst,def)}),$ZodXID=$constructor("$ZodXID",(inst,def)=>{def.pattern??(def.pattern=xid),$ZodStringFormat.init(inst,def)}),$ZodKSUID=$constructor("$ZodKSUID",(inst,def)=>{def.pattern??(def.pattern=ksuid),$ZodStringFormat.init(inst,def)}),$ZodISODateTime=$constructor("$ZodISODateTime",(inst,def)=>{def.pattern??(def.pattern=datetime(def)),$ZodStringFormat.init(inst,def)}),$ZodISODate=$constructor("$ZodISODate",(inst,def)=>{def.pattern??(def.pattern=date),$ZodStringFormat.init(inst,def)}),$ZodISOTime=$constructor("$ZodISOTime",(inst,def)=>{def.pattern??(def.pattern=time(def)),$ZodStringFormat.init(inst,def)}),$ZodISODuration=$constructor("$ZodISODuration",(inst,def)=>{def.pattern??(def.pattern=duration),$ZodStringFormat.init(inst,def)}),$ZodIPv4=$constructor("$ZodIPv4",(inst,def)=>{def.pattern??(def.pattern=ipv4),$ZodStringFormat.init(inst,def),inst._zod.bag.format="ipv4"}),$ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6),$ZodStringFormat.init(inst,def),inst._zod.bag.format="ipv6",inst._zod.check=payload=>{try{new URL(`http://[${payload.value}]`)}catch{payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4),$ZodStringFormat.init(inst,def)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{let parts=payload.value.split("/");try{if(parts.length!==2)throw new Error;let[address,prefix]=parts;if(!prefix)throw new Error;let prefixNum=Number(prefix);if(`${prefixNum}`!==prefix)throw new Error;if(prefixNum<0||prefixNum>128)throw new Error;new URL(`http://[${address}]`)}catch{payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}}});$ZodBase64=$constructor("$ZodBase64",(inst,def)=>{def.pattern??(def.pattern=base64),$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding="base64",inst._zod.check=payload=>{isValidBase64(payload.value)||payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}});$ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64url),$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding="base64url",inst._zod.check=payload=>{isValidBase64URL(payload.value)||payload.issues.push({code:"invalid_format",format:"base64url",input:payload.value,inst,continue:!def.abort})}}),$ZodE164=$constructor("$ZodE164",(inst,def)=>{def.pattern??(def.pattern=e164),$ZodStringFormat.init(inst,def)});$ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidJWT(payload.value,def.alg)||payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}}),$ZodNumber=$constructor("$ZodNumber",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=inst._zod.bag.pattern??number,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Number(payload.value)}catch{}let input=payload.value;if(typeof input=="number"&&!Number.isNaN(input)&&Number.isFinite(input))return payload;let received=typeof input=="number"?Number.isNaN(input)?"NaN":Number.isFinite(input)?void 0:"Infinity":void 0;return payload.issues.push({expected:"number",code:"invalid_type",input,inst,...received?{received}:{}}),payload}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(inst,def)=>{$ZodCheckNumberFormat.init(inst,def),$ZodNumber.init(inst,def)}),$ZodBoolean=$constructor("$ZodBoolean",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=boolean,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=!!payload.value}catch{}let input=payload.value;return typeof input=="boolean"||payload.issues.push({expected:"boolean",code:"invalid_type",input,inst}),payload}}),$ZodBigInt=$constructor("$ZodBigInt",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=bigint,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=BigInt(payload.value)}catch{}return typeof payload.value=="bigint"||payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodNull=$constructor("$ZodNull",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_null,inst._zod.values=new Set([null]),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return input===null||payload.issues.push({expected:"null",code:"invalid_type",input,inst}),payload}}),$ZodAny=$constructor("$ZodAny",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodUnknown=$constructor("$ZodUnknown",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodNever=$constructor("$ZodNever",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>(payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst}),payload)}),$ZodDate=$constructor("$ZodDate",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=new Date(payload.value)}catch{}let input=payload.value,isDate=input instanceof Date;return isDate&&!Number.isNaN(input.getTime())||payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst}),payload}});$ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({expected:"array",code:"invalid_type",input,inst}),payload;payload.value=Array(input.length);let proms=[];for(let i=0;i<input.length;i++){let item=input[i],result=def.element._zod.run({value:item,issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>handleArrayResult(result2,payload,i))):handleArrayResult(result,payload,i)}return proms.length?Promise.all(proms).then(()=>payload):payload}});$ZodObject=$constructor("$ZodObject",(inst,def)=>{if($ZodType.init(inst,def),!Object.getOwnPropertyDescriptor(def,"shape")?.get){let sh=def.shape;Object.defineProperty(def,"shape",{get:()=>{let newSh={...sh};return Object.defineProperty(def,"shape",{value:newSh}),newSh}})}let _normalized=cached(()=>normalizeDef(def));defineLazy(inst._zod,"propValues",()=>{let shape=def.shape,propValues={};for(let key in shape){let field=shape[key]._zod;if(field.values){propValues[key]??(propValues[key]=new Set);for(let v of field.values)propValues[key].add(v)}}return propValues});let isObject2=isObject,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;payload.value={};let proms=[],shape=value.shape;for(let key of value.keys){let el=shape[key],isOptionalIn=el._zod.optin==="optional",isOptionalOut=el._zod.optout==="optional",r=el._zod.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut))):handlePropertyResult(r,payload,key,input,isOptionalIn,isOptionalOut)}return catchall?handleCatchall(proms,input,payload,ctx,_normalized.value,inst):proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);let superParse=inst._zod.parse,_normalized=cached(()=>normalizeDef(def)),generateFastpass=shape=>{let doc=new Doc(["shape","payload","ctx"]),normalized=_normalized.value,parseStr=key=>{let k=esc(key);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};doc.write("const input = payload.value;");let ids=Object.create(null),counter=0;for(let key of normalized.keys)ids[key]=`key_${counter++}`;doc.write("const newResult = {};");for(let key of normalized.keys){let id=ids[key],k=esc(key),schema2=shape[key],isOptionalIn=schema2?._zod?.optin==="optional",isOptionalOut=schema2?._zod?.optout==="optional";doc.write(`const ${id} = ${parseStr(key)};`),isOptionalIn&&isOptionalOut?doc.write(`
4
- if (${id}.issues.length) {
5
- if (${k} in input) {
6
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
7
- ...iss,
8
- path: iss.path ? [${k}, ...iss.path] : [${k}]
9
- })));
1
+ var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})};var __create,__defProp2,__getOwnPropDesc,__getOwnPropNames2,__getProtoOf,__hasOwnProp,__commonJSMin,__exportAll,__copyProps,__toESM,init_chunk_Br0eD_fh=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs"(){"use strict";__create=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports),__exportAll=(all,symbols)=>{let target={};for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0});return symbols&&__defProp2(target,Symbol.toStringTag,{value:"Module"}),target},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(var keys2=__getOwnPropNames2(from),i=0,n=keys2.length,key;i<n;i++)key=keys2[i],!__hasOwnProp.call(to,key)&&key!==except&&__defProp2(to,key,{get:(k=>from[k]).bind(null,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp2(target,"default",{value:mod,enumerable:!0}):target,mod))}});function declares2019Dialect($schema){return typeof $schema=="string"&&DRAFT_2019_09_URIS.has($schema.replace(/#$/,""))}function declaredDialect(schema2,remedy){if(!("$schema"in schema2)||typeof schema2.$schema!="string")return"2020-12";let declared=schema2.$schema.replace(/#$/,"");if(DRAFT_2020_12_URIS.has(declared))return"2020-12";if(DRAFT_2019_09_URIS.has(declared))return"2019-09";if(DRAFT_07_URIS.has(declared)||DRAFT_06_URIS.has(declared))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema2.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`)}var DRAFT_2020_12_URIS,DRAFT_2019_09_URIS,DRAFT_07_URIS,DRAFT_06_URIS,init_dialects_DoSzNhcb=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs"(){"use strict";DRAFT_2020_12_URIS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),DRAFT_2019_09_URIS=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),DRAFT_07_URIS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),DRAFT_06_URIS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])}});var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,CONSTANT_CATCH:()=>CONSTANT_CATCH,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,attachSchema:()=>attachSchema,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,codePointLength:()=>codePointLength,constantCatch:()=>constantCatch,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,defineLazyInternal:()=>defineLazyInternal,derived:()=>derived,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,hide:()=>hide,installLazyProp:()=>installLazyProp,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,members:()=>members,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,own:()=>own,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,rawShape:()=>rawShape,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,sizeCaps:()=>sizeCaps,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,toZod:()=>toZod,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function toZod(){return schema2=>schema2}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_){}function getEnumValues(entries){let numericValues=Object.values(entries).filter(v=>typeof v=="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function joinValues(array4,separator="|"){return array4.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return new Cached(getter)}function nullish(input){return input==null}function cleanRegex(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){let ratio=val/step,roundedRatio=Math.round(ratio),tolerance=4*Number.EPSILON*Math.max(Math.abs(ratio),1);return Math.abs(ratio-roundedRatio)<tolerance?0:ratio-roundedRatio}function defineLazy(object5,key,getter){let value;Object.defineProperty(object5,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v){Object.defineProperty(object5,key,{value:v})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function rawShape(def){let desc=Object.getOwnPropertyDescriptor(def,"shape");return desc?.get?desc.get.raw:desc?.value}function sourceShape(schema2){return rawShape(schema2._zod.def)??schema2._zod.def.shape}function deferProp(target,key,getter){Object.defineProperty(target,key,{get(){let value=getter();return assignProp(this,key,value),value},enumerable:!0,configurable:!0})}function putProp(target,key,value){key in target?assignProp(target,key,value):target[key]=value}function mirrorShape(target,source,keys2,wrap){let raw2=sourceShape(source);for(let key of keys2){let desc=Object.getOwnPropertyDescriptor(raw2,key);desc.enumerable&&(desc.get?deferProp(target,key,()=>{let value=source._zod.def.shape[key];return wrap?wrap(value,key):value}):putProp(target,key,wrap?wrap(desc.value,key):desc.value))}}function mirrorProps(target,source){for(let key of Reflect.ownKeys(source)){let desc=Object.getOwnPropertyDescriptor(source,key);desc.enumerable&&(desc.get?deferProp(target,key,()=>source[key]):putProp(target,key,desc.value))}}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema2){return mergeDefs(schema2._zod.def)}function getElementAtPath(obj,path){return path?path.reduce((acc,key)=>acc?.[key],obj):obj}function promiseAllObject(promisesObj){let keys2=Object.keys(promisesObj),promises=keys2.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{let resolvedObj={};for(let i=0;i<keys2.length;i++)resolvedObj[keys2[i]]=results[i];return resolvedObj})}function randomString(length=10){let chars="abcdefghijklmnopqrstuvwxyz",str="";for(let i=0;i<length;i++)str+=chars[Math.floor(Math.random()*chars.length)];return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject(data){return typeof data=="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;let prot=ctor.prototype;return!(isObject(prot)===!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function numKeys(data){let keyCount=0;for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&keyCount++;return keyCount}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){return typeof value=="bigint"?value.toString()+"n":typeof value=="string"?`"${value}"`:`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k=>shape[k]._zod.optin!==void 0&&shape[k]._zod.optout==="optional")}function pick(schema2,mask){let currDef=schema2._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let newShape={};return mirrorShape(newShape,schema2,maskedKeys(schema2,mask)),clone(schema2,mergeDefs(currDef,{shape:newShape,checks:[]}))}function maskedKeys(schema2,mask){let raw2=sourceShape(schema2),keys2=[];for(let key of Reflect.ownKeys(mask)){if(!Object.getOwnPropertyDescriptor(raw2,key)?.enumerable)throw new Error(`Unrecognized key: "${String(key)}"`);mask[key]&&keys2.push(key)}return keys2}function omit(schema2,mask){let currDef=schema2._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let omitted=new Set(maskedKeys(schema2,mask)),newShape={};return mirrorShape(newShape,schema2,Reflect.ownKeys(sourceShape(schema2)).filter(key=>!omitted.has(key))),clone(schema2,mergeDefs(currDef,{shape:newShape,checks:[]}))}function extend(schema2,shape){if(!isPlainObject(shape))throw new Error("Invalid input to extend: expected a plain object");let checks=schema2._zod.def.checks;if(checks&&checks.length>0){let existingShape=sourceShape(schema2);for(let key of Reflect.ownKeys(shape))if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(schema2,mergeDefs(schema2._zod.def,{shape:extended(schema2,shape)}))}function extended(schema2,shape){let newShape={};return mirrorShape(newShape,schema2,Reflect.ownKeys(sourceShape(schema2))),mirrorProps(newShape,shape),newShape}function safeExtend(schema2,shape){if(!isPlainObject(shape))throw new Error("Invalid input to safeExtend: expected a plain object");return clone(schema2,mergeDefs(schema2._zod.def,{shape:extended(schema2,shape)}))}function merge(a,b){if(!b?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(a._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let newShape={};mirrorShape(newShape,a,Reflect.ownKeys(sourceShape(a))),mirrorShape(newShape,b,Reflect.ownKeys(sourceShape(b)));let def=mergeDefs(a._zod.def,{shape:newShape,get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema2,mask,name="partial"){let checks=schema2._zod.def.checks;if(checks&&checks.length>0)throw new Error(`.${name}() cannot be used on object schemas containing refinements`);let selected=mask?new Set(maskedKeys(schema2,mask)):void 0,newShape={};return mirrorShape(newShape,schema2,Reflect.ownKeys(sourceShape(schema2)),Class2&&((value,key)=>selected&&!selected.has(key)?value:new Class2({type:"optional",innerType:value}))),clone(schema2,mergeDefs(schema2._zod.def,{shape:newShape,checks:[]}))}function required(Class2,schema2,mask){let selected=mask?new Set(maskedKeys(schema2,mask)):void 0,newShape={};return mirrorShape(newShape,schema2,Reflect.ownKeys(sourceShape(schema2)),(value,key)=>selected&&!selected.has(key)?value:new Class2({type:"nonoptional",innerType:value})),clone(schema2,mergeDefs(schema2._zod.def,{shape:newShape}))}function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function explicitlyAborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue===!1)return!0;return!1}function prefixIssues(path,issues){return issues.map(iss=>{var _a3;return(_a3=iss).path??(_a3.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message=="string"?message:message?.message}function sizeCaps(defChecks){let caps=[];for(let ch of defChecks??[]){let d=ch._zod.def;if(!/_(length|size)$|_equals$/.test(d.check))break;let max=d.maximum??d.length??d.size;max>=0&&caps.push([max,ch])}return caps}function attachSchema(issues,start,inst){var _a3;for(let i=start;i<issues.length;i++)(_a3=issues[i]).schema??(_a3.schema=inst)}function finalizeIssue(iss,ctx,config2){var _a3;let traits=iss.inst?._zod?.traits;traits?.has("$ZodType")&&(traits.has("$ZodCheck")?(_a3=iss).schema??(_a3.schema=iss.inst):iss.schema=iss.inst);let schemaError=iss.schema!==iss.inst?iss.schema?._zod.def?.error:void 0,message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(schemaError?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input",full={};for(let k of Object.keys(iss))k==="inst"||k==="schema"||k==="continue"||k==="input"||k==="__proto__"||(full[k]=iss[k]);return full.path??(full.path=[]),full.message=message,ctx?.reportInput&&(full.input=iss.input),full}function getSizableOrigin(input){return input instanceof Set?"set":input instanceof Map?"map":input instanceof File?"file":"unknown"}function codePointLength(str){let units=str.length;if(!highSurrogate.test(str))return units;let count=units;for(let i=0;i<units-1;i++)(str.charCodeAt(i)&64512)===55296&&(str.charCodeAt(i+1)&64512)===56320&&(count--,i++);return count}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args){let[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>Number.isNaN(Number.parseInt(k,10))).map(el=>el[1])}function base64ToUint8Array(base642){let binaryString=atob(base642),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array(base64url2){let base642=base64url2.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base642.length%4)%4);return base64ToUint8Array(base642+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex){let cleanHex=hex.replace(/^0x/,"");if(cleanHex.length%2!==0)throw new Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b=>b.toString(16).padStart(2,"0")).join("")}function members(proto,table){for(let key in table){let desc=Object.getOwnPropertyDescriptor(table,key);desc.get?Object.defineProperty(proto,key,{...desc,enumerable:!1}):defineBound(proto,key,desc.value)}}function own(inst,key,value,enumerable=!0){return Object.defineProperty(inst,key,{configurable:!0,writable:!0,enumerable,value}),value}function hide(inst,key,value){return own(inst,key,value,!1)}function derived(computes,table){for(let key in computes){let compute=computes[key];Object.defineProperty(table,key,{configurable:!0,enumerable:!0,get(){return own(this,key,compute(this))},set(value){own(this,key,value)}})}return table}function defineBound(proto,key,fn){Object.defineProperty(proto,key,{configurable:!0,get(){return this==null?fn:own(this,key,fn.bind(this))},set(value){own(this,key,value)}})}function claim(inst,sentinel){let proto=Object.getPrototypeOf(inst);return sentinel in proto?void 0:proto}function defineLazyInternal(inst,key,compute){let proto=Object.getPrototypeOf(inst._zod);if(key in proto&&installing!==inst._zod){installing=void 0;return}installing=inst._zod,Object.defineProperty(proto,key,{configurable:!0,get(){Object.defineProperty(this,key,breaker);let outer=broke;broke=!1;try{let value=compute(this);return broke?delete this[key]:Object.defineProperty(this,key,{configurable:!0,writable:!0,value}),broke=broke||outer,value}catch(err){throw delete this[key],broke=broke||outer,err}},set(value){Object.defineProperty(this,key,{configurable:!0,writable:!0,value})}})}function installLazyProp(inst,key,make,enumerable){let proto=claim(inst,key);proto&&Object.defineProperty(proto,key,{configurable:!0,get(){let desc={configurable:!0,writable:!0,enumerable,value:void 0};return Object.defineProperty(this,key,desc),desc.value=make(this),Object.defineProperty(this,key,desc),desc.value},set(value){Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable,value})}})}function constantCatch(value){let fn=()=>value;return fn[CONSTANT_CATCH]=!0,fn}var Cached,EVALUATING,captureStackTrace,allowsEval,getParsedType,propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES,highSurrogate,Class,installing,broke,breaker,CONSTANT_CATCH,init_util=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js"(){"use strict";init_core();Cached=class{constructor(getter){this._getter=getter,this._value=void 0}get value(){let getter=this._getter;return getter!==void 0&&(this._value=getter(),this._getter=void 0),this._value}};EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let F=Function;return new F(""),!0}catch{return!1}});getParsedType=data=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(data)?"array":data===null?"null":data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?"promise":typeof Map<"u"&&data instanceof Map?"map":typeof Set<"u"&&data instanceof Set?"set":typeof Date<"u"&&data instanceof Date?"date":typeof File<"u"&&data instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};highSurrogate=/[\uD800-\uDBFF]/;Class=class{constructor(..._args){}};broke=!1,breaker={configurable:!0,get(){broke=!0}};CONSTANT_CATCH="~constantCatch"}});function newError(Definition){let E=_E;if(E){let saved=E.stackTraceLimit;if(typeof saved=="number"){try{E.stackTraceLimit=0}catch{return _E=null,new Definition}try{return new Definition}finally{E.stackTraceLimit=saved}}}return new Definition}function $constructor(name,initializer3,proto,params){let zodProto={};function Internals(def){this.def=def,this.constr=_,this.traits=new Set}Internals.prototype=zodProto;let protoMembers=proto,initialized=protoMembers&&new WeakSet;function init(inst,def){if(inst._zod){if(inst._zod.traits.has(name))return}else{_zodDesc.value=new Internals(def);try{Object.defineProperty(inst,"_zod",_zodDesc)}finally{_zodDesc.value=void 0}}if(inst._zod.traits.add(name),initializer3(inst,def),initialized){let own2=Object.getPrototypeOf(inst),ctorProto=inst._zod.constr.prototype,up=own2;for(;up&&up!==ctorProto;)up=Object.getPrototypeOf(up);let target=up??own2;initialized.has(target)||(initialized.add(target),members(target,protoMembers))}let proto2=_.prototype;for(let k in proto2)Object.prototype.hasOwnProperty.call(proto2,k)&&(k in inst||(inst[k]=proto2[k].bind(inst)))}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){let inst=params?.Parent?newError(Definition):this;init(inst,def);let deferred=inst._zod.deferred;if(deferred){for(let fn of deferred)fn();inst._zod.deferred=void 0}let pp=globalThis.__zod_globalConfig?.postProcessor;return pp&&pp(inst),inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_,"name",{value:name}),_}function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}var _a,NEVER,_zodDesc,_E,$ZodAsyncError,$ZodEncodeError,globalConfig,init_core=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js"(){"use strict";init_util();NEVER=Object.freeze({status:"aborted"}),_zodDesc={value:void 0,enumerable:!1},_E="captureStackTrace"in Error?Error:null;$ZodAsyncError=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}};(_a=globalThis).__zod_globalConfig??(_a.__zod_globalConfig={});globalConfig=globalThis.__zod_globalConfig}});function _getMessage(){let internals=this._zod;return internals.message??(internals.message=JSON.stringify(internals.def,jsonStringifyReplacer,2)),internals.message}function _setMessage(value){this._zod.message=value}function node(obj,key,make){return Object.prototype.hasOwnProperty.call(obj,key)||(key==="__proto__"?Object.defineProperty(obj,key,{value:make(),writable:!0,enumerable:!0,configurable:!0}):obj[key]=make()),obj[key]}function flattenError(error3,mapper=issue2=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error3.issues)sub.path.length>0?node(fieldErrors,sub.path[0],()=>[]).push(mapper(sub)):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error3,mapper=issue2=>issue2.message){let fieldErrors={_errors:[]},processError=(error4,path=[])=>{for(let issue2 of error4.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path,...issue2.path]);else{let fullpath=[...path,...issue2.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;for(;i<fullpath.length;){let el=fullpath[i],terminal=i===fullpath.length-1;if(el==="_errors"){terminal&&curr._errors.push(mapper(issue2)),i++;continue}Object.prototype.hasOwnProperty.call(curr,el)||Object.defineProperty(curr,el,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let node2=curr[el];terminal&&node2._errors.push(mapper(issue2)),curr=node2,i++}}}};return processError(error3),fieldErrors}var _messageDesc,_issuesDesc,_installedToString,initializer,$ZodError,$ZodRealError,init_errors=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js"(){"use strict";init_core();init_util();_messageDesc={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},_issuesDesc={value:void 0,enumerable:!1},_installedToString=new WeakSet([Object.prototype,Error.prototype]),initializer=(inst,def)=>{inst.name="$ZodError",_issuesDesc.value=def,Object.defineProperty(inst,"issues",_issuesDesc),_issuesDesc.value=void 0,Object.defineProperty(inst,"message",_messageDesc);let proto=Object.getPrototypeOf(inst);_installedToString.has(proto)||(_installedToString.add(proto),Object.defineProperty(proto,"toString",{configurable:!0,enumerable:!1,get(){let value=()=>this.message;return Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0})}}))},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,void 0,{Parent:Error})}});function finalizeParams(callee,params){return{callee:params?.callee??callee,Err:params?.Err}}function failure(Err,issues,ctx){let error3;return{success:!1,get error(){return error3||(error3=new Err(issues.map(iss=>finalizeIssue(iss,ctx,config()))),issues=void 0,ctx=void 0),error3},set error(e){error3=e,issues=void 0,ctx=void 0}}}function validateFallback(schema2,value,_ctx){let ctx=_ctx?{..._ctx,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},fallbackRun=schema2._zod.bag.fallbackRun,result;if(fallbackRun?(ctx[COMPILE_FALLBACK]=!0,result=fallbackRun({value,issues:[]},ctx)):result=schema2._zod.run({value,issues:[]},ctx),result instanceof Promise)throw new $ZodAsyncError;return result.issues.length===0}var _parse,_parseAsync,_safeParse,_safeParseAsync,COMPILE_INVALID,COMPILE_FALLBACK,validate,validateAsync,_encode,_decode,_encodeAsync,_decodeAsync,_safeEncode,_safeDecode,_safeEncodeAsync,_safeDecodeAsync,init_parse=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js"(){"use strict";init_core();init_util();_parse=_Err=>{let fn=(schema2,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee??fn),e}return result.value};return fn},_parseAsync=_Err=>{let fn=async(schema2,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){let e=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee??fn),e}return result.value};return fn},_safeParse=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?failure(_Err,result.issues,ctx):{success:!0,data:result.value}};_safeParseAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema2._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?failure(_Err,result.issues,ctx):{success:!0,data:result.value}},COMPILE_INVALID=Symbol.for("zod.compile.invalid"),COMPILE_FALLBACK=Symbol.for("zod.compile.fallback"),validate=((schema2,value,_ctx)=>{let validator=schema2._zod.bag.validator;if(validator!==void 0){if(validator(value)!==COMPILE_INVALID)return!0;if(validator.definite===!0&&_ctx===void 0)return!1}return validateFallback(schema2,value,_ctx)});validateAsync=async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},result=schema2._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length===0},_encode=_Err=>{let parse3=_parse(_Err),fn=(schema2,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return parse3(schema2,value,ctx,finalizeParams(fn,_params))};return fn},_decode=_Err=>{let parse3=_parse(_Err),fn=(schema2,value,_ctx,_params)=>parse3(schema2,value,_ctx,finalizeParams(fn,_params));return fn},_encodeAsync=_Err=>{let parseAsync2=_parseAsync(_Err),fn=async(schema2,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return await parseAsync2(schema2,value,ctx,finalizeParams(fn,_params))};return fn},_decodeAsync=_Err=>{let parseAsync2=_parseAsync(_Err),fn=async(schema2,value,_ctx,_params)=>await parseAsync2(schema2,value,_ctx,finalizeParams(fn,_params));return fn},_safeEncode=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema2,value,ctx)},_safeDecode=_Err=>(schema2,value,_ctx)=>_safeParse(_Err)(schema2,value,_ctx),_safeEncodeAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema2,value,ctx)},_safeDecodeAsync=_Err=>async(schema2,value,_ctx)=>_safeParseAsync(_Err)(schema2,value,_ctx)}});function nanoidOfLength(length){return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`)}function emoji(){return new RegExp(_emoji,"u")}function anchor(source){return new RegExp(`^${source}$`)}function timeSource(args){let hhmm="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof args.precision=="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:args.seconds?`${hhmm}:[0-5]\\d(?:\\.\\d+)?`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){let opts=["Z"];args.offset&&opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let qualified=`${timeSource({precision:args.precision,seconds:!0})}(?:${opts.join("|")})`,timeRegex=args.local?`${qualified}|${timeSource({precision:args.precision})}`:qualified;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}var cuid,cuid2,ulid,xid,ksuid,nanoid,duration,guid,uuid,email,_emoji,ipv4,ipv6,cidrv4,cidrv6,base64,base64url,httpProtocol,e164,dateSource,date,anyString,bigint,integer,number,boolean,_null,lowercase,uppercase,init_regexes=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js"(){"use strict";cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/;duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version2=>version2?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,cidrv4=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\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])))";date=anchor(dateSource);anyString=/^[\s\S]{0,}$/,bigint=/^-?\d+n?$/,integer=/^-?\d+$/,number=/^-?\d+(?:\.\d+)?$/,boolean=/^(?:true|false)$/i,_null=/^null$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/}});var $ZodCheck,_whenHasLength,numericOriginMap,$ZodCheckLessThan,$ZodCheckGreaterThan,$ZodCheckMultipleOf,$ZodCheckNumberFormat,$ZodCheckMaxLength,$ZodCheckMinLength,$ZodCheckLengthEquals,$ZodCheckStringFormat,$ZodCheckRegex,$ZodCheckLowerCase,$ZodCheckUpperCase,$ZodCheckIncludes,$ZodCheckStartsWith,$ZodCheckEndsWith,$ZodCheckOverwrite,init_checks=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js"(){"use strict";init_core();init_regexes();init_util();$ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a3;inst._zod??(inst._zod={}),inst._zod.def=def,(_a3=inst._zod).onattach??(_a3.onattach=[])}),_whenHasLength=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0},numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.check=payload=>{(def.inclusive?payload.value<=def.value:payload.value<def.value)||payload.issues.push({origin:numericOriginMap[typeof payload.value]??origin,code:"too_big",maximum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.check=payload=>{(def.inclusive?payload.value>=def.value:payload.value>def.value)||payload.issues.push({origin:numericOriginMap[typeof payload.value]??origin,code:"too_small",minimum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{if(typeof payload.value!=typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof payload.value=="bigint"?def.value!==BigInt(0)&&payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)||payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.check=payload=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){input>0?payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort}):payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort});return}}input<minimum&&payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort}),input>maximum&&payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=_whenHasLength),inst._zod.check=payload=>{let input=payload.value,units=input.length;if((typeof input=="string"&&units>def.maximum?codePointLength(input):units)<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=_whenHasLength),inst._zod.check=payload=>{let input=payload.value,units=input.length;if((typeof input=="string"&&units>=def.minimum&&units<def.minimum*2?codePointLength(input):units)>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=_whenHasLength),inst._zod.check=payload=>{let input=payload.value,units=input.length,length=typeof input=="string"&&units>=def.length&&units<=def.length*2?codePointLength(input):units;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a3,_b;$ZodCheck.init(inst,def),def.pattern?(_a3=inst._zod).check??(_a3.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})}):(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),pattern=new RegExp(typeof def.position=="number"?`^.{${def.position},}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.check=payload=>{payload.value.includes(def.includes,def.position)||payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.check=payload=>{payload.value.startsWith(def.prefix)||payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.check=payload=>{payload.value.endsWith(def.suffix)||payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{payload.value=def.tx(payload.value)}})}});var Doc,init_doc=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js"(){"use strict";Doc=class{constructor(args=[],closed={}){this.content=[],this.indent=0,this.args=args,this.closed=closed}indented(fn){this.indent+=1;try{fn(this)}finally{this.indent-=1}}write(arg){if(typeof arg=="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
2
+ `).filter(x=>x),minIndent=Math.min(...lines.map(x=>x.length-x.trimStart().length)),dedented=lines.map(x=>x.slice(minIndent)).map(x=>" ".repeat(this.indent*2)+x);for(let line of dedented)this.content.push(line)}compile(){let F=Function,content=this?.content??[""];return new F(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
3
+ ${content.join(`
4
+ `)}
5
+ };`)(...Object.values(this.closed))}}}});var version,init_versions=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js"(){"use strict";version={major:4,minor:6,patch:6}}});async function validateAsync2(inst,value){let ctx={async:!0};return toStandardResult(await inst._zod.run({value,issues:[]},ctx),ctx)}function standardProps(inst){return{validate:value=>{let ctx={async:!1};try{let r=inst._zod.run({value,issues:[]},ctx);if(!(r instanceof Promise))return toStandardResult(r,ctx)}catch{}return validateAsync2(inst,value)},vendor:"zod",version:1}}function canParseURL(input){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(input):(new URL(input),!0)}catch{return!1}}function validateURL(trimmed,def){return!("normalize"in def)&&!("hostname"in def)&&!("protocol"in def)?canParseURL(trimmed)||URL_UNPARSEABLE:parseURLObject(trimmed,def)}function parseURLObject(trimmed,def){if(!def.normalize&&def.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(trimmed))return URL_BAD_FORMAT;try{if(typeof URL<"u"){let URLStatic=URL;if(typeof URLStatic.parse=="function")return URLStatic.parse(trimmed)??URL_UNPARSEABLE}return new URL(trimmed)}catch{return URL_UNPARSEABLE}}function stripTabAndNewline(value){return value.replace(asciiTabOrNewline,"")}function urlHostnameOk(url2,hostname){return hostname.lastIndex=0,hostname.test(url2.hostname)}function urlProtocolOk(url2,protocol){return protocol.lastIndex=0,protocol.test(url2.protocol.endsWith(":")?url2.protocol.slice(0,-1):url2.protocol)}function isValidIPv6(value){return ipv6Alphabet.test(value)?canParseURL(`http://[${value}]`):!1}function isValidCIDRv6(value){let parts=value.split("/");if(parts.length!==2)return!1;let[address,prefix]=parts;if(!prefix)return!1;let prefixNum=Number(prefix);return`${prefixNum}`!==prefix||prefixNum<0||prefixNum>128?!1:isValidIPv6(address)}function isValidBase64(data){if(data==="")return!0;if(/\s/.test(data)||data.length%4!==0)return!1;try{return atob(data),!0}catch{return!1}}function isValidBase64URL(data){if(!base64urlCharset.test(data))return!1;let base642=data.replace(/[-_]/g,c=>c==="-"?"+":"/"),padded=base642.padEnd(Math.ceil(base642.length/4)*4,"=");return isValidBase64(padded)}function isValidJWT(token,algorithm=null){try{let tokensParts=token.split(".");if(tokensParts.length!==3)return!1;let[header]=tokensParts;if(!header)return!1;let parsedHeader=JSON.parse(atob(header));return!("typ"in parsedHeader&&parsedHeader?.typ!=="JWT"||!parsedHeader.alg||algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))}catch{return!1}}function capSize(inst,size){let caps=sizeCaps(inst._zod.def.checks);if(!caps.length)return;let cap=Math.min(...caps.map(c=>c[0])),parse3=inst._zod.parse;inst._zod.parse=(payload,ctx)=>{let n=size(payload.value);if(n>cap&&!ctx?.skipChecks&&ctx?.direction!=="backward"){for(let[max,ch]of sizeCaps(inst._zod.def.checks))if(n>max&&ch._zod.def.when(payload)){let start=payload.issues.length;return ch._zod.check(payload),payload.issues[start].continue=!1,attachSchema(payload.issues,start,inst),payload}}return parse3(payload,ctx)}}function handleArrayResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}function handlePropertyResult(result,final,key,input,optin,optout){let isPresent=key in input,isOptionalOut=optout==="optional";if(!(!isPresent&&isOptionalOut&&optin==="optional")){if(result.issues.length){if(optin!==void 0&&isOptionalOut&&!isPresent)return;final.issues.push(...prefixIssues(key,result.issues))}if(!isPresent&&optin===void 0){result.issues.length||final.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[key]});return}result.value===void 0?(isPresent||optin==="defaulted"&&!isOptionalOut)&&(final.value[key]=void 0):final.value[key]=result.value}}function normalizeDef(def){let keys2=Object.keys(def.shape),ownSymbols=Object.getOwnPropertySymbols(def.shape),symbolKeys=ownSymbols.length?ownSymbols:NO_SYMBOL_KEYS,allKeys=symbolKeys.length?[...keys2,...symbolKeys]:keys2;for(let k of allKeys)if(!def.shape?.[k]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`);let okeys=optionalKeys(def.shape);return{...def,allKeys,symbolKeys,keySet:new Set(keys2),numKeys:keys2.length,optionalKeys:new Set(okeys)}}function handleCatchall(proms,input,payload,ctx,def,inst,abortEarly){let unrecognized=[],keySet=def.keySet,_catchall=def.catchall._zod,t=_catchall.def.type,optin=_catchall.optin,optout=_catchall.optout,seen=0;for(let key in input){if(abortEarly&&payload.issues.length!==seen){if(aborted(payload,seen))break;seen=payload.issues.length}if(keySet.has(key))continue;if(key==="__proto__"){t==="never"&&unrecognized.push(key);continue}if(t==="never"){unrecognized.push(key);continue}let r=_catchall.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,optin,optout))):handlePropertyResult(r,payload,key,input,optin,optout)}return unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst,continue:!0}),proms.length?Promise.all(proms).then(()=>payload):payload}function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter(r=>!aborted(r));return nonaborted.length===1?(final.value=nonaborted[0].value,nonaborted[0]):(final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}),final)}function discriminatorMap(def){let map=new Map;for(let option of def.options){let values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let value of values)if(map.has(value)){if(value!==void 0)throw new Error(`Duplicate discriminator value "${String(value)}"`);map.set(value,null)}else map.set(value,option)}return map}function mergeValues(a,b){if(a===b)return{valid:!0,data:a};if(a instanceof Date&&b instanceof Date&&+a==+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};Object.prototype.hasOwnProperty.call(newObj,"__proto__")&&delete newObj.__proto__;for(let key of sharedKeys){if(key==="__proto__")continue;let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue,keyIssues=new Map,collect=(iss,side)=>{let keys2;if(iss.code==="unrecognized_keys"&&!iss.path?.length)unrecIssue??(unrecIssue=iss),keys2=iss.keys;else if(iss.code==="invalid_key"&&iss.origin==="record"&&iss.path?.length===1){let k=String(iss.path[0]);keyIssues.has(k)||keyIssues.set(k,iss),keys2=[k]}else return!1;for(let k of keys2)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k)[side]=!0;return!0};for(let iss of left.issues)collect(iss,"l")||result.issues.push(iss);for(let iss of right.issues)collect(iss,"r")||result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k])=>k);if(bothKeys.length){let aggregated=unrecIssue?bothKeys.filter(k=>unrecIssue.keys.includes(k)):[];aggregated.length&&result.issues.push({...unrecIssue,keys:aggregated});for(let k of bothKeys)!aggregated.includes(k)&&keyIssues.has(k)&&result.issues.push(keyIssues.get(k))}let merged=mergeValues(left.value,right.value);if(!merged.valid){if(aborted(result))return result;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`)}return result.value=merged.data,result}function handleOptionalResult(payload,result){return payload.value=result.issues.length?void 0:result.value,payload}function handleDefaultResult(payload,def){return payload.value===void 0&&(payload.value=def.defaultValue),payload}function handleNonOptionalResult(payload,inst){return!payload.issues.length&&payload.value===void 0&&payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst}),payload}function handleCatchResult(payload,result,def,ctx){return result.issues.length?(payload.value=def.catchValue({...result,value:payload.value,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload):(payload.value=result.value,result.memo&&(payload.memo=!0),payload)}function handlePipeResult(left,next,ctx){return left.issues.some(iss=>iss.code!=="unrecognized_keys")?(left.aborted=!0,left):next._zod.run({value:left.value,issues:left.issues},ctx)}function handleReadonlyResult(payload){return payload.memo||(payload.value=Object.freeze(payload.value)),payload}function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};inst._zod.def.params&&(_iss.params=inst._zod.def.params),payload.issues.push(issue(_iss))}}var $ZodType,toStandardResult,$ZodString,$ZodStringFormat,$ZodGUID,$ZodUUID,$ZodEmail,URL_BAD_FORMAT,URL_UNPARSEABLE,asciiTabOrNewline,$ZodURL,$ZodEmoji,$ZodNanoID,$ZodCUID,$ZodCUID2,$ZodULID,$ZodXID,$ZodKSUID,$ZodISODateTime,$ZodISODate,$ZodISOTime,$ZodISODuration,$ZodIPv4,ipv6Alphabet,$ZodIPv6,$ZodCIDRv4,$ZodCIDRv6,base64Charset,$ZodBase64,base64urlCharset,$ZodBase64URL,$ZodE164,$ZodJWT,$ZodNumber,$ZodNumberFormat,$ZodBoolean,$ZodBigInt,$ZodNull,$ZodAny,$ZodUnknown,$ZodNever,$ZodDate,arraySize,$ZodArray,NO_SYMBOL_KEYS,$ZodObject,$ZodObjectJIT,$ZodUnion,$ZodDiscriminatedUnion,$ZodIntersection,$ZodRecord,$ZodEnum,$ZodLiteral,$ZodTransform,$ZodOptional,$ZodExactOptional,$ZodNullable,$ZodDefault,$ZodPrefault,$ZodNonOptional,$ZodCatch,$ZodPipe,$ZodPreprocess,$ZodReadonly,$ZodLazy,$ZodCustom,init_schemas=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js"(){"use strict";init_checks();init_core();init_doc();init_regexes();init_util();init_versions();init_util();$ZodType=$constructor("$ZodType",(inst,def)=>{var _a3;inst??(inst={}),inst._zod.def=def,inst._zod.bag=inst._zod.bag||{},inst._zod.version=version;let defChecks=inst._zod.def.checks,checks=inst._zod.traits.has("$ZodCheck")?[inst,...defChecks??[]]:defChecks?.length?[...defChecks]:[];for(let ch of checks)for(let fn of ch._zod.onattach)fn(inst);if(checks.length===0)(_a3=inst._zod).deferred??(_a3.deferred=[]),inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse});else{let runChecks=(payload,checks2,ctx)=>{if(payload.memo)return payload;let isAborted=aborted(payload),asyncResult;for(let ch of checks2){if(ch._zod.def.when){if(explicitlyAborted(payload)||!ch._zod.def.when(payload))continue}else if(isAborted)continue;let currLen=payload.issues.length,_=ch._zod.check(payload);if(_ instanceof Promise&&ctx?.async===!1)throw new $ZodAsyncError;if(asyncResult||_ instanceof Promise)asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _,payload.issues.length!==currLen&&(attachSchema(payload.issues,currLen,inst),isAborted||(isAborted=aborted(payload,currLen)))});else{if(payload.issues.length===currLen)continue;attachSchema(payload.issues,currLen,inst),isAborted||(isAborted=aborted(payload,currLen))}}return asyncResult?asyncResult.then(()=>payload):payload},handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary))return canary.aborted=!0,canary;let checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return checkResult.then(checkResult2=>inst._zod.parse(checkResult2,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks)return inst._zod.parse(payload,ctx);if(ctx.direction==="backward"){let canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:!0});return canary instanceof Promise?canary.then(canary2=>handleCanaryResult(canary2,payload,ctx)):handleCanaryResult(canary,payload,ctx)}let result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return result.then(result2=>runChecks(result2,checks,ctx))}return runChecks(result,checks,ctx)}}},{get"~standard"(){return hide(this,"~standard",standardProps(this))},set"~standard"(value){own(this,"~standard",value)}}),toStandardResult=(r,ctx)=>r.issues.length?{issues:r.issues.map(iss=>finalizeIssue(iss,ctx,config()))}:{value:r.value};$ZodString=$constructor("$ZodString",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=def.pattern??anyString,inst._zod.parse=(payload,_)=>{if(def.coerce)try{payload.value=String(payload.value)}catch{}return typeof payload.value=="string"||payload.issues.push({expected:"string",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodStringFormat=$constructor("$ZodStringFormat",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),$ZodString.init(inst,def)}),$ZodGUID=$constructor("$ZodGUID",(inst,def)=>{def.pattern??(def.pattern=guid),$ZodStringFormat.init(inst,def)}),$ZodUUID=$constructor("$ZodUUID",(inst,def)=>{if(def.version){let v={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[def.version];if(v===void 0)throw new Error(`Invalid UUID version: "${def.version}"`);def.pattern??(def.pattern=uuid(v))}else def.pattern??(def.pattern=uuid());$ZodStringFormat.init(inst,def)}),$ZodEmail=$constructor("$ZodEmail",(inst,def)=>{def.pattern??(def.pattern=email),$ZodStringFormat.init(inst,def)}),URL_BAD_FORMAT=1,URL_UNPARSEABLE=2;asciiTabOrNewline=/[\t\n\r]/g;$ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{try{let trimmed=payload.value.trim(),url2=validateURL(trimmed,def);if(url2===URL_BAD_FORMAT){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:payload.value,inst,continue:!def.abort});return}if(url2===URL_UNPARSEABLE){payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort});return}if(url2===!0){payload.value=stripTabAndNewline(trimmed);return}def.hostname&&!urlHostnameOk(url2,def.hostname)&&payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort}),def.protocol&&!urlProtocolOk(url2,def.protocol)&&payload.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort}),payload.value=def.normalize?url2.href:stripTabAndNewline(trimmed);return}catch{payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(inst,def)=>{def.pattern??(def.pattern=emoji()),$ZodStringFormat.init(inst,def)}),$ZodNanoID=$constructor("$ZodNanoID",(inst,def)=>{if(def.length!==void 0&&(!Number.isInteger(def.length)||def.length<1))throw new Error(`Invalid nanoid length: ${def.length}`);def.pattern??(def.pattern=def.length===void 0?nanoid:nanoidOfLength(def.length)),$ZodStringFormat.init(inst,def)}),$ZodCUID=$constructor("$ZodCUID",(inst,def)=>{def.pattern??(def.pattern=cuid),$ZodStringFormat.init(inst,def)}),$ZodCUID2=$constructor("$ZodCUID2",(inst,def)=>{def.pattern??(def.pattern=cuid2),$ZodStringFormat.init(inst,def)}),$ZodULID=$constructor("$ZodULID",(inst,def)=>{def.pattern??(def.pattern=ulid),$ZodStringFormat.init(inst,def)}),$ZodXID=$constructor("$ZodXID",(inst,def)=>{def.pattern??(def.pattern=xid),$ZodStringFormat.init(inst,def)}),$ZodKSUID=$constructor("$ZodKSUID",(inst,def)=>{def.pattern??(def.pattern=ksuid),$ZodStringFormat.init(inst,def)}),$ZodISODateTime=$constructor("$ZodISODateTime",(inst,def)=>{def.pattern??(def.pattern=datetime(def)),$ZodStringFormat.init(inst,def)}),$ZodISODate=$constructor("$ZodISODate",(inst,def)=>{def.pattern??(def.pattern=date),$ZodStringFormat.init(inst,def)}),$ZodISOTime=$constructor("$ZodISOTime",(inst,def)=>{def.pattern??(def.pattern=time(def)),$ZodStringFormat.init(inst,def)}),$ZodISODuration=$constructor("$ZodISODuration",(inst,def)=>{def.pattern??(def.pattern=duration),$ZodStringFormat.init(inst,def)}),$ZodIPv4=$constructor("$ZodIPv4",(inst,def)=>{def.pattern??(def.pattern=ipv4),$ZodStringFormat.init(inst,def)}),ipv6Alphabet=/^[0-9a-fA-F:.]+$/;$ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidIPv6(payload.value)||payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4),$ZodStringFormat.init(inst,def)});$ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidCIDRv6(payload.value)||payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}});base64Charset=/^[0-9a-zA-Z+/]*={0,2}$/,$ZodBase64=$constructor("$ZodBase64",(inst,def)=>{def.pattern??(def.pattern=base64Charset),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidBase64(payload.value)||payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}}),base64urlCharset=/^[A-Za-z0-9_-]*$/;$ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64urlCharset),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidBase64URL(payload.value)||payload.issues.push({code:"invalid_format",format:"base64url",input:payload.value,inst,continue:!def.abort})}}),$ZodE164=$constructor("$ZodE164",(inst,def)=>{def.pattern??(def.pattern=e164),$ZodStringFormat.init(inst,def)});$ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidJWT(payload.value,def.alg)||payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}}),$ZodNumber=$constructor("$ZodNumber",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=number,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Number(payload.value)}catch{}let input=payload.value;if(typeof input=="number"&&!Number.isNaN(input)&&Number.isFinite(input))return payload;let received=typeof input=="number"?Number.isNaN(input)?"NaN":Number.isFinite(input)?void 0:String(input):void 0;return payload.issues.push({expected:"number",code:"invalid_type",input,inst,...received?{received}:{}}),payload}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(inst,def)=>{$ZodCheckNumberFormat.init(inst,def),$ZodNumber.init(inst,def)}),$ZodBoolean=$constructor("$ZodBoolean",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=boolean,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=!!payload.value}catch{}let input=payload.value;return typeof input=="boolean"||payload.issues.push({expected:"boolean",code:"invalid_type",input,inst}),payload}}),$ZodBigInt=$constructor("$ZodBigInt",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=bigint,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=BigInt(payload.value)}catch{}return typeof payload.value=="bigint"||payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodNull=$constructor("$ZodNull",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_null,inst._zod.values=new Set([null]),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return input===null||payload.issues.push({expected:"null",code:"invalid_type",input,inst}),payload}}),$ZodAny=$constructor("$ZodAny",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodUnknown=$constructor("$ZodUnknown",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodNever=$constructor("$ZodNever",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>(payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst}),payload)}),$ZodDate=$constructor("$ZodDate",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=new Date(payload.value)}catch{}let input=payload.value,isDate=input instanceof Date;return isDate&&!Number.isNaN(input.getTime())||payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst}),payload}});arraySize=input=>Array.isArray(input)?input.length:-1;$ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def);let memo3=globalConfig.memoizer;memo3?.attach(inst),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({expected:"array",code:"invalid_type",input,inst}),payload;payload.value=memo3?memo3.alloc(inst,payload,Array(input.length),ctx):Array(input.length);let proms=[],abortEarly=ctx?.abortEarly;for(let i=0;i<input.length;i++){let item=input[i],result=def.element._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then(result2=>handleArrayResult(result2,payload,i)));else if(handleArrayResult(result,payload,i),abortEarly&&result.issues.length!==0&&aborted(result))break}return proms.length?Promise.all(proms).then(()=>payload):payload},capSize(inst,arraySize)});NO_SYMBOL_KEYS=[];$ZodObject=$constructor("$ZodObject",(inst,def)=>{$ZodType.init(inst,def);let desc=Object.getOwnPropertyDescriptor(def,"shape"),sh=desc?.get?desc.get.raw:def.shape??{};if(sh){let get=()=>{let newSh={...sh};return Object.defineProperty(def,"shape",{value:newSh}),get.raw=newSh,newSh};get.raw=sh,Object.defineProperty(def,"shape",{get})}let _normalized=cached(()=>normalizeDef(def));defineLazyInternal(inst,"propValues",zod=>{let shape=zod.def.shape,propValues={};for(let key in shape){let field=shape[key]._zod;if(field.values){Object.prototype.hasOwnProperty.call(propValues,key)||assignProp(propValues,key,new Set);for(let v of field.values)propValues[key].add(v);field.optin!==void 0&&propValues[key].add(void 0)}}return propValues});let isObject2=isObject,catchall=def.catchall,value,memo3=globalConfig.memoizer;memo3?.attach(inst),inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;payload.value=memo3?memo3.alloc(inst,payload,{},ctx):{};let proms=[],shape=value.shape,abortEarly=ctx?.abortEarly,seen=payload.issues.length;for(let key of value.allKeys){if(abortEarly&&payload.issues.length!==seen){if(aborted(payload,seen))break;seen=payload.issues.length}if(key==="__proto__")continue;let el=shape[key],optin=el._zod.optin,optout=el._zod.optout,r=el._zod.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,optin,optout))):handlePropertyResult(r,payload,key,input,optin,optout)}return catchall?handleCatchall(proms,input,payload,ctx,_normalized.value,inst,abortEarly===!0):proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);let superParse=inst._zod.parse,_normalized=cached(()=>normalizeDef(def)),memo3=globalConfig.memoizer,generateFastpass=shape=>{let normalized=_normalized.value,syms=normalized.symbolKeys,doc=new Doc(["payload","ctx"],{shape,inst,memo:memo3,syms}),parseStr=k=>`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`,prefixStr=(id,k)=>`
6
+ let ${id}_ab = false;
7
+ for (let i = 0; i < ${id}.issues.length; i++) {
8
+ const iss = ${id}.issues[i];
9
+ iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
10
+ payload.issues.push(iss);
11
+ if (iss.continue !== true) ${id}_ab = true;
10
12
  }
11
- }
12
-
13
- if (${id}.value === undefined) {
14
- if (${k} in input) {
15
- newResult[${k}] = undefined;
13
+ if (${id}_ab && ctx && ctx.abortEarly) {
14
+ payload.value = newResult;
15
+ return payload;
16
+ }`;doc.write("const input = payload.value;");let ids=Object.create(null),counter=0;for(let key of normalized.allKeys)ids[key]=`key_${counter++}`;doc.write(memo3?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let key of normalized.allKeys){if(key==="__proto__")continue;let id=ids[key],k=typeof key=="symbol"?`syms[${syms.indexOf(key)}]`:esc(key),isPresent=`${k} in input`,schema2=shape[key],optin=schema2?._zod?.optin,isOptionalIn=optin!==void 0,isOptionalOut=schema2?._zod?.optout==="optional";if(doc.write(`const ${id} = ${parseStr(k)};`),isOptionalIn&&isOptionalOut){let assign=optin==="optional"?`${id}_present`:`${id}.value !== undefined || ${id}_present`;doc.write(`
17
+ const ${id}_present = ${isPresent};
18
+ if (!${id}.issues.length || ${id}_present) {
19
+ if (${id}.issues.length) {${prefixStr(id,k)}
20
+ }
21
+
22
+ if (${assign}) {
23
+ newResult[${k}] = ${id}.value;
16
24
  }
17
- } else {
18
- newResult[${k}] = ${id}.value;
19
25
  }
20
-
21
- `):isOptionalIn?doc.write(`
22
- if (${id}.issues.length) {
23
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
24
- ...iss,
25
- path: iss.path ? [${k}, ...iss.path] : [${k}]
26
- })));
26
+
27
+ `)}else isOptionalIn?(doc.write(`
28
+ if (${id}.issues.length) {${prefixStr(id,k)}
27
29
  }
28
-
29
- if (${id}.value === undefined) {
30
- if (${k} in input) {
31
- newResult[${k}] = undefined;
32
- }
33
- } else {
30
+ `),optin==="defaulted"?doc.write(`newResult[${k}] = ${id}.value;`):doc.write(`
31
+ if (${id}.value !== undefined || ${isPresent}) {
34
32
  newResult[${k}] = ${id}.value;
35
33
  }
36
-
37
- `):doc.write(`
38
- const ${id}_present = ${k} in input;
39
- if (${id}.issues.length) {
40
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
41
- ...iss,
42
- path: iss.path ? [${k}, ...iss.path] : [${k}]
43
- })));
34
+ `)):doc.write(`
35
+ const ${id}_present = ${isPresent};
36
+ if (${id}.issues.length) {${prefixStr(id,k)}
44
37
  }
45
38
  if (!${id}_present && !${id}.issues.length) {
46
39
  payload.issues.push({
@@ -49,34 +42,34 @@ var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyN
49
42
  input: undefined,
50
43
  path: [${k}]
51
44
  });
45
+ if (ctx && ctx.abortEarly) {
46
+ payload.value = newResult;
47
+ return payload;
48
+ }
52
49
  }
53
50
 
54
51
  if (${id}_present) {
55
- if (${id}.value === undefined) {
56
- newResult[${k}] = undefined;
57
- } else {
58
- newResult[${k}] = ${id}.value;
59
- }
52
+ newResult[${k}] = ${id}.value;
60
53
  }
61
54
 
62
- `)}doc.write("payload.value = newResult;"),doc.write("return payload;");let fn=doc.compile();return(payload,ctx)=>fn(shape,payload,ctx)},fastpass,isObject2=isObject,jit=!globalConfig.jitless,fastEnabled=jit&&allowsEval.value,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;return isObject2(input)?jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0?(fastpass||(fastpass=generateFastpass(def.shape)),payload=fastpass(payload,ctx),catchall?handleCatchall([],input,payload,ctx,value,inst):payload):superParse(payload,ctx):(payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload)}});$ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.options.some(o=>o._zod.optin==="optional")?"optional":void 0),defineLazy(inst._zod,"optout",()=>def.options.some(o=>o._zod.optout==="optional")?"optional":void 0),defineLazy(inst._zod,"values",()=>{if(def.options.every(o=>o._zod.values))return new Set(def.options.flatMap(option=>Array.from(option._zod.values)))}),defineLazy(inst._zod,"pattern",()=>{if(def.options.every(o=>o._zod.pattern)){let patterns=def.options.map(o=>o._zod.pattern);return new RegExp(`^(${patterns.map(p=>cleanRegex(p.source)).join("|")})$`)}});let first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}return async?Promise.all(results).then(results2=>handleUnionResults(results2,payload,inst,ctx)):handleUnionResults(results,payload,inst,ctx)}}),$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=!1,$ZodUnion.init(inst,def);let _super=inst._zod.parse;defineLazy(inst._zod,"propValues",()=>{let propValues={};for(let option of def.options){let pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let[k,v]of Object.entries(pv)){propValues[k]||(propValues[k]=new Set);for(let val of v)propValues[k].add(val)}}return propValues});let disc=cached(()=>{let opts=def.options,map=new Map;for(let o of opts){let values=o._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);for(let v of values){if(map.has(v))throw new Error(`Duplicate discriminator value "${String(v)}"`);map.set(v,o)}}return map});inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isObject(input))return payload.issues.push({code:"invalid_type",expected:"object",input,inst}),payload;let opt=disc.value.get(input?.[def.discriminator]);return opt?opt._zod.run(payload,ctx):def.unionFallback||ctx.direction==="backward"?_super(payload,ctx):(payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,options:Array.from(disc.value.keys()),input,path:[def.discriminator],inst}),payload)}}),$ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);return left instanceof Promise||right instanceof Promise?Promise.all([left,right]).then(([left2,right2])=>handleIntersectionResults(payload,left2,right2)):handleIntersectionResults(payload,left,right)}});$ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isPlainObject(input))return payload.issues.push({expected:"record",code:"invalid_type",input,inst}),payload;let proms=[],values=def.keyType._zod.values;if(values){payload.value={};let recordKeys=new Set;for(let key of values)if(typeof key=="string"||typeof key=="number"||typeof key=="symbol"){recordKeys.add(typeof key=="number"?key.toString():key);let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(keyResult.issues.length){payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let outKey=keyResult.value,result=def.valueType._zod.run({value:input[key],issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>{result2.issues.length&&payload.issues.push(...prefixIssues(key,result2.issues)),payload.value[outKey]=result2.value})):(result.issues.length&&payload.issues.push(...prefixIssues(key,result.issues)),payload.value[outKey]=result.value)}let unrecognized;for(let key in input)recordKeys.has(key)||(unrecognized=unrecognized??[],unrecognized.push(key));unrecognized&&unrecognized.length>0&&payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized})}else{payload.value={};for(let key of Reflect.ownKeys(input)){if(key==="__proto__"||!Object.prototype.propertyIsEnumerable.call(input,key))continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof key=="string"&&number.test(key)&&keyResult.issues.length){let retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");retryResult.issues.length===0&&(keyResult=retryResult)}if(keyResult.issues.length){def.mode==="loose"?payload.value[key]=input[key]:payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>{result2.issues.length&&payload.issues.push(...prefixIssues(key,result2.issues)),payload.value[keyResult.value]=result2.value})):(result.issues.length&&payload.issues.push(...prefixIssues(key,result.issues)),payload.value[keyResult.value]=result.value)}}return proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);let values=getEnumValues(def.entries),valuesSet=new Set(values);inst._zod.values=valuesSet,inst._zod.pattern=new RegExp(`^(${values.filter(k=>propertyKeyTypes.has(typeof k)).map(o=>typeof o=="string"?escapeRegex(o):o.toString()).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return valuesSet.has(input)||payload.issues.push({code:"invalid_value",values,input,inst}),payload}}),$ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{if($ZodType.init(inst,def),def.values.length===0)throw new Error("Cannot create literal schema with no valid values");let values=new Set(def.values);inst._zod.values=values,inst._zod.pattern=new RegExp(`^(${def.values.map(o=>typeof o=="string"?escapeRegex(o):o?escapeRegex(o.toString()):String(o)).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return values.has(input)||payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}}),$ZodTransform=$constructor("$ZodTransform",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then(output2=>(payload.value=output2,payload.fallback=!0,payload));if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload.fallback=!0,payload}});$ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",inst._zod.optout="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values?new Set([...def.innerType._zod.values,void 0]):void 0),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin==="optional"){let input=payload.value,result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(r=>handleOptionalResult(r,input)):handleOptionalResult(result,input)}return payload.value===void 0?payload:def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(inst,def)=>{$ZodOptional.init(inst,def),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"pattern",()=>def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>def.innerType._zod.run(payload,ctx)}),$ZodNullable=$constructor("$ZodNullable",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazy(inst._zod,"values",()=>def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):void 0),inst._zod.parse=(payload,ctx)=>payload.value===null?payload:def.innerType._zod.run(payload,ctx)}),$ZodDefault=$constructor("$ZodDefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>handleDefaultResult(result2,def)):handleDefaultResult(result,def)}});$ZodPrefault=$constructor("$ZodPrefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>(ctx.direction==="backward"||payload.value===void 0&&(payload.value=def.defaultValue),def.innerType._zod.run(payload,ctx))}),$ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>{let v=def.innerType._zod.values;return v?new Set([...v].filter(x=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>handleNonOptionalResult(result2,inst)):handleNonOptionalResult(result,inst)}});$ZodCatch=$constructor("$ZodCatch",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>(payload.value=result2.value,result2.issues.length&&(payload.value=def.catchValue({...payload,error:{issues:result2.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[],payload.fallback=!0),payload)):(payload.value=result.value,result.issues.length&&(payload.value=def.catchValue({...payload,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[],payload.fallback=!0),payload)}}),$ZodPipe=$constructor("$ZodPipe",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>def.in._zod.values),defineLazy(inst._zod,"optin",()=>def.in._zod.optin),defineLazy(inst._zod,"optout",()=>def.out._zod.optout),defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){let right=def.out._zod.run(payload,ctx);return right instanceof Promise?right.then(right2=>handlePipeResult(right2,def.in,ctx)):handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);return left instanceof Promise?left.then(left2=>handlePipeResult(left2,def.out,ctx)):handlePipeResult(left,def.out,ctx)}});$ZodPreprocess=$constructor("$ZodPreprocess",(inst,def)=>{$ZodPipe.init(inst,def)}),$ZodReadonly=$constructor("$ZodReadonly",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"propValues",()=>def.innerType._zod.propValues),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"optin",()=>def.innerType?._zod?.optin),defineLazy(inst._zod,"optout",()=>def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(handleReadonlyResult):handleReadonlyResult(result)}});$ZodLazy=$constructor("$ZodLazy",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"innerType",()=>{let d=def;return d._cachedInner||(d._cachedInner=def.getter()),d._cachedInner}),defineLazy(inst._zod,"pattern",()=>inst._zod.innerType?._zod?.pattern),defineLazy(inst._zod,"propValues",()=>inst._zod.innerType?._zod?.propValues),defineLazy(inst._zod,"optin",()=>inst._zod.innerType?._zod?.optin??void 0),defineLazy(inst._zod,"optout",()=>inst._zod.innerType?._zod?.optout??void 0),inst._zod.parse=(payload,ctx)=>inst._zod.innerType._zod.run(payload,ctx)}),$ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>payload,inst._zod.check=payload=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then(r2=>handleRefineResult(r2,payload,input,inst));handleRefineResult(r,payload,input,inst)}})}});function en_default(){return{localeError:error()}}var error,init_en=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js"(){"use strict";init_util();error=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return`Invalid input: expected ${expected}, received ${received}`}case"invalid_value":return issue2.values.length===1?`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`:`Invalid option: expected one of ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Too big: expected ${issue2.origin??"value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"}`:`Too big: expected ${issue2.origin??"value"} to be ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Invalid string: must start with "${_issue.prefix}"`:_issue.format==="ends_with"?`Invalid string: must end with "${_issue.suffix}"`:_issue.format==="includes"?`Invalid string: must include "${_issue.includes}"`:_issue.format==="regex"?`Invalid string: must match pattern ${_issue.pattern}`:`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue2.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue2.origin}`;case"invalid_union":return issue2.options&&Array.isArray(issue2.options)&&issue2.options.length>0?`Invalid discriminator value. Expected ${issue2.options.map(o=>`'${o}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${issue2.origin}`;default:return"Invalid input"}}}}});var init_locales=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js"(){"use strict"}});function registry(){return new $ZodRegistry}var _a2,$ZodRegistry,globalRegistry,init_registries=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js"(){"use strict";$ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema2,..._meta){let meta2=_meta[0];return this._map.set(schema2,meta2),meta2&&typeof meta2=="object"&&"id"in meta2&&this._idmap.set(meta2.id,schema2),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema2){let meta2=this._map.get(schema2);return meta2&&typeof meta2=="object"&&"id"in meta2&&this._idmap.delete(meta2.id),this._map.delete(schema2),this}get(schema2){let p=schema2._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema2)};return Object.keys(f).length?f:void 0}return this._map.get(schema2)}has(schema2){return this._map.has(schema2)}};(_a2=globalThis).__zod_globalRegistry??(_a2.__zod_globalRegistry=registry());globalRegistry=globalThis.__zod_globalRegistry}});function _string(Class2,params){return new Class2({type:"string",...normalizeParams(params)})}function _coercedString(Class2,params){return new Class2({type:"string",coerce:!0,...normalizeParams(params)})}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2({type:"number",checks:[],...normalizeParams(params)})}function _coercedNumber(Class2,params){return new Class2({type:"number",coerce:!0,checks:[],...normalizeParams(params)})}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:!0,...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:!0,...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:!0,...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!1})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!0})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!1})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!0})}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite(input=>input.normalize(form))}function _trim(){return _overwrite(input=>input.trim())}function _toLowerCase(){return _overwrite(input=>input.toLowerCase())}function _toUpperCase(){return _overwrite(input=>input.toUpperCase())}function _slugify(){return _overwrite(input=>slugify(input))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _refine(Class2,fn,_params){return new Class2({type:"custom",check:"custom",fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch=_check(payload=>(payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(issue(_issue))}},fn(payload.value,payload)),params);return ch}function _check(fn,params){let ch=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch._zod.check=fn,ch}var init_api=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js"(){"use strict";init_checks();init_util()}});function initializeContext(params){let target=params?.target??"draft-2020-12";return target==="draft-4"&&(target="draft-04"),target==="draft-7"&&(target="draft-07"),{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,cycles:params?.cycles??"ref",reused:params?.reused??"inline",external:params?.external??void 0}}function process2(schema2,ctx,_params={path:[],schemaPath:[]}){var _a3;let def=schema2._zod.def,seen=ctx.seen.get(schema2);if(seen)return seen.count++,_params.schemaPath.includes(schema2)&&(seen.cycle=_params.path),seen.schema;let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema2,result);let overrideSchema=schema2._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema2],path:_params.path};if(schema2._zod.processJSONSchema)schema2._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema2,ctx,_json,params)}let parent=schema2._zod.parent;parent&&(result.ref||(result.ref=parent),process2(parent,ctx,params),ctx.seen.get(parent).isParent=!0)}let meta2=ctx.metadataRegistry.get(schema2);return meta2&&Object.assign(result.schema,meta2),ctx.io==="input"&&isTransforming(schema2)&&(delete result.schema.examples,delete result.schema.default),ctx.io==="input"&&"_prefault"in result.schema&&((_a3=result.schema).default??(_a3.default=result.schema._prefault)),delete result.schema._prefault,ctx.seen.get(schema2).schema}function extractDefs(ctx,schema2){let root=ctx.seen.get(schema2);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=entry=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??(id2=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${id}`}}if(entry[1]===root)return{ref:"#"};let defUriPrefix=`#/${defsSegment}/`,defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+defId}},extractToDef=entry=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);seen.def={...seen.schema},defId&&(seen.defId=defId);let schema3=seen.schema;for(let key in schema3)delete schema3[key];schema3.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
55
+ `)}return doc.write("payload.value = newResult;"),doc.write("return payload;"),doc.compile()},fastpass,isObject2=isObject,jit=!globalConfig.jitless,fastEnabled=jit&&allowsEval.value,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;return isObject2(input)?jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0?(fastpass||(fastpass=generateFastpass(def.shape)),payload=fastpass(payload,ctx),catchall?handleCatchall([],input,payload,ctx,value,inst,ctx?.abortEarly===!0):payload):superParse(payload,ctx):(payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload)}});$ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",zod=>zod.def.options.some(o=>o._zod.optin==="defaulted")?"defaulted":zod.def.options.some(o=>o._zod.optin!==void 0)?"optional":void 0),defineLazyInternal(inst,"optout",zod=>zod.def.options.some(o=>o._zod.optout==="optional")?"optional":void 0),defineLazyInternal(inst,"values",zod=>{if(zod.def.options.every(o=>o._zod.values))return new Set(zod.def.options.flatMap(option=>Array.from(option._zod.values)))}),defineLazyInternal(inst,"pattern",zod=>{if(zod.def.options.every(o=>o._zod.pattern)){let patterns=zod.def.options.map(o=>o._zod.pattern);return new RegExp(`^(${patterns.map(p=>cleanRegex(p.source)).join("|")})$`)}});let first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}return async?Promise.all(results).then(results2=>handleUnionResults(results2,payload,inst,ctx)):handleUnionResults(results,payload,inst,ctx)}});$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=!1,$ZodUnion.init(inst,def);let _super=inst._zod.parse;defineLazyInternal(inst,"propValues",zod=>{let propValues={},undefinedCount=0;for(let option of zod.def.options){let pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);pv[zod.def.discriminator]?.has(void 0)&&undefinedCount++;for(let[k,v]of Object.entries(pv)){Object.prototype.hasOwnProperty.call(propValues,k)||assignProp(propValues,k,new Set);for(let val of v)propValues[k].add(val)}}return!zod.def.unionFallback&&undefinedCount>1&&propValues[zod.def.discriminator]?.delete(void 0),propValues}),def.options.forEach((option,i)=>{let propShape=rawShape(option._zod.def);if(propShape&&!Object.prototype.hasOwnProperty.call(propShape,def.discriminator))throw new Error(`Invalid discriminated union option at index "${i}"`)});let disc=cached(()=>discriminatorMap(def));inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isObject(input))return payload.issues.push({code:"invalid_type",expected:"object",input,inst}),payload;let value=input?.[def.discriminator],opt=disc.value.get(value);return opt&&(value!==void 0||ctx.direction!=="backward")?opt._zod.run(payload,ctx):def.unionFallback||ctx.direction==="backward"?_super(payload,ctx):(payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,options:Array.from(disc.value.keys()).filter(value2=>disc.value.get(value2)!==null),input,path:[def.discriminator],inst}),payload)}}),$ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);return left instanceof Promise||right instanceof Promise?Promise.all([left,right]).then(([left2,right2])=>handleIntersectionResults(payload,left2,right2)):handleIntersectionResults(payload,left,right)}});$ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def);let memo3=globalConfig.memoizer;memo3?.attach(inst),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isPlainObject(input))return payload.issues.push({expected:"record",code:"invalid_type",input,inst}),payload;let proms=[],values=def.keyType._zod.values;if(values&&!def.partial){payload.value=memo3?memo3.alloc(inst,payload,{},ctx):{};let recordKeys=new Set;for(let key of values)if(typeof key=="string"||typeof key=="number"||typeof key=="symbol"){if(recordKeys.add(typeof key=="number"?key.toString():key),key==="__proto__")continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(keyResult.issues.length){payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let outKey=keyResult.value;if(outKey==="__proto__")continue;let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>{result2.issues.length&&payload.issues.push(...prefixIssues(key,result2.issues)),payload.value[outKey]=result2.value})):(result.issues.length&&payload.issues.push(...prefixIssues(key,result.issues)),payload.value[outKey]=result.value)}let unrecognized;for(let key in input)if(!recordKeys.has(key))if(def.mode==="loose"){if(key==="__proto__")continue;payload.value[key]=input[key]}else unrecognized=unrecognized??[],unrecognized.push(key);unrecognized&&unrecognized.length>0&&payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized,continue:!0})}else{payload.value=memo3?memo3.alloc(inst,payload,{},ctx):{};let unrecognized;for(let key of Reflect.ownKeys(input)){if(key==="__proto__"||!Object.prototype.propertyIsEnumerable.call(input,key))continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof key=="string"&&number.test(key)&&keyResult.issues.length){let retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");retryResult.issues.length===0&&(keyResult=retryResult)}if(keyResult.issues.length){def.mode==="loose"?payload.value[key]=input[key]:values?(unrecognized=unrecognized??[],unrecognized.push(key)):payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let outKey=keyResult.value;if(outKey==="__proto__")continue;let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>{result2.issues.length&&payload.issues.push(...prefixIssues(key,result2.issues)),payload.value[outKey]=result2.value})):(result.issues.length&&payload.issues.push(...prefixIssues(key,result.issues)),payload.value[outKey]=result.value)}unrecognized&&unrecognized.length>0&&payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized,continue:!0})}return proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);let values=getEnumValues(def.entries),valuesSet=new Set(values);inst._zod.values=valuesSet,defineLazyInternal(inst,"pattern",zod=>{let patternValues=getEnumValues(zod.def.entries).filter(k=>propertyKeyTypes.has(typeof k));return new RegExp(patternValues.length?`^(${patternValues.map(o=>escapeRegex(o.toString())).join("|")})$`:"^[^\\s\\S]$")}),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return valuesSet.has(input)||payload.issues.push({code:"invalid_value",values,input,inst}),payload}}),$ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{$ZodType.init(inst,def);let values=new Set(def.values);inst._zod.values=values,defineLazyInternal(inst,"pattern",zod=>{let vals=zod.def.values;return new RegExp(vals.length?`^(${vals.map(o=>typeof o=="string"?escapeRegex(o):o?escapeRegex(o.toString()):String(o)).join("|")})$`:"^[^\\s\\S]$")}),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return values.has(input)||payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}}),$ZodTransform=$constructor("$ZodTransform",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",globalConfig.memoizer?.guard(inst),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then(output2=>(payload.value=output2,payload));if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload}});$ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",zod=>zod.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),inst._zod.optout="optional",defineLazyInternal(inst,"values",zod=>{let values=zod.def.innerType._zod.values;return values?new Set([...values,void 0]):void 0}),defineLazyInternal(inst,"pattern",zod=>{let pattern=zod.def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(payload.value===void 0){if(def.innerType._zod.optin!=="defaulted")return payload;let result=def.innerType._zod.run({value:payload.value,issues:[]},ctx);return result instanceof Promise?result.then(result2=>handleOptionalResult(payload,result2)):handleOptionalResult(payload,result)}return def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(inst,def)=>{$ZodOptional.init(inst,def),defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values),defineLazyInternal(inst,"pattern",zod=>zod.def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>def.innerType._zod.run(payload,ctx)}),$ZodNullable=$constructor("$ZodNullable",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",zod=>zod.def.innerType._zod.optin),defineLazyInternal(inst,"optout",zod=>zod.def.innerType._zod.optout),defineLazyInternal(inst,"pattern",zod=>{let pattern=zod.def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values?new Set([...zod.def.innerType._zod.values,null]):void 0),inst._zod.parse=(payload,ctx)=>payload.value===null?payload:def.innerType._zod.run(payload,ctx)}),$ZodDefault=$constructor("$ZodDefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="defaulted",defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>handleDefaultResult(result2,def)):handleDefaultResult(result,def)}});$ZodPrefault=$constructor("$ZodPrefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="defaulted",defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>(ctx.direction==="backward"||payload.value===void 0&&(payload.value=def.defaultValue),def.innerType._zod.run(payload,ctx))}),$ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"values",zod=>{let v=zod.def.innerType._zod.values;return v?new Set([...v].filter(x=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>handleNonOptionalResult(result2,inst)):handleNonOptionalResult(result,inst)}});$ZodCatch=$constructor("$ZodCatch",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",zod=>zod.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),defineLazyInternal(inst,"optout",zod=>zod.def.innerType._zod.optout),defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run({value:payload.value,issues:[]},ctx);return result instanceof Promise?result.then(result2=>handleCatchResult(payload,result2,def,ctx)):handleCatchResult(payload,result,def,ctx)}}),$ZodPipe=$constructor("$ZodPipe",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"values",zod=>zod.def.in._zod.values),defineLazyInternal(inst,"optin",zod=>zod.def.in._zod.optin),defineLazyInternal(inst,"optout",zod=>zod.def.out._zod.optout),defineLazyInternal(inst,"propValues",zod=>zod.def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){let right=def.out._zod.run(payload,ctx);return right instanceof Promise?right.then(right2=>handlePipeResult(right2,def.in,ctx)):handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);return left instanceof Promise?left.then(left2=>handlePipeResult(left2,def.out,ctx)):handlePipeResult(left,def.out,ctx)}});$ZodPreprocess=$constructor("$ZodPreprocess",(inst,def)=>{$ZodPipe.init(inst,def)}),$ZodReadonly=$constructor("$ZodReadonly",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"propValues",zod=>zod.def.innerType._zod.propValues),defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values),defineLazyInternal(inst,"optin",zod=>zod.def.innerType?._zod?.optin),defineLazyInternal(inst,"optout",zod=>zod.def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(handleReadonlyResult):handleReadonlyResult(result)}});$ZodLazy=$constructor("$ZodLazy",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"innerType",()=>{let d=def;return d._cachedInner||(d._cachedInner=def.getter()),d._cachedInner}),defineLazyInternal(inst,"pattern",zod=>zod.innerType?._zod?.pattern),defineLazyInternal(inst,"propValues",zod=>zod.innerType?._zod?.propValues),defineLazyInternal(inst,"optin",zod=>zod.innerType?._zod?.optin??void 0),defineLazyInternal(inst,"optout",zod=>zod.innerType?._zod?.optout??void 0),inst._zod.parse=(payload,ctx)=>inst._zod.innerType._zod.run(payload,ctx)}),$ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>payload,inst._zod.check=payload=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then(r2=>handleRefineResult(r2,payload,input,inst));handleRefineResult(r,payload,input,inst)}})}});function isRef(value){return value!==null&&typeof value=="object"}function cloneIssues(issues){return issues.map(iss=>iss.path?{...iss,path:iss.path.slice()}:{...iss})}function isRecursive(inst,stack,resolve){let cached2=recursive.get(inst);if(cached2!==void 0)return cached2?PROVEN:NONE;if(stack.has(inst))return PROVEN;stack.add(inst);let result=NONE,check=child=>{if(result!==PROVEN&&child?._zod){let answer=isRecursive(child,stack,resolve);answer>result&&(result=answer)}},shape=(sh,spread)=>{let answer=NONE;for(let key of Reflect.ownKeys(sh)){let desc=Object.getOwnPropertyDescriptor(sh,key);if(spread&&!desc.enumerable)continue;let child=desc.get?ASSUMED:desc.value?._zod?isRecursive(desc.value,stack,resolve):NONE;child>answer&&(answer=child)}return answer},merge2=answer=>{answer>result&&(result=answer)},def=inst._zod.def,kind=def.type;switch(kind){case"object":{let raw2=rawShape(def);merge2(raw2?shape(raw2,!0):ASSUMED),check(def.catchall);break}case"array":check(def.element);break;case"tuple":for(let el of def.items)check(el);check(def.rest);break;case"record":case"map":check(def.keyType),check(def.valueType);break;case"set":check(def.valueType);break;case"union":for(let el of def.options)check(el);break;case"intersection":check(def.left),check(def.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":check(def.innerType);break;case"pipe":check(def.in),check(def.out);break;case"function":check(def.input),check(def.output);break;case"lazy":{let inner=def._cachedInner??(resolve?inst._zod.innerType:void 0);merge2(inner?isRecursive(inner,stack,!1):ASSUMED);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let key in def){let desc=Object.getOwnPropertyDescriptor(def,key);if(!desc||desc.get)continue;let value=desc.value;if(!(!value||typeof value!="object")){if(value._zod)check(value);else if(Array.isArray(value))for(let el of value)check(el)}}}return stack.delete(inst),settle(inst,result)}function settle(inst,answer){return answer!==ASSUMED&&recursive.set(inst,answer===PROVEN),answer}function bucketFor(state,inst){let bucket=state.buckets.get(inst);return bucket||(bucket=new WeakMap,state.buckets.set(inst,bucket)),bucket}function memoizer(){return memo}function isBackEdge(ctx,value){let backEdges=ctx[STATE]?.backEdges;return backEdges!==void 0&&isRef(value)&&backEdges.has(value)}var $ZodCyclicError,STATE,NO_ISSUES,recursive,NONE,ASSUMED,PROVEN,handoff,open,memo,init_memoizer=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js"(){"use strict";init_util();$ZodCyclicError=class extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}},STATE="~memo",NO_ISSUES=[];recursive=new WeakMap,NONE=0,ASSUMED=1,PROVEN=2;open=[],memo={alloc(_inst,payload,empty){let bucket=handoff;if(!bucket)return empty;handoff=void 0;let entry={value:empty,issues:null};return bucket.set(payload.value,entry),open.push(entry),empty},guard(inst){var _a3;(_a3=inst._zod).deferred??(_a3.deferred=[]),inst._zod.deferred.push(()=>{let base=inst._zod.parse,wrapped=(payload,ctx)=>{if(ctx.direction!=="backward"&&isBackEdge(ctx,payload.value))throw new $ZodCyclicError;return base(payload,ctx)};inst._zod.parse=wrapped,inst._zod.run===base&&(inst._zod.run=wrapped)})},attach(inst){var _a3;let isRecursiveInst,rechecked=!1,lastCtx,lastBucket;(_a3=inst._zod).deferred??(_a3.deferred=[]),inst._zod.deferred.push(()=>{let base=inst._zod.parse,wrapped=(payload,ctx)=>{if(isRecursiveInst===void 0){let walked=isRecursive(inst,new Set,!1);if(walked===NONE)return inst._zod.parse=base,inst._zod.run===wrapped&&(inst._zod.run=base),base(payload,ctx);walked===PROVEN||rechecked?isRecursiveInst=!0:rechecked=!0}let input=payload.value;if(!isRef(input))return base(payload,ctx);let state=ctx[STATE];state||(state={buckets:new WeakMap,backEdges:void 0},ctx[STATE]=state);let bucket;lastCtx===ctx?bucket=lastBucket:(bucket=bucketFor(state,inst),lastCtx=ctx,lastBucket=bucket);let hit=bucket.get(input);if(hit)return payload.value=hit.value,hit.issues?hit.issues.length&&payload.issues.push(...cloneIssues(hit.issues)):(payload.memo=!0,state.backEdges??(state.backEdges=new WeakSet),state.backEdges.add(hit.value)),payload;handoff=bucket;let depth=open.length,result=base(payload,ctx);handoff=void 0;let entry=open.length>depth?open.pop():void 0;return result instanceof Promise?result.then(r=>(entry&&(entry.issues=r.issues.length?cloneIssues(r.issues):NO_ISSUES),r)):(entry&&(entry.issues=result.issues.length?cloneIssues(result.issues):NO_ISSUES),result)};inst._zod.parse=wrapped,inst._zod.run===base&&(inst._zod.run=wrapped)})}}}});function en_default(){return{localeError:error()}}var error,init_en=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js"(){"use strict";init_util();error=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};function getTypeName(type,input){return type==="number"&&typeof input=="number"&&!Number.isFinite(input)?String(input):TypeDictionary[type]??type}return issue2=>{switch(issue2.code){case"invalid_type":{let expected=getTypeName(issue2.expected),receivedType=parsedType(issue2.input),received=getTypeName(receivedType,issue2.input);return`Invalid input: expected ${expected}, received ${received}`}case"invalid_value":return issue2.values.length===1?`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`:`Invalid option: expected one of ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.exact?"exactly ":issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Too big: expected ${issue2.origin??"value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"}`:`Too big: expected ${issue2.origin??"value"} to be ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.exact?"exactly ":issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Invalid string: must start with "${_issue.prefix}"`:_issue.format==="ends_with"?`Invalid string: must end with "${_issue.suffix}"`:_issue.format==="includes"?`Invalid string: must include "${_issue.includes}"`:_issue.format==="regex"?`Invalid string: must match pattern ${_issue.pattern}`:`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue2.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue2.origin}`;case"invalid_union":return issue2.options&&Array.isArray(issue2.options)&&issue2.options.length>0?`Invalid discriminator value. Expected ${issue2.options.map(o=>`'${o}'`).join(" | ")}`:issue2.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${issue2.origin}`;default:return"Invalid input"}}}}});var init_locales=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js"(){"use strict"}});function registry(){return new $ZodRegistry}var _a2,$ZodRegistry,globalRegistry,init_registries=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js"(){"use strict";$ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema2,..._meta){let meta2=_meta[0];return this._map.set(schema2,meta2),meta2&&typeof meta2=="object"&&"id"in meta2&&this._idmap.set(meta2.id,schema2),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema2){let meta2=this._map.get(schema2);return meta2&&typeof meta2=="object"&&"id"in meta2&&this._idmap.delete(meta2.id),this._map.delete(schema2),this}get(schema2){let p=schema2._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema2)};return Object.keys(f).length?f:void 0}return this._map.get(schema2)}has(schema2){return this._map.has(schema2)}};(_a2=globalThis).__zod_globalRegistry??(_a2.__zod_globalRegistry=registry());globalRegistry=globalThis.__zod_globalRegistry}});var init_compile=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js"(){"use strict"}});function snapshotChecks(def){return def.checks&&(def.checks=[...def.checks]),def}function _string(Class2,params){return new Class2(snapshotChecks({type:"string",...normalizeParams(params)}))}function _coercedString(Class2,params){return new Class2(snapshotChecks({type:"string",coerce:!0,...normalizeParams(params)}))}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _coercedNumber(Class2,params){return new Class2(snapshotChecks({type:"number",coerce:!0,checks:[],...normalizeParams(params)}))}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:!0,...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:!0,...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:!0,...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!1})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!0})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!1})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!0})}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite(input=>input.normalize(form))}function _trim(){return _overwrite(input=>input.trim())}function _toLowerCase(){return _overwrite(input=>input.toLowerCase())}function _toUpperCase(){return _overwrite(input=>input.toUpperCase())}function _slugify(){return _overwrite(input=>slugify(input))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _refine(Class2,fn,_params){return new Class2({type:"custom",check:"custom",fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch=_check(payload=>(payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(issue(_issue))}},fn(payload.value,payload)),params);return ch}function _check(fn,params){let ch=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch._zod.check=fn,ch}var init_api=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js"(){"use strict";init_checks();init_util()}});function assignProps(target,...sources){for(let source of sources)for(let key of Reflect.ownKeys(source))Object.prototype.propertyIsEnumerable.call(source,key)&&assignProp(target,key,source[key]);return target}function initializeContext(params){let target=params?.target??"draft-2020-12";return target==="draft-4"&&(target="draft-04"),target==="draft-7"&&(target="draft-07"),{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??void 0}}function handleUnrepresentable(schema2,ctx,json,params,message){let result=typeof ctx.unrepresentable=="function"?ctx.unrepresentable({zodSchema:schema2,path:params.path,message}):ctx.unrepresentable;if(result==="any")return!1;if(result===void 0||result==="throw")throw new Error(message);return Object.assign(json,result),!0}function processSchema(schema2,ctx,_params={path:[],schemaPath:[]}){var _a3;let def=schema2._zod.def,seen=ctx.seen.get(schema2);if(seen)return seen.count++,_params.schemaPath.includes(schema2)&&(seen.cycle=_params.path),seen.schema;let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema2,result),ctx.sharedDefsExtractedFor=void 0,ctx.sharedEmitDoneFor=void 0;let overrideSchema=schema2._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema2],path:_params.path};if(schema2._zod.processJSONSchema)schema2._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema2,ctx,_json,params)}let parent=schema2._zod.parent;parent&&(result.ref||(result.ref=parent),processSchema(parent,ctx,params),ctx.seen.get(parent).isParent=!0)}let meta2=ctx.metadataRegistry.get(schema2);return meta2&&assignProps(result.schema,meta2),ctx.io==="input"&&isTransforming(schema2)&&(delete result.schema.examples,delete result.schema.default),ctx.io==="input"&&"_prefault"in result.schema&&((_a3=result.schema).default??(_a3.default=result.schema._prefault)),delete result.schema._prefault,ctx.seen.get(schema2).schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema2){let root=ctx.seen.get(schema2);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=entry=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??(id2=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}let uriPrefix="#",defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id)return{ref:uriPrefix};let defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}},extractToDef=entry=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);seen.def={...seen.schema},defId&&(seen.defId=defId);let schema3=seen.schema;for(let key in schema3)delete schema3[key];schema3.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
63
56
 
64
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema2===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema2!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1&&ctx.reused==="ref"){extractToDef(entry);continue}}}function finalize(ctx,schema2){let root=ctx.seen.get(schema2);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema3=seen.def??seen.schema,_cached={...schema3},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema3.allOf=schema3.allOf??[],schema3.allOf.push(refSchema)):Object.assign(schema3,refSchema),Object.assign(schema3,_cached),zodSchema._zod.parent===ref)for(let key in schema3)key==="$ref"||key==="allOf"||key in _cached||delete schema3[key];if(refSchema.$ref&&refSeen.def)for(let key in schema3)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema3[key])===JSON.stringify(refSeen.def[key])&&delete schema3[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema3.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema3)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema3[key])===JSON.stringify(parentSeen.def[key])&&delete schema3[key]}ctx.override({zodSchema,jsonSchema:schema3,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema2)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema2)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,defs[seen.defId]=seen.def)}ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema2["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema2,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema2,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var createToJSONSchemaMethod,createStandardJSONSchemaMethod,init_to_json_schema=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js"(){"use strict";init_registries();createToJSONSchemaMethod=(schema2,processors={})=>params=>{let ctx=initializeContext({...params,processors});return process2(schema2,ctx),extractDefs(ctx,schema2),finalize(ctx,schema2)},createStandardJSONSchemaMethod=(schema2,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process2(schema2,ctx),extractDefs(ctx,schema2),finalize(ctx,schema2)}}});function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema2]=entry;process2(schema2,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema2]=entry;extractDefs(ctx2,schema2),schemas[key]=finalize(ctx2,schema2)}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return process2(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var formatMap,stringProcessor,numberProcessor,booleanProcessor,bigintProcessor,symbolProcessor,nullProcessor,undefinedProcessor,voidProcessor,neverProcessor,anyProcessor,unknownProcessor,dateProcessor,enumProcessor,literalProcessor,nanProcessor,templateLiteralProcessor,fileProcessor,successProcessor,customProcessor,functionProcessor,transformProcessor,mapProcessor,setProcessor,arrayProcessor,objectProcessor,unionProcessor,intersectionProcessor,tupleProcessor,recordProcessor,nullableProcessor,nonoptionalProcessor,defaultProcessor,prefaultProcessor,catchProcessor,pipeProcessor,readonlyProcessor,promiseProcessor,optionalProcessor,lazyProcessor,allProcessors,init_json_schema_processors=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js"(){"use strict";init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},stringProcessor=(schema2,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema2._zod.bag;if(typeof minimum=="number"&&(json.minLength=minimum),typeof maximum=="number"&&(json.maxLength=maximum),format&&(json.format=formatMap[format]??format,json.format===""&&delete json.format,format==="time"&&delete json.format),contentEncoding&&(json.contentEncoding=contentEncoding),patterns&&patterns.size>0){let regexes=[...patterns];regexes.length===1?json.pattern=regexes[0].source:regexes.length>1&&(json.allOf=[...regexes.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema2,ctx,_json,_params)=>{let json=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema2._zod.bag;typeof format=="string"&&format.includes("int")?json.type="integer":json.type="number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";exMin?legacy?(json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0):json.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json.minimum=minimum),exMax?legacy?(json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0):json.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json.maximum=maximum),typeof multipleOf=="number"&&(json.multipleOf=multipleOf)},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{ctx.target==="openapi-3.0"?(json.type="string",json.nullable=!0,json.enum=[null]):json.type="null"},undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},enumProcessor=(schema2,_ctx,json,_params)=>{let def=schema2._zod.def,values=getEnumValues(def.entries);values.every(v=>typeof v=="number")&&(json.type="number"),values.every(v=>typeof v=="string")&&(json.type="string"),json.enum=values},literalProcessor=(schema2,ctx,json,_params)=>{let def=schema2._zod.def,vals=[];for(let val of def.values)if(val===void 0){if(ctx.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val=="bigint"){if(ctx.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json.enum=[val]:json.const=val}else vals.every(v=>typeof v=="number")&&(json.type="number"),vals.every(v=>typeof v=="string")&&(json.type="string"),vals.every(v=>typeof v=="boolean")&&(json.type="boolean"),vals.every(v=>v===null)&&(json.type="null"),json.enum=vals},nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema2,_ctx,json,_params)=>{let _json=json,pattern=schema2._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema2,_ctx,json,_params)=>{let _json=json,file={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema2._zod.bag;minimum!==void 0&&(file.minLength=minimum),maximum!==void 0&&(file.maxLength=maximum),mime?mime.length===1?(file.contentMediaType=mime[0],Object.assign(_json,file)):(Object.assign(_json,file),_json.anyOf=mime.map(m=>({contentMediaType:m}))):Object.assign(_json,file)},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},arrayProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def,{minimum,maximum}=schema2._zod.bag;typeof minimum=="number"&&(json.minItems=minimum),typeof maximum=="number"&&(json.maxItems=maximum),json.type="array",json.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})},objectProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="object",json.properties={};let shape=def.shape;for(let key in shape)json.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter(key=>{let v=def.shape[key]._zod;return ctx.io==="input"?v.optin===void 0:v.optout===void 0}));requiredKeys.size>0&&(json.required=Array.from(requiredKeys)),def.catchall?._zod.def.type==="never"?json.additionalProperties=!1:def.catchall?def.catchall&&(json.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json.additionalProperties=!1)},unionProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));isExclusive?json.oneOf=options:json.anyOf=options},intersectionProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf},tupleProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;ctx.target==="draft-2020-12"?(json.prefixItems=prefixItems,rest&&(json.items=rest)):ctx.target==="openapi-3.0"?(json.items={anyOf:prefixItems},rest&&json.items.anyOf.push(rest),json.minItems=prefixItems.length,rest||(json.maxItems=prefixItems.length)):(json.items=prefixItems,rest&&(json.additionalItems=rest));let{minimum,maximum}=schema2._zod.bag;typeof minimum=="number"&&(json.minItems=minimum),typeof maximum=="number"&&(json.maxItems=maximum)},recordProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="object";let keyType=def.keyType,patterns=keyType._zod.bag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)json.patternProperties[pattern.source]=valueSchema}else(ctx.target==="draft-07"||ctx.target==="draft-2020-12")&&(json.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]})),json.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]});let keyValues=keyType._zod.values;if(keyValues){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json.required=validKeyValues)}},nullableProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,inner=process2(def.innerType,ctx,params),seen=ctx.seen.get(schema2);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json.nullable=!0):json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},defaultProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType,ctx.io==="input"&&(json._prefault=JSON.parse(JSON.stringify(def.defaultValue)))},catchProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}json.default=catchValue},pipeProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;process2(innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=innerType},readonlyProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},optionalProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},lazyProcessor=(schema2,ctx,_json,params)=>{let innerType=schema2._zod.innerType;process2(innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}}});var init_json_schema=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js"(){"use strict"}});var init_core2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js"(){"use strict";init_core();init_parse();init_errors();init_schemas();init_checks();init_versions();init_util();init_regexes();init_locales();init_registries();init_doc();init_api();init_to_json_schema();init_json_schema()}});var init_checks2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js"(){"use strict";init_core2()}});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date2,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration,init_iso=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js"(){"use strict";init_core2();init_schemas2();ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)})}});var initializer2,ZodRealError,init_errors2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js"(){"use strict";init_core2();init_core2();init_util();initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:mapper=>formatError(inst,mapper)},flatten:{value:mapper=>flattenError(inst,mapper)},addIssue:{value:issue2=>{inst.issues.push(issue2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:issues2=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodRealError=$constructor("ZodError",initializer2,{Parent:Error})}});var parse2,parseAsync2,safeParse2,safeParseAsync2,encode,decode,encodeAsync,decodeAsync,safeEncode,safeDecode,safeEncodeAsync,safeDecodeAsync,init_parse2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js"(){"use strict";init_core2();init_errors2();parse2=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError)}});function _installLazyMethods(inst,group,methods){let proto=Object.getPrototypeOf(inst),installed=_installedGroups.get(proto);if(installed||(installed=new Set,_installedGroups.set(proto,installed)),!installed.has(group)){installed.add(group);for(let key in methods){let fn=methods[key];Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let bound=fn.bind(this);return Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:bound}),bound},set(v){Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:v})}})}}}function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function url(params){return _url(ZodURL,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function array(element,params){return _array(ZodArray,element,params)}function object(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function _enum(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}function transform(fn){return new ZodTransform({type:"transform",transform:fn})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function _default(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}function _catch(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:()=>catchValue})}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function preprocess(fn,schema2){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema2})}var _installedGroups,ZodType,_ZodString,ZodString,ZodStringFormat,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodDate,ZodArray,ZodObject,ZodUnion,ZodDiscriminatedUnion,ZodIntersection,ZodRecord,ZodEnum,ZodLiteral,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodCatch,ZodPipe,ZodPreprocess,ZodReadonly,ZodLazy,ZodCustom,init_schemas2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js"(){"use strict";init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_checks2();init_iso();init_parse2();_installedGroups=new WeakMap;ZodType=$constructor("ZodType",(inst,def)=>($ZodType.init(inst,def),Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.parse=(data,params)=>parse2(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse2(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode(inst,data,params),inst.decode=(data,params)=>decode(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync(inst,data,params),inst.safeEncode=(data,params)=>safeEncode(inst,data,params),inst.safeDecode=(data,params)=>safeDecode(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync(inst,data,params),_installLazyMethods(inst,"ZodType",{check(...chks){let def2=this.def;return this.clone(util_exports.mergeDefs(def2,{checks:[...def2.checks??[],...chks.map(ch=>typeof ch=="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def2,params){return clone(this,def2,params)},brand(){return this},register(reg,meta2){return reg.add(this,meta2),this},refine(check,params){return this.check(refine(check,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn){return fn(this)}}),Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst)),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,_installLazyMethods(inst,"_ZodString",{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=params=>inst.check(_email(ZodEmail,params)),inst.url=params=>inst.check(_url(ZodURL,params)),inst.jwt=params=>inst.check(_jwt(ZodJWT,params)),inst.emoji=params=>inst.check(_emoji2(ZodEmoji,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.uuid=params=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=params=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=params=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=params=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=params=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.cuid=params=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=params=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=params=>inst.check(_ulid(ZodULID,params)),inst.base64=params=>inst.check(_base64(ZodBase64,params)),inst.base64url=params=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=params=>inst.check(_xid(ZodXID,params)),inst.ksuid=params=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=params=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=params=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=params=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=params=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=params=>inst.check(_e164(ZodE164,params)),inst.datetime=params=>inst.check(datetime2(params)),inst.date=params=>inst.check(date2(params)),inst.time=params=>inst.check(time2(params)),inst.duration=params=>inst.check(duration2(params))});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)}),ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)}),ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)}),ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)}),ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)}),ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),_installLazyMethods(inst,"ZodNumber",{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}});let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=params=>inst.check(_gt(BigInt(0),params)),inst.negative=params=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=params=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=params=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null}),ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>dateProcessor(inst,ctx,json,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null}),ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,_installLazyMethods(inst,"ZodArray",{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}})});ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),util_exports.defineLazy(inst,"shape",()=>def.shape),_installLazyMethods(inst,"ZodObject",{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone({...this._zod.def,catchall})},passthrough(){return this.clone({...this._zod.def,catchall:unknown()})},loose(){return this.clone({...this._zod.def,catchall:unknown()})},strict(){return this.clone({...this._zod.def,catchall:never()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}})});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys2=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys2.has(value))newEntries[value]=def.entries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys2.has(value))delete newEntries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output=def.transform(payload.value,payload);return output instanceof Promise?output.then(output2=>(payload.value=output2,payload.fallback=!0,payload)):(payload.value=output,payload.fallback=!0,payload)}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>lazyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.getter()});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)})}});var ZodIssueCode,ZodFirstPartyTypeKind,init_compat=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js"(){"use strict";ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={})}});var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint2,boolean:()=>boolean3,date:()=>date3,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint2(params){return _coercedBigint(ZodBigInt,params)}function date3(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js"(){"use strict";init_core2();init_schemas2()}});var init_external=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js"(){"use strict";init_core2();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();init_core2();init_en();init_core2();init_json_schema_processors();init_locales();init_iso();init_coerce();config(en_default())}});var init_classic=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/index.js"(){"use strict";init_external()}});var init_v4=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/index.js"(){"use strict";init_classic()}});var LATEST_PROTOCOL_VERSION,DEFAULT_NEGOTIATED_PROTOCOL_VERSION,SUPPORTED_PROTOCOL_VERSIONS,RELATED_TASK_META_KEY,PROTOCOL_VERSION_META_KEY,CLIENT_INFO_META_KEY,SERVER_INFO_META_KEY,CLIENT_CAPABILITIES_META_KEY,SUBSCRIPTION_ID_META_KEY,LOG_LEVEL_META_KEY,JSONRPC_VERSION,INVALID_PARAMS,JSONValueSchema,JSONObjectSchema,JSONArraySchema,ProgressTokenSchema,CursorSchema,TaskMetadataSchema,RelatedTaskMetadataSchema,RequestMetaSchema,BaseRequestParamsSchema,TaskAugmentedRequestParamsSchema,RequestSchema,NotificationsParamsSchema,NotificationSchema,ResultMetaObjectSchema,ResultSchema,RequestIdSchema,JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema,JSONRPCMessageSchema,JSONRPCResponseSchema,EmptyResultSchema,CancelledNotificationParamsSchema,CancelledNotificationSchema,IconSchema,IconsSchema,BaseMetadataSchema,ImplementationSchema,FormElicitationCapabilitySchema,ElicitationCapabilitySchema,ClientTasksCapabilitySchema,ServerTasksCapabilitySchema,ClientCapabilitiesSchema,InitializeRequestParamsSchema,InitializeRequestSchema,ServerCapabilitiesSchema,InitializeResultSchema,InitializedNotificationSchema,DiscoverRequestSchema,DiscoverResultSchema,PingRequestSchema,ProgressSchema,ProgressNotificationParamsSchema,ProgressNotificationSchema,PaginatedRequestParamsSchema,PaginatedRequestSchema,PaginatedResultSchema,ResourceContentsSchema,TextResourceContentsSchema,Base64Schema,BlobResourceContentsSchema,RoleSchema,AnnotationsSchema,ResourceSchema,ResourceTemplateSchema,ListResourcesRequestSchema,ListResourcesResultSchema,ListResourceTemplatesRequestSchema,ListResourceTemplatesResultSchema,ResourceRequestParamsSchema,ReadResourceRequestParamsSchema,ReadResourceRequestSchema,ReadResourceResultSchema,ResourceListChangedNotificationSchema,SubscribeRequestParamsSchema,SubscribeRequestSchema,UnsubscribeRequestParamsSchema,UnsubscribeRequestSchema,SubscriptionFilterSchema,SubscriptionsListenRequestParamsSchema,SubscriptionsListenRequestSchema,SubscriptionsAcknowledgedNotificationParamsSchema,SubscriptionsAcknowledgedNotificationSchema,SubscriptionsListenResultMetaSchema,SubscriptionsListenResultSchema,ResourceUpdatedNotificationParamsSchema,ResourceUpdatedNotificationSchema,PromptArgumentSchema,PromptSchema,ListPromptsRequestSchema,ListPromptsResultSchema,GetPromptRequestParamsSchema,GetPromptRequestSchema,TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,EmbeddedResourceSchema,ResourceLinkSchema,ContentBlockSchema,PromptMessageSchema,GetPromptResultSchema,PromptListChangedNotificationSchema,ToolAnnotationsSchema,ToolExecutionSchema,ToolSchema,ListToolsRequestSchema,ListToolsResultSchema,CallToolResultSchema,CompatibilityCallToolResultSchema,CallToolRequestParamsSchema,CallToolRequestSchema,ToolListChangedNotificationSchema,ListChangedOptionsBaseSchema,LoggingLevelSchema,SetLevelRequestParamsSchema,SetLevelRequestSchema,LoggingMessageNotificationParamsSchema,LoggingMessageNotificationSchema,ModelHintSchema,ModelPreferencesSchema,ToolChoiceSchema,ToolResultContentSchema,SamplingContentSchema,SamplingMessageContentBlockSchema,SamplingMessageSchema,CreateMessageRequestParamsSchema,CreateMessageRequestSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema,UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema,LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema,EnumSchemaSchema,PrimitiveSchemaDefinitionSchema,ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema,ElicitRequestParamsSchema,ElicitRequestSchema,ElicitationCompleteNotificationParamsSchema,ElicitationCompleteNotificationSchema,ElicitResultSchema,ResourceTemplateReferenceSchema,PromptReferenceSchema,CompleteRequestParamsSchema,CompleteRequestSchema,CompleteResultSchema,RootSchema,ListRootsRequestSchema,ListRootsResultSchema,RootsListChangedNotificationSchema,TaskCreationParamsSchema,TaskStatusSchema,TaskSchema,CreateTaskResultSchema,TaskStatusNotificationParamsSchema,TaskStatusNotificationSchema,GetTaskRequestSchema,GetTaskResultSchema,GetTaskPayloadRequestSchema,GetTaskPayloadResultSchema,ListTasksRequestSchema,ListTasksResultSchema,CancelTaskRequestSchema,CancelTaskResultSchema,ClientRequestSchema,ClientNotificationSchema,ClientResultSchema,ServerRequestSchema,ServerNotificationSchema,ServerResultSchema,SafeUrlSchema,OAuthProtectedResourceMetadataSchema,OAuthMetadataSchema,OpenIdProviderMetadataSchema,OpenIdProviderDiscoveryMetadataSchema,OAuthTokensSchema,IdJagTokenExchangeResponseSchema,OAuthErrorResponseSchema,OptionalSafeUrlSchema,OAuthClientMetadataSchema,OAuthClientInformationSchema,OAuthClientInformationFullSchema,OAuthClientRegistrationErrorSchema,OAuthTokenRevocationRequestSchema,init_auth_BNDyLTqp=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+core@2.3.1/node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs"(){"use strict";init_v4();LATEST_PROTOCOL_VERSION="2025-11-25",DEFAULT_NEGOTIATED_PROTOCOL_VERSION="2025-03-26",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",PROTOCOL_VERSION_META_KEY="io.modelcontextprotocol/protocolVersion",CLIENT_INFO_META_KEY="io.modelcontextprotocol/clientInfo",SERVER_INFO_META_KEY="io.modelcontextprotocol/serverInfo",CLIENT_CAPABILITIES_META_KEY="io.modelcontextprotocol/clientCapabilities",SUBSCRIPTION_ID_META_KEY="io.modelcontextprotocol/subscriptionId",LOG_LEVEL_META_KEY="io.modelcontextprotocol/logLevel",JSONRPC_VERSION="2.0",INVALID_PARAMS=-32602,JSONValueSchema=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema),array(JSONValueSchema)])),JSONObjectSchema=record(string2(),JSONValueSchema),JSONArraySchema=array(JSONValueSchema),ProgressTokenSchema=union([string2(),number2().int()]),CursorSchema=string2(),TaskMetadataSchema=object({ttl:number2().optional()}),RelatedTaskMetadataSchema=object({taskId:string2()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),RequestSchema=object({method:string2(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object({_meta:RequestMetaSchema.optional()}),NotificationSchema=object({method:string2(),params:NotificationsParamsSchema.loose().optional()}),ResultMetaObjectSchema=looseObject({get[SERVER_INFO_META_KEY](){return ImplementationSchema.optional().catch(void 0)}}),ResultSchema=looseObject({_meta:ResultMetaObjectSchema.optional()}),RequestIdSchema=union([string2(),number2().int()]),JSONRPCRequestSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),JSONRPCNotificationSchema=object({jsonrpc:literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),JSONRPCResultResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),JSONRPCErrorResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:object({code:number2().int(),message:string2(),data:unknown().optional()})}).strict(),JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string2().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema=object({icons:array(IconSchema).optional()}),BaseMetadataSchema=object({name:string2(),title:string2().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema),ElicitationCapabilitySchema=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema.optional(),url:JSONObjectSchema.optional()}),JSONObjectSchema.optional())),ClientTasksCapabilitySchema=looseObject({list:JSONObjectSchema.optional(),cancel:JSONObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:JSONObjectSchema.optional(),cancel:JSONObjectSchema.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object({experimental:record(string2(),JSONObjectSchema).optional(),sampling:object({context:JSONObjectSchema.optional(),tools:JSONObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string2(),JSONObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal("initialize"),params:InitializeRequestParamsSchema}),ServerCapabilitiesSchema=object({experimental:record(string2(),JSONObjectSchema).optional(),logging:JSONObjectSchema.optional(),completions:JSONObjectSchema.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string2(),JSONObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string2().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()}),DiscoverRequestSchema=RequestSchema.extend({method:literal("server/discover"),params:BaseRequestParamsSchema.optional()}),DiscoverResultSchema=ResultSchema.extend({supportedVersions:array(string2()),capabilities:ServerCapabilitiesSchema,instructions:string2().optional()}),PingRequestSchema=RequestSchema.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema=object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),ResourceContentsSchema=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string2()}),Base64Schema=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum(["user","assistant"]),AnnotationsSchema=object({audience:array(RoleSchema).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string2()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),SubscriptionFilterSchema=object({toolsListChanged:boolean2().optional(),promptsListChanged:boolean2().optional(),resourcesListChanged:boolean2().optional(),resourceSubscriptions:array(string2()).optional()}),SubscriptionsListenRequestParamsSchema=BaseRequestParamsSchema.extend({notifications:SubscriptionFilterSchema}),SubscriptionsListenRequestSchema=RequestSchema.extend({method:literal("subscriptions/listen"),params:SubscriptionsListenRequestParamsSchema}),SubscriptionsAcknowledgedNotificationParamsSchema=NotificationsParamsSchema.extend({notifications:SubscriptionFilterSchema}),SubscriptionsAcknowledgedNotificationSchema=NotificationSchema.extend({method:literal("notifications/subscriptions/acknowledged"),params:SubscriptionsAcknowledgedNotificationParamsSchema}),SubscriptionsListenResultMetaSchema=ResultMetaObjectSchema.extend({[SUBSCRIPTION_ID_META_KEY]:RequestIdSchema}),SubscriptionsListenResultSchema=ResultSchema.extend({_meta:SubscriptionsListenResultMetaSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string2()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string2(),arguments:record(string2(),string2()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema=object({type:literal("image"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema=object({type:literal("audio"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema=object({type:literal("resource"),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal("resource_link")}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string2().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolExecutionSchema=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string2().optional(),inputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:looseObject({$schema:string2().optional()}).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string2(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:unknown().optional(),isError:boolean2().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string2(),arguments:record(string2(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object({autoRefresh:boolean2().default(!0),debounceMs:number2().int().nonnegative().default(300)}),LoggingLevelSchema=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object({name:string2().optional()}),ModelPreferencesSchema=object({hints:array(ModelHintSchema).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema=object({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema),structuredContent:unknown().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string2(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema),required:array(string2()).optional()}).catchall(unknown())}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string2()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional())}),ResourceTemplateReferenceSchema=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema=object({type:literal("ref/prompt"),name:string2()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema}),CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})}),RootSchema=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),TaskCreationParamsSchema=looseObject({ttl:number2().optional(),pollInterval:number2().optional()}),TaskStatusSchema=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=object({taskId:string2(),status:TaskStatusSchema,ttl:union([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,DiscoverRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,SubscriptionsListenRequestSchema,CallToolRequestSchema,ListToolsRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,SubscriptionsAcknowledgedNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,DiscoverResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,SubscriptionsListenResultSchema]),SafeUrlSchema=url().superRefine((val,ctx)=>{if(!URL.canParse(val))return ctx.addIssue({code:ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),NEVER}).refine(url2=>{let u=new URL(url2);return u.protocol!=="javascript:"&&u.protocol!=="data:"&&u.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),OAuthProtectedResourceMetadataSchema=looseObject({resource:string2().url(),authorization_servers:array(SafeUrlSchema).optional(),jwks_uri:string2().url().optional(),scopes_supported:array(string2()).optional(),bearer_methods_supported:array(string2()).optional(),resource_signing_alg_values_supported:array(string2()).optional(),resource_name:string2().optional(),resource_documentation:string2().optional(),resource_policy_uri:string2().url().optional(),resource_tos_uri:string2().url().optional(),tls_client_certificate_bound_access_tokens:boolean2().optional(),authorization_details_types_supported:array(string2()).optional(),dpop_signing_alg_values_supported:array(string2()).optional(),dpop_bound_access_tokens_required:boolean2().optional()}),OAuthMetadataSchema=looseObject({issuer:string2(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array(string2()).optional(),response_types_supported:array(string2()),response_modes_supported:array(string2()).optional(),grant_types_supported:array(string2()).optional(),token_endpoint_auth_methods_supported:array(string2()).optional(),token_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),service_documentation:SafeUrlSchema.optional(),revocation_endpoint:SafeUrlSchema.optional(),revocation_endpoint_auth_methods_supported:array(string2()).optional(),revocation_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),introspection_endpoint:string2().optional(),introspection_endpoint_auth_methods_supported:array(string2()).optional(),introspection_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),code_challenge_methods_supported:array(string2()).optional(),client_id_metadata_document_supported:boolean2().optional(),authorization_response_iss_parameter_supported:boolean2().optional().catch(void 0),dpop_signing_alg_values_supported:array(string2()).optional()}),OpenIdProviderMetadataSchema=looseObject({issuer:string2(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,userinfo_endpoint:SafeUrlSchema.optional(),jwks_uri:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array(string2()).optional(),response_types_supported:array(string2()),response_modes_supported:array(string2()).optional(),grant_types_supported:array(string2()).optional(),acr_values_supported:array(string2()).optional(),subject_types_supported:array(string2()),id_token_signing_alg_values_supported:array(string2()),id_token_encryption_alg_values_supported:array(string2()).optional(),id_token_encryption_enc_values_supported:array(string2()).optional(),userinfo_signing_alg_values_supported:array(string2()).optional(),userinfo_encryption_alg_values_supported:array(string2()).optional(),userinfo_encryption_enc_values_supported:array(string2()).optional(),request_object_signing_alg_values_supported:array(string2()).optional(),request_object_encryption_alg_values_supported:array(string2()).optional(),request_object_encryption_enc_values_supported:array(string2()).optional(),token_endpoint_auth_methods_supported:array(string2()).optional(),token_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),display_values_supported:array(string2()).optional(),claim_types_supported:array(string2()).optional(),claims_supported:array(string2()).optional(),service_documentation:string2().optional(),claims_locales_supported:array(string2()).optional(),ui_locales_supported:array(string2()).optional(),claims_parameter_supported:boolean2().optional(),request_parameter_supported:boolean2().optional(),request_uri_parameter_supported:boolean2().optional(),require_request_uri_registration:boolean2().optional(),op_policy_uri:SafeUrlSchema.optional(),op_tos_uri:SafeUrlSchema.optional(),client_id_metadata_document_supported:boolean2().optional(),authorization_response_iss_parameter_supported:boolean2().optional().catch(void 0)}),OpenIdProviderDiscoveryMetadataSchema=object({...OpenIdProviderMetadataSchema.shape,...OAuthMetadataSchema.pick({code_challenge_methods_supported:!0}).shape}),OAuthTokensSchema=object({access_token:string2(),id_token:string2().optional(),token_type:string2(),expires_in:coerce_exports.number().optional(),scope:string2().optional(),refresh_token:string2().optional(),issuer:string2().optional().catch(void 0)}).strip(),IdJagTokenExchangeResponseSchema=object({issued_token_type:literal("urn:ietf:params:oauth:token-type:id-jag"),access_token:string2(),token_type:string2().optional(),expires_in:number2().optional(),scope:string2().optional()}).strip(),OAuthErrorResponseSchema=object({error:string2(),error_description:string2().optional(),error_uri:string2().optional()}),OptionalSafeUrlSchema=SafeUrlSchema.optional().or(literal("").transform(()=>{})),OAuthClientMetadataSchema=object({redirect_uris:array(SafeUrlSchema),token_endpoint_auth_method:string2().optional(),grant_types:array(string2()).optional(),response_types:array(string2()).optional(),application_type:string2().optional(),client_name:string2().optional(),client_uri:SafeUrlSchema.optional(),logo_uri:OptionalSafeUrlSchema,scope:string2().optional(),contacts:array(string2()).optional(),tos_uri:OptionalSafeUrlSchema,policy_uri:string2().optional(),jwks_uri:SafeUrlSchema.optional(),jwks:any().optional(),software_id:string2().optional(),software_version:string2().optional(),software_statement:string2().optional()}).strip(),OAuthClientInformationSchema=object({client_id:string2(),client_secret:string2().optional(),client_id_issued_at:number2().optional(),client_secret_expires_at:number2().optional(),issuer:string2().optional().catch(void 0)}).strip(),OAuthClientInformationFullSchema=OAuthClientMetadataSchema.merge(OAuthClientInformationSchema),OAuthClientRegistrationErrorSchema=object({error:string2(),error_description:string2().optional()}).strip(),OAuthTokenRevocationRequestSchema=object({token:string2(),token_type_hint:string2().optional()}).strip()}});var init_internal=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+core@2.3.1/node_modules/@modelcontextprotocol/core/dist/internal.mjs"(){"use strict";init_auth_BNDyLTqp()}});function stampErrorBrands(instance,ctor){let brands=new Set,current=ctor;for(;typeof current=="function";){let brand=current.mcpBrand;Object.prototype.hasOwnProperty.call(current,"mcpBrand")&&typeof brand=="string"&&brands.add(brand),current=Object.getPrototypeOf(current)}brands.size!==0&&Object.defineProperty(instance,BRANDS,{value:brands,enumerable:!1,configurable:!0})}function brandedHasInstance(cls,value){try{if(typeof value=="object"&&value!==null&&Object.prototype.hasOwnProperty.call(cls,"mcpBrand")&&typeof cls.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(value,BRANDS)){let carried=value[BRANDS];if(carried&&typeof carried.has=="function"&&carried.has(cls.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(cls,value)}function requiredClientCapabilitiesForRequest(method){return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD,method)?REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method]:void 0}function isPlainObject$7(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isImpliedCapabilityMember(capability,member,declaredValue){return capability==="elicitation"&&member==="form"&&declaredValue.form===void 0&&declaredValue.url===void 0}function requiredClientCapabilitiesForInputRequest(entry){switch(entry.method){case"elicitation/create":return entry.params?.mode==="url"?{elicitation:{url:{}}}:{elicitation:{form:{}}};case"sampling/createMessage":{let params=entry.params;return params!==void 0&&(params.tools!==void 0||params.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case"roots/list":return{roots:{}};default:return}}function missingClientCapabilities(required2,declared){let missing={};for(let[capability,requirement]of Object.entries(required2)){if(requirement===void 0)continue;let declaredValue=declared===void 0?void 0:declared[capability];if(declaredValue===void 0){missing[capability]=requirement;continue}if(isPlainObject$7(requirement)&&isPlainObject$7(declaredValue)){let missingMembers={};for(let[member,memberRequirement]of Object.entries(requirement))memberRequirement!==void 0&&declaredValue[member]===void 0&&!isImpliedCapabilityMember(capability,member,declaredValue)&&(missingMembers[member]=memberRequirement);Object.keys(missingMembers).length>0&&(missing[capability]=missingMembers)}}return Object.keys(missing).length>0?missing:void 0}function isModernProtocolVersion(version2){return version2>=FIRST_MODERN_PROTOCOL_VERSION}function legacyProtocolVersions(versions){return versions.filter(version2=>!isModernProtocolVersion(version2))}function modernProtocolVersions(versions){return versions.filter(version2=>isModernProtocolVersion(version2))}function appendTextFallbackForNonObject(result){let sc=result.structuredContent;return sc===void 0||!(typeof sc!="object"||sc===null||Array.isArray(sc))||(result.content?.some(c=>c.type==="text")??!1)?result:{...result,content:[...result.content??[],{type:"text",text:JSON.stringify(sc)}]}}function normalizeContentlessToolResult(value){return value===null||typeof value!="object"||Array.isArray(value)||value.content!==void 0||TOOL_RESULT_FOREIGN_FAMILY_KEYS.some(key=>key in value)?value:{...value,content:[]}}function build$1(){let JSONValueSchema$1=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema$1),array(JSONValueSchema$1)])),JSONObjectSchema$1=record(string2(),JSONValueSchema$1),ProgressTokenSchema$1=union([string2(),number2().int()]),CursorSchema$1=string2(),TaskMetadataSchema$1=object({ttl:number2().optional()}),RelatedTaskMetadataSchema$1=object({taskId:string2()}),RequestMetaSchema$1=looseObject({progressToken:ProgressTokenSchema$1.optional(),"io.modelcontextprotocol/related-task":RelatedTaskMetadataSchema$1.optional()}),BaseRequestParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),TaskAugmentedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({task:TaskMetadataSchema$1.optional()}),RequestSchema$1=object({method:string2(),params:BaseRequestParamsSchema$1.loose().optional()}),NotificationsParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),NotificationSchema$1=object({method:string2(),params:NotificationsParamsSchema$1.loose().optional()}),ResultSchema$1=looseObject({_meta:RequestMetaSchema$1.optional()}),RequestIdSchema$1=union([string2(),number2().int()]),EmptyResultSchema$1=ResultSchema$1.strict(),CancelledNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({requestId:RequestIdSchema$1.optional(),reason:string2().optional()}),CancelledNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema$1}),IconSchema$1=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema$1=object({icons:array(IconSchema$1).optional()}),BaseMetadataSchema$1=object({name:string2(),title:string2().optional()}),ImplementationSchema$1=BaseMetadataSchema$1.extend({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema2=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema$1),ElicitationCapabilitySchema2=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema2.optional(),url:JSONObjectSchema$1.optional()}),JSONObjectSchema$1.optional())),ClientTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema$1.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema$1.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema$1.optional()}).optional()}).optional()}),ClientCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),sampling:object({context:JSONObjectSchema$1.optional(),tools:JSONObjectSchema$1.optional()}).optional(),elicitation:ElicitationCapabilitySchema2.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),InitializeRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema$1,clientInfo:ImplementationSchema$1}),InitializeRequestSchema$1=RequestSchema$1.extend({method:literal("initialize"),params:InitializeRequestParamsSchema$1}),ServerCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),logging:JSONObjectSchema$1.optional(),completions:JSONObjectSchema$1.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),InitializeResultSchema$1=ResultSchema$1.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema$1,serverInfo:ImplementationSchema$1,instructions:string2().optional()}),InitializedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema$1.optional()}),PingRequestSchema$1=RequestSchema$1.extend({method:literal("ping"),params:BaseRequestParamsSchema$1.optional()}),ProgressSchema$1=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema$1=object({...NotificationsParamsSchema$1.shape,...ProgressSchema$1.shape,progressToken:ProgressTokenSchema$1}),ProgressNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema$1}),PaginatedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({cursor:CursorSchema$1.optional()}),PaginatedRequestSchema$1=RequestSchema$1.extend({params:PaginatedRequestParamsSchema$1.optional()}),PaginatedResultSchema$1=ResultSchema$1.extend({nextCursor:CursorSchema$1.optional()}),ResourceContentsSchema$1=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema$1=ResourceContentsSchema$1.extend({text:string2()}),Base64Schema2=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema$1=ResourceContentsSchema$1.extend({blob:Base64Schema2}),RoleSchema$1=_enum(["user","assistant"]),AnnotationsSchema$1=object({audience:array(RoleSchema$1).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("resources/list")}),ListResourcesResultSchema$1=PaginatedResultSchema$1.extend({resources:array(ResourceSchema$1)}),ListResourceTemplatesRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema$1=PaginatedResultSchema$1.extend({resourceTemplates:array(ResourceTemplateSchema$1)}),ResourceRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({uri:string2()}),ReadResourceRequestParamsSchema$1=ResourceRequestParamsSchema$1,ReadResourceRequestSchema$1=RequestSchema$1.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema$1}),ReadResourceResultSchema$1=ResultSchema$1.extend({contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),ResourceListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema$1.optional()}),SubscribeRequestParamsSchema$1=ResourceRequestParamsSchema$1,SubscribeRequestSchema$1=RequestSchema$1.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema$1}),UnsubscribeRequestParamsSchema$1=ResourceRequestParamsSchema$1,UnsubscribeRequestSchema$1=RequestSchema$1.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema$1}),ResourceUpdatedNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({uri:string2()}),ResourceUpdatedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema$1}),PromptArgumentSchema$1=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema$1)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("prompts/list")}),ListPromptsResultSchema$1=PaginatedResultSchema$1.extend({prompts:array(PromptSchema$1)}),GetPromptRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({name:string2(),arguments:record(string2(),string2()).optional()}),GetPromptRequestSchema$1=RequestSchema$1.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema$1}),TextContentSchema$1=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema$1=object({type:literal("image"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema$1=object({type:literal("audio"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema$1=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema$1=object({type:literal("resource"),resource:union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema$1=ResourceSchema$1.extend({type:literal("resource_link")}),ContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ResourceLinkSchema$1,EmbeddedResourceSchema$1]),PromptMessageSchema$1=object({role:RoleSchema$1,content:ContentBlockSchema$1}),GetPromptResultSchema$1=ResultSchema$1.extend({description:string2().optional(),messages:array(PromptMessageSchema$1)}),PromptListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema$1.optional()}),ToolAnnotationsSchema$1=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolExecutionSchema$1=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:string2().optional(),inputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema$1).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema$1).optional(),required:array(string2()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema$1.optional(),execution:ToolExecutionSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ListToolsRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("tools/list")}),ListToolsResultSchema$1=PaginatedResultSchema$1.extend({tools:array(ToolSchema$1)}),CallToolResultSchema$1=ResultSchema$1.extend({content:array(ContentBlockSchema$1),structuredContent:record(string2(),unknown()).optional(),isError:boolean2().optional()}),CallToolRequestParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({name:string2(),arguments:record(string2(),unknown()).optional()}),CallToolRequestSchema$1=RequestSchema$1.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema$1}),ToolListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema$1.optional()}),LoggingLevelSchema$1=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({level:LoggingLevelSchema$1}),SetLevelRequestSchema$1=RequestSchema$1.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema$1}),LoggingMessageNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({level:LoggingLevelSchema$1,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema$1}),ModelHintSchema$1=object({name:string2().optional()}),ModelPreferencesSchema$1=object({hints:array(ModelHintSchema$1).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema$1=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema$1=object({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema$1),structuredContent:object({}).loose().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingContentSchema$1=discriminatedUnion("type",[TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1]),SamplingMessageContentBlockSchema$1=discriminatedUnion("type",[TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ToolUseContentSchema$1,ToolResultContentSchema$1]),SamplingMessageSchema$1=object({role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)]),_meta:record(string2(),unknown()).optional()}),CreateMessageRequestParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({messages:array(SamplingMessageSchema$1),modelPreferences:ModelPreferencesSchema$1.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema$1.optional(),tools:array(ToolSchema$1).optional(),toolChoice:ToolChoiceSchema$1.optional()}),CreateMessageRequestSchema$1=RequestSchema$1.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema$1}),CreateMessageResultSchema$1=ResultSchema$1.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema$1,content:SamplingContentSchema$1}),CreateMessageResultWithToolsSchema$1=ResultSchema$1.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)])}),BooleanSchemaSchema$1=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema$1=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema$1=union([UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema$1]),UntitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema$1=union([UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema$1]),EnumSchemaSchema$1=union([LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema$1]),PrimitiveSchemaDefinitionSchema$1=union([EnumSchemaSchema$1,BooleanSchemaSchema$1,StringSchemaSchema$1,NumberSchemaSchema$1]),ElicitRequestFormParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema$1),required:array(string2()).optional()}).catchall(unknown())}),ElicitRequestURLParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()}),ElicitRequestParamsSchema$1=union([ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema$1]),ElicitRequestSchema$1=RequestSchema$1.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema$1}),ElicitationCompleteNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({elicitationId:string2()}),ElicitationCompleteNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema$1}),ElicitResultSchema$1=ResultSchema$1.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional())}),ResourceTemplateReferenceSchema$1=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema$1=object({type:literal("ref/prompt"),name:string2()}),CompleteRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({ref:union([PromptReferenceSchema$1,ResourceTemplateReferenceSchema$1]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()}),CompleteRequestSchema$1=RequestSchema$1.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema$1}),CompleteResultSchema$1=ResultSchema$1.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})}),RootSchema$1=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),ListRootsRequestSchema$1=RequestSchema$1.extend({method:literal("roots/list"),params:BaseRequestParamsSchema$1.optional()}),ListRootsResultSchema$1=ResultSchema$1.extend({roots:array(RootSchema$1)}),RootsListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema$1.optional()}),TaskCreationParamsSchema$1=looseObject({ttl:number2().optional(),pollInterval:number2().optional()}),TaskStatusSchema$1=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema$1=object({taskId:string2(),status:TaskStatusSchema$1,ttl:union([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())}),CreateTaskResultSchema$1=ResultSchema$1.extend({task:TaskSchema$1}),TaskStatusNotificationParamsSchema$1=NotificationsParamsSchema$1.merge(TaskSchema$1),TaskStatusNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema$1}),GetTaskRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})}),GetTaskResultSchema$1=ResultSchema$1.merge(TaskSchema$1),GetTaskPayloadRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})}),GetTaskPayloadResultSchema$1=ResultSchema$1.loose(),ListTasksRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("tasks/list")}),ListTasksResultSchema$1=PaginatedResultSchema$1.extend({tasks:array(TaskSchema$1)}),CancelTaskRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})});return{JSONValueSchema:JSONValueSchema$1,JSONObjectSchema:JSONObjectSchema$1,ProgressTokenSchema:ProgressTokenSchema$1,CursorSchema:CursorSchema$1,TaskMetadataSchema:TaskMetadataSchema$1,RelatedTaskMetadataSchema:RelatedTaskMetadataSchema$1,RequestMetaSchema:RequestMetaSchema$1,BaseRequestParamsSchema:BaseRequestParamsSchema$1,TaskAugmentedRequestParamsSchema:TaskAugmentedRequestParamsSchema$1,RequestSchema:RequestSchema$1,NotificationsParamsSchema:NotificationsParamsSchema$1,NotificationSchema:NotificationSchema$1,ResultSchema:ResultSchema$1,RequestIdSchema:RequestIdSchema$1,EmptyResultSchema:EmptyResultSchema$1,CancelledNotificationParamsSchema:CancelledNotificationParamsSchema$1,CancelledNotificationSchema:CancelledNotificationSchema$1,IconSchema:IconSchema$1,IconsSchema:IconsSchema$1,BaseMetadataSchema:BaseMetadataSchema$1,ImplementationSchema:ImplementationSchema$1,ClientTasksCapabilitySchema:ClientTasksCapabilitySchema$1,ServerTasksCapabilitySchema:ServerTasksCapabilitySchema$1,ClientCapabilitiesSchema:ClientCapabilitiesSchema$1,InitializeRequestParamsSchema:InitializeRequestParamsSchema$1,InitializeRequestSchema:InitializeRequestSchema$1,ServerCapabilitiesSchema:ServerCapabilitiesSchema$1,InitializeResultSchema:InitializeResultSchema$1,InitializedNotificationSchema:InitializedNotificationSchema$1,PingRequestSchema:PingRequestSchema$1,ProgressSchema:ProgressSchema$1,ProgressNotificationParamsSchema:ProgressNotificationParamsSchema$1,ProgressNotificationSchema:ProgressNotificationSchema$1,PaginatedRequestParamsSchema:PaginatedRequestParamsSchema$1,PaginatedRequestSchema:PaginatedRequestSchema$1,PaginatedResultSchema:PaginatedResultSchema$1,ResourceContentsSchema:ResourceContentsSchema$1,TextResourceContentsSchema:TextResourceContentsSchema$1,BlobResourceContentsSchema:BlobResourceContentsSchema$1,RoleSchema:RoleSchema$1,AnnotationsSchema:AnnotationsSchema$1,ResourceSchema:ResourceSchema$1,ResourceTemplateSchema:ResourceTemplateSchema$1,ListResourcesRequestSchema:ListResourcesRequestSchema$1,ListResourcesResultSchema:ListResourcesResultSchema$1,ListResourceTemplatesRequestSchema:ListResourceTemplatesRequestSchema$1,ListResourceTemplatesResultSchema:ListResourceTemplatesResultSchema$1,ResourceRequestParamsSchema:ResourceRequestParamsSchema$1,ReadResourceRequestParamsSchema:ReadResourceRequestParamsSchema$1,ReadResourceRequestSchema:ReadResourceRequestSchema$1,ReadResourceResultSchema:ReadResourceResultSchema$1,ResourceListChangedNotificationSchema:ResourceListChangedNotificationSchema$1,SubscribeRequestParamsSchema:SubscribeRequestParamsSchema$1,SubscribeRequestSchema:SubscribeRequestSchema$1,UnsubscribeRequestParamsSchema:UnsubscribeRequestParamsSchema$1,UnsubscribeRequestSchema:UnsubscribeRequestSchema$1,ResourceUpdatedNotificationParamsSchema:ResourceUpdatedNotificationParamsSchema$1,ResourceUpdatedNotificationSchema:ResourceUpdatedNotificationSchema$1,PromptArgumentSchema:PromptArgumentSchema$1,PromptSchema:PromptSchema$1,ListPromptsRequestSchema:ListPromptsRequestSchema$1,ListPromptsResultSchema:ListPromptsResultSchema$1,GetPromptRequestParamsSchema:GetPromptRequestParamsSchema$1,GetPromptRequestSchema:GetPromptRequestSchema$1,TextContentSchema:TextContentSchema$1,ImageContentSchema:ImageContentSchema$1,AudioContentSchema:AudioContentSchema$1,ToolUseContentSchema:ToolUseContentSchema$1,EmbeddedResourceSchema:EmbeddedResourceSchema$1,ResourceLinkSchema:ResourceLinkSchema$1,ContentBlockSchema:ContentBlockSchema$1,PromptMessageSchema:PromptMessageSchema$1,GetPromptResultSchema:GetPromptResultSchema$1,PromptListChangedNotificationSchema:PromptListChangedNotificationSchema$1,ToolAnnotationsSchema:ToolAnnotationsSchema$1,ToolExecutionSchema:ToolExecutionSchema$1,ToolSchema:ToolSchema$1,ListToolsRequestSchema:ListToolsRequestSchema$1,ListToolsResultSchema:ListToolsResultSchema$1,CallToolResultSchema:CallToolResultSchema$1,CallToolRequestParamsSchema:CallToolRequestParamsSchema$1,CallToolRequestSchema:CallToolRequestSchema$1,ToolListChangedNotificationSchema:ToolListChangedNotificationSchema$1,LoggingLevelSchema:LoggingLevelSchema$1,SetLevelRequestParamsSchema:SetLevelRequestParamsSchema$1,SetLevelRequestSchema:SetLevelRequestSchema$1,LoggingMessageNotificationParamsSchema:LoggingMessageNotificationParamsSchema$1,LoggingMessageNotificationSchema:LoggingMessageNotificationSchema$1,ModelHintSchema:ModelHintSchema$1,ModelPreferencesSchema:ModelPreferencesSchema$1,ToolChoiceSchema:ToolChoiceSchema$1,ToolResultContentSchema:ToolResultContentSchema$1,SamplingContentSchema:SamplingContentSchema$1,SamplingMessageContentBlockSchema:SamplingMessageContentBlockSchema$1,SamplingMessageSchema:SamplingMessageSchema$1,CreateMessageRequestParamsSchema:CreateMessageRequestParamsSchema$1,CreateMessageRequestSchema:CreateMessageRequestSchema$1,CreateMessageResultSchema:CreateMessageResultSchema$1,CreateMessageResultWithToolsSchema:CreateMessageResultWithToolsSchema$1,BooleanSchemaSchema:BooleanSchemaSchema$1,StringSchemaSchema:StringSchemaSchema$1,NumberSchemaSchema:NumberSchemaSchema$1,UntitledSingleSelectEnumSchemaSchema:UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema:TitledSingleSelectEnumSchemaSchema$1,LegacyTitledEnumSchemaSchema:LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema:SingleSelectEnumSchemaSchema$1,UntitledMultiSelectEnumSchemaSchema:UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema:TitledMultiSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema:MultiSelectEnumSchemaSchema$1,EnumSchemaSchema:EnumSchemaSchema$1,PrimitiveSchemaDefinitionSchema:PrimitiveSchemaDefinitionSchema$1,ElicitRequestFormParamsSchema:ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema:ElicitRequestURLParamsSchema$1,ElicitRequestParamsSchema:ElicitRequestParamsSchema$1,ElicitRequestSchema:ElicitRequestSchema$1,ElicitationCompleteNotificationParamsSchema:ElicitationCompleteNotificationParamsSchema$1,ElicitationCompleteNotificationSchema:ElicitationCompleteNotificationSchema$1,ElicitResultSchema:ElicitResultSchema$1,ResourceTemplateReferenceSchema:ResourceTemplateReferenceSchema$1,PromptReferenceSchema:PromptReferenceSchema$1,CompleteRequestParamsSchema:CompleteRequestParamsSchema$1,CompleteRequestSchema:CompleteRequestSchema$1,CompleteResultSchema:CompleteResultSchema$1,RootSchema:RootSchema$1,ListRootsRequestSchema:ListRootsRequestSchema$1,ListRootsResultSchema:ListRootsResultSchema$1,RootsListChangedNotificationSchema:RootsListChangedNotificationSchema$1,TaskCreationParamsSchema:TaskCreationParamsSchema$1,TaskStatusSchema:TaskStatusSchema$1,TaskSchema:TaskSchema$1,CreateTaskResultSchema:CreateTaskResultSchema$1,TaskStatusNotificationParamsSchema:TaskStatusNotificationParamsSchema$1,TaskStatusNotificationSchema:TaskStatusNotificationSchema$1,GetTaskRequestSchema:GetTaskRequestSchema$1,GetTaskResultSchema:GetTaskResultSchema$1,GetTaskPayloadRequestSchema:GetTaskPayloadRequestSchema$1,GetTaskPayloadResultSchema:GetTaskPayloadResultSchema$1,ListTasksRequestSchema:ListTasksRequestSchema$1,ListTasksResultSchema:ListTasksResultSchema$1,CancelTaskRequestSchema:CancelTaskRequestSchema$1,CancelTaskResultSchema:ResultSchema$1.merge(TaskSchema$1),ClientRequestSchema:union([PingRequestSchema$1,InitializeRequestSchema$1,CompleteRequestSchema$1,SetLevelRequestSchema$1,GetPromptRequestSchema$1,ListPromptsRequestSchema$1,ListResourcesRequestSchema$1,ListResourceTemplatesRequestSchema$1,ReadResourceRequestSchema$1,SubscribeRequestSchema$1,UnsubscribeRequestSchema$1,CallToolRequestSchema$1,ListToolsRequestSchema$1,GetTaskRequestSchema$1,GetTaskPayloadRequestSchema$1,ListTasksRequestSchema$1,CancelTaskRequestSchema$1]),ClientNotificationSchema:union([CancelledNotificationSchema$1,ProgressNotificationSchema$1,InitializedNotificationSchema$1,RootsListChangedNotificationSchema$1,TaskStatusNotificationSchema$1]),ClientResultSchema:union([EmptyResultSchema$1,CreateMessageResultSchema$1,CreateMessageResultWithToolsSchema$1,ElicitResultSchema$1,ListRootsResultSchema$1,GetTaskResultSchema$1,ListTasksResultSchema$1,CreateTaskResultSchema$1]),ServerRequestSchema:union([PingRequestSchema$1,CreateMessageRequestSchema$1,ElicitRequestSchema$1,ListRootsRequestSchema$1,GetTaskRequestSchema$1,GetTaskPayloadRequestSchema$1,ListTasksRequestSchema$1,CancelTaskRequestSchema$1]),ServerNotificationSchema:union([CancelledNotificationSchema$1,ProgressNotificationSchema$1,LoggingMessageNotificationSchema$1,ResourceUpdatedNotificationSchema$1,ResourceListChangedNotificationSchema$1,ToolListChangedNotificationSchema$1,PromptListChangedNotificationSchema$1,TaskStatusNotificationSchema$1,ElicitationCompleteNotificationSchema$1]),ServerResultSchema:union([EmptyResultSchema$1,InitializeResultSchema$1,CompleteResultSchema$1,GetPromptResultSchema$1,ListPromptsResultSchema$1,ListResourcesResultSchema$1,ListResourceTemplatesResultSchema$1,ReadResourceResultSchema$1,CallToolResultSchema$1,ListToolsResultSchema$1,GetTaskResultSchema$1,ListTasksResultSchema$1,CreateTaskResultSchema$1]),CallToolResultWireSchema:unknown().superRefine((value,ctx)=>{if(!(typeof value!="object"||value===null||Array.isArray(value)||value.content!==void 0)){for(let key of TOOL_RESULT_FOREIGN_FAMILY_KEYS)if(key in value){ctx.addIssue({code:"custom",message:`content is required when the body carries '${key}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1)}}function buildSchemas2025(){return memo$1??=build$1()}function isNonObjectJsonSchemaRoot(json){return json.type!=="object"}function establishesNewBase(id){return id!==void 0&&!(typeof id=="string"&&id.startsWith("#"))}function wrapOutputSchemaForLegacy(natural){let $schema=typeof natural.$schema=="string"?natural.$schema:void 0;if(establishesNewBase(natural.$id))return{...$schema!==void 0&&{$schema},type:"object",properties:{result:natural},required:["result"]};let convertRecursiveRefs=declares2019Dialect(natural.$schema)&&natural.$recursiveAnchor!==!0,rewriteRefs=(node,parentIsNameMap)=>{if(Array.isArray(node))return node.map(item=>rewriteRefs(item,!1));if(node===null||typeof node!="object"||!parentIsNameMap&&establishesNewBase(node.$id))return node;let out={},convertedRecursion=!1;for(let[k,v]of Object.entries(node))parentIsNameMap?out[k]=rewriteRefs(v,!1):(k==="$ref"||k==="$dynamicRef")&&typeof v=="string"?out[k]=v==="#"?"#/properties/result":v.startsWith("#/")?`#/properties/result${v.slice(1)}`:v:k==="$recursiveRef"&&v==="#"&&convertRecursiveRefs?convertedRecursion=!0:REF_REWRITE_DATA_POSITION_KEYS.has(k)?out[k]=v:REF_REWRITE_NAME_MAP_KEYS.has(k)?out[k]=rewriteRefs(v,!0):out[k]=rewriteRefs(v,!1);return convertedRecursion&&("$ref"in out?out.allOf=[...Array.isArray(out.allOf)?out.allOf:[],{$ref:"#/properties/result"}]:out.$ref="#/properties/result"),out};return{...$schema!==void 0&&{$schema},type:"object",properties:{result:rewriteRefs(natural,!1)},required:["result"]}}function registryMaps(){if(maps$1)return maps$1;let s=buildSchemas2025();return maps$1={requestSchemas:{ping:s.PingRequestSchema,initialize:s.InitializeRequestSchema,"completion/complete":s.CompleteRequestSchema,"logging/setLevel":s.SetLevelRequestSchema,"prompts/get":s.GetPromptRequestSchema,"prompts/list":s.ListPromptsRequestSchema,"resources/list":s.ListResourcesRequestSchema,"resources/templates/list":s.ListResourceTemplatesRequestSchema,"resources/read":s.ReadResourceRequestSchema,"resources/subscribe":s.SubscribeRequestSchema,"resources/unsubscribe":s.UnsubscribeRequestSchema,"tools/call":s.CallToolRequestSchema,"tools/list":s.ListToolsRequestSchema,"tasks/get":s.GetTaskRequestSchema,"tasks/result":s.GetTaskPayloadRequestSchema,"tasks/list":s.ListTasksRequestSchema,"tasks/cancel":s.CancelTaskRequestSchema,"sampling/createMessage":s.CreateMessageRequestSchema,"elicitation/create":s.ElicitRequestSchema,"roots/list":s.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":s.CancelledNotificationSchema,"notifications/progress":s.ProgressNotificationSchema,"notifications/initialized":s.InitializedNotificationSchema,"notifications/roots/list_changed":s.RootsListChangedNotificationSchema,"notifications/tasks/status":s.TaskStatusNotificationSchema,"notifications/message":s.LoggingMessageNotificationSchema,"notifications/resources/updated":s.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":s.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":s.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":s.PromptListChangedNotificationSchema,"notifications/elicitation/complete":s.ElicitationCompleteNotificationSchema},resultSchemas:{ping:s.EmptyResultSchema,initialize:s.InitializeResultSchema,"completion/complete":s.CompleteResultSchema,"logging/setLevel":s.EmptyResultSchema,"prompts/get":s.GetPromptResultSchema,"prompts/list":s.ListPromptsResultSchema,"resources/list":s.ListResourcesResultSchema,"resources/templates/list":s.ListResourceTemplatesResultSchema,"resources/read":s.ReadResourceResultSchema,"resources/subscribe":s.EmptyResultSchema,"resources/unsubscribe":s.EmptyResultSchema,"tools/call":s.CallToolResultWireSchema,"tools/list":s.ListToolsResultSchema,"sampling/createMessage":s.CreateMessageResultWithToolsSchema,"elicitation/create":s.ElicitResultSchema,"roots/list":s.ListRootsResultSchema}},maps$1}function hasRequestMethod2025(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys$1,method)}function hasNotificationMethod2025(method){return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1,method)}function hasResultMethod(method){return Object.prototype.hasOwnProperty.call(resultMethodKeys,method)}function getResultSchema(method){return hasResultMethod(method)?registryMaps().resultSchemas[method]:void 0}function getRequestSchema(method){return hasRequestMethod2025(method)?registryMaps().requestSchemas[method]:void 0}function getNotificationSchema(method){return hasNotificationMethod2025(method)?registryMaps().notificationSchemas[method]:void 0}function isPlainObject$6(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function triState$1(schema2,raw2){if(schema2===void 0)return{ok:!1,reason:"not-in-era"};let parsed=schema2.safeParse(raw2);return parsed.success?{ok:!0,value:parsed.data}:{ok:!1,reason:"invalid",message:String(parsed.error)}}function toolNeedsLegacyWrap(t){return isPlainObject$6(t)&&isPlainObject$6(t.outputSchema)&&isNonObjectJsonSchemaRoot(t.outputSchema)}function build(){let JSONValueSchema$1=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema$1),array(JSONValueSchema$1)])),JSONObjectSchema$1=record(string2(),JSONValueSchema$1),ProgressTokenSchema$1=union([string2(),number2().int()]),CursorSchema$1=string2(),RequestIdSchema$1=union([string2(),number2().int()]),RoleSchema$1=_enum(["user","assistant"]),LoggingLevelSchema$1=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Base64Schema2=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),TaskMetadataSchema$1=object({ttl:number2().optional()}),RelatedTaskMetadataSchema$1=object({taskId:string2()}),RequestMetaSchema$1=looseObject({progressToken:ProgressTokenSchema$1.optional(),"io.modelcontextprotocol/related-task":RelatedTaskMetadataSchema$1.optional()}),BaseRequestParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),TaskAugmentedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({task:TaskMetadataSchema$1.optional()}),NotificationsParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),NotificationSchema$1=object({method:string2(),params:NotificationsParamsSchema$1.loose().optional()}),IconSchema$1=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema$1=object({icons:array(IconSchema$1).optional()}),BaseMetadataSchema$1=object({name:string2(),title:string2().optional()}),ImplementationSchema$1=BaseMetadataSchema$1.extend({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema2=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema$1),ElicitationCapabilitySchema2=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema2.optional(),url:JSONObjectSchema$1.optional()}),JSONObjectSchema$1.optional())),ClientTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema$1.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema$1.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema$1.optional()}).optional()}).optional()}),ClientCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),sampling:object({context:JSONObjectSchema$1.optional(),tools:JSONObjectSchema$1.optional()}).optional(),elicitation:ElicitationCapabilitySchema2.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),ServerCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),logging:JSONObjectSchema$1.optional(),completions:JSONObjectSchema$1.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),ProgressSchema$1=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema$1=object({...NotificationsParamsSchema$1.shape,...ProgressSchema$1.shape,progressToken:ProgressTokenSchema$1}),ProgressNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema$1}),LoggingMessageNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({level:LoggingLevelSchema$1,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema$1}),ResourceContentsSchema$1=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema$1=ResourceContentsSchema$1.extend({text:string2()}),BlobResourceContentsSchema$1=ResourceContentsSchema$1.extend({blob:Base64Schema2}),AnnotationsSchema$1=object({audience:array(RoleSchema$1).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema$1.optional()}),ResourceUpdatedNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({uri:string2()}),ResourceUpdatedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema$1}),PromptArgumentSchema$1=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema$1)),_meta:optional(looseObject({}))}),PromptListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema$1.optional()}),TextContentSchema$1=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema$1=object({type:literal("image"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema$1=object({type:literal("audio"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema$1=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema$1=object({type:literal("resource"),resource:union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema$1=ResourceSchema$1.extend({type:literal("resource_link")}),ContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ResourceLinkSchema$1,EmbeddedResourceSchema$1]),PromptMessageSchema$1=object({role:RoleSchema$1,content:ContentBlockSchema$1}),ToolAnnotationsSchema$1=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema$1.optional()}),ModelHintSchema$1=object({name:string2().optional()}),ModelPreferencesSchema$1=object({hints:array(ModelHintSchema$1).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema$1=object({mode:_enum(["auto","required","none"]).optional()}),BooleanSchemaSchema$1=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema$1=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema$1=union([UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema$1]),UntitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema$1=union([UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema$1]),EnumSchemaSchema$1=union([LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema$1]),PrimitiveSchemaDefinitionSchema$1=union([EnumSchemaSchema$1,BooleanSchemaSchema$1,StringSchemaSchema$1,NumberSchemaSchema$1]),ElicitRequestFormParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema$1),required:array(string2()).optional()}).catchall(unknown())}),ResourceTemplateReferenceSchema$1=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema$1=object({type:literal("ref/prompt"),name:string2()}),RootSchema$1=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),sharedClientCapabilityShape=ClientCapabilitiesSchema$1.shape,ClientCapabilities2026Schema=object({experimental:sharedClientCapabilityShape.experimental,sampling:sharedClientCapabilityShape.sampling,elicitation:sharedClientCapabilityShape.elicitation,roots:sharedClientCapabilityShape.roots,extensions:sharedClientCapabilityShape.extensions}),sharedServerCapabilityShape=ServerCapabilitiesSchema$1.shape,ServerCapabilities2026Schema=object({experimental:sharedServerCapabilityShape.experimental,logging:sharedServerCapabilityShape.logging,completions:sharedServerCapabilityShape.completions,prompts:sharedServerCapabilityShape.prompts,resources:sharedServerCapabilityShape.resources,tools:sharedServerCapabilityShape.tools,extensions:sharedServerCapabilityShape.extensions}),RequestMetaEnvelopeSchema=looseObject({progressToken:ProgressTokenSchema$1.optional(),[PROTOCOL_VERSION_META_KEY]:string2(),[CLIENT_INFO_META_KEY]:ImplementationSchema$1.optional(),[CLIENT_CAPABILITIES_META_KEY]:ClientCapabilities2026Schema,[LOG_LEVEL_META_KEY]:LoggingLevelSchema$1.optional()}),ToolSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:string2().optional(),inputSchema:looseObject({$schema:string2().optional(),type:literal("object")}),outputSchema:looseObject({$schema:string2().optional()}).optional(),annotations:ToolAnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolResultContentSchema$1=object({type:literal("tool_result"),toolUseId:string2(),content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingMessageContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ToolUseContentSchema$1,ToolResultContentSchema$1]),SamplingMessageSchema$1=object({role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)]),_meta:record(string2(),unknown()).optional()}),ResultTypeSchema=string2(),ResultMetaSchema=looseObject({[SERVER_INFO_META_KEY]:ImplementationSchema$1.optional().catch(void 0)}),wireMeta=ResultMetaSchema.optional();function wireResult(shape){return looseObject({_meta:wireMeta,resultType:ResultTypeSchema.default("complete"),...shape})}let ResultSchema$1=wireResult({}),PaginatedResultSchema$1=wireResult({nextCursor:CursorSchema$1.optional()}),CallToolResultSchema$1=wireResult({content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional()}),ListToolsResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),tools:array(ToolSchema$1),nextCursor:CursorSchema$1.optional()}),ListPromptsResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),prompts:array(PromptSchema$1),nextCursor:CursorSchema$1.optional()}),GetPromptResultSchema$1=wireResult({description:string2().optional(),messages:array(PromptMessageSchema$1)}),ListResourcesResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resources:array(ResourceSchema$1),nextCursor:CursorSchema$1.optional()}),ListResourceTemplatesResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resourceTemplates:array(ResourceTemplateSchema$1),nextCursor:CursorSchema$1.optional()}),ReadResourceResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),CompleteResultSchema$1=wireResult({completion:object({values:array(string2()).max(100),total:number2().int().optional(),hasMore:boolean2().optional()}).loose()}),CacheableResultSchema=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"])}),DiscoverResultSchema$1=wireResult({ttlMs:number2().int().min(0).catch(0),cacheScope:_enum(["public","private"]).catch("private"),supportedVersions:array(string2()),capabilities:ServerCapabilities2026Schema,instructions:string2().optional()}),CreateMessageRequestParamsSchema$1=object({messages:array(SamplingMessageSchema$1),modelPreferences:ModelPreferencesSchema$1.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema$1.optional(),tools:array(ToolSchema$1).optional(),toolChoice:ToolChoiceSchema$1.optional()}),CreateMessageRequestSchema$1=object({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema$1}),ListRootsRequestSchema$1=object({method:literal("roots/list"),params:object({_meta:record(string2(),unknown()).optional()}).optional()}),CreateMessageResultSchema$1=object({...SamplingMessageSchema$1.shape,model:string2(),stopReason:string2().optional()}),ListRootsResultSchema$1=object({roots:array(RootSchema$1)}),ElicitResultSchema$1=object({action:_enum(["accept","decline","cancel"]),content:record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional()}),ElicitRequestURLParamsSchema$1=object({mode:literal("url"),message:string2(),url:string2().url()}),ElicitRequestParamsSchema$1=union([ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema$1]),ElicitRequestSchema$1=object({method:literal("elicitation/create"),params:ElicitRequestParamsSchema$1}),InputRequestSchema=union([CreateMessageRequestSchema$1,ListRootsRequestSchema$1,ElicitRequestSchema$1]),InputResponseSchema=union([CreateMessageResultSchema$1,ListRootsResultSchema$1,ElicitResultSchema$1]),InputRequestsSchema=record(string2(),InputRequestSchema),InputResponsesSchema=record(string2(),InputResponseSchema),InputRequiredResultSchema=wireResult({inputRequests:InputRequestsSchema.optional(),requestState:string2().optional()}),retryParamsShape={inputResponses:InputResponsesSchema.optional(),requestState:string2().optional()},InputResponseRequestParamsSchema=object({_meta:RequestMetaEnvelopeSchema,...retryParamsShape}),DispatchRequestMetaSchema=looseObject({progressToken:ProgressTokenSchema$1.optional()});function wireRequest(method,paramsShape){return object({method:literal(method),params:object({_meta:RequestMetaEnvelopeSchema,...paramsShape})})}function dispatchRequest(method,paramsShape){return object({method:literal(method),params:object({_meta:DispatchRequestMetaSchema.optional(),...paramsShape}).optional()})}let callToolParamsShape={name:string2(),arguments:record(string2(),unknown()).optional(),...retryParamsShape},paginatedParamsShape={cursor:CursorSchema$1.optional()},CallToolRequestSchema$1=wireRequest("tools/call",callToolParamsShape),ListToolsRequestSchema$1=wireRequest("tools/list",paginatedParamsShape),ListPromptsRequestSchema$1=wireRequest("prompts/list",paginatedParamsShape),GetPromptRequestSchema$1=wireRequest("prompts/get",{name:string2(),arguments:record(string2(),string2()).optional(),...retryParamsShape}),ListResourcesRequestSchema$1=wireRequest("resources/list",paginatedParamsShape),ListResourceTemplatesRequestSchema$1=wireRequest("resources/templates/list",paginatedParamsShape),ReadResourceRequestSchema$1=wireRequest("resources/read",{uri:string2(),...retryParamsShape}),completeParamsShape={ref:union([PromptReferenceSchema$1,ResourceTemplateReferenceSchema$1]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()},CompleteRequestSchema$1=wireRequest("completion/complete",completeParamsShape),DiscoverRequestSchema$1=wireRequest("server/discover",{}),SubscriptionFilterSchema$1=object({toolsListChanged:boolean2().optional(),promptsListChanged:boolean2().optional(),resourcesListChanged:boolean2().optional(),resourceSubscriptions:array(string2()).optional()}),subscriptionsListenParamsShape={notifications:SubscriptionFilterSchema$1},SubscriptionsListenRequestSchema$1=wireRequest("subscriptions/listen",subscriptionsListenParamsShape),SubscriptionsListenResultMetaSchema$1=ResultMetaSchema.extend({"io.modelcontextprotocol/subscriptionId":RequestIdSchema$1}),SubscriptionsListenResultSchema$1=looseObject({_meta:SubscriptionsListenResultMetaSchema$1,resultType:ResultTypeSchema.default("complete")}),dispatchRequestSchemas={"tools/call":dispatchRequest("tools/call",callToolParamsShape),"tools/list":dispatchRequest("tools/list",paginatedParamsShape),"prompts/get":dispatchRequest("prompts/get",{name:string2(),arguments:record(string2(),string2()).optional()}),"prompts/list":dispatchRequest("prompts/list",paginatedParamsShape),"resources/list":dispatchRequest("resources/list",paginatedParamsShape),"resources/templates/list":dispatchRequest("resources/templates/list",paginatedParamsShape),"resources/read":dispatchRequest("resources/read",{uri:string2()}),"completion/complete":dispatchRequest("completion/complete",completeParamsShape),"server/discover":dispatchRequest("server/discover",{}),"subscriptions/listen":dispatchRequest("subscriptions/listen",subscriptionsListenParamsShape)};function liftedResult(shape){return looseObject({_meta:wireMeta,...shape})}let dispatchResultSchemas={"tools/call":liftedResult({content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional()}),"tools/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),tools:array(ToolSchema$1),nextCursor:CursorSchema$1.optional()}),"prompts/get":liftedResult({description:string2().optional(),messages:array(PromptMessageSchema$1)}),"prompts/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),prompts:array(PromptSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resources:array(ResourceSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/templates/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resourceTemplates:array(ResourceTemplateSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/read":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),"completion/complete":liftedResult({completion:object({values:array(string2()).max(100),total:number2().int().optional(),hasMore:boolean2().optional()}).loose()}),"server/discover":liftedResult({ttlMs:number2().int().min(0).catch(0),cacheScope:_enum(["public","private"]).catch("private"),supportedVersions:array(string2()),capabilities:ServerCapabilities2026Schema,instructions:string2().optional()}),"subscriptions/listen":liftedResult({})},NotificationMetaSchema=looseObject({"io.modelcontextprotocol/subscriptionId":RequestIdSchema$1.optional()}),SubscriptionsAcknowledgedNotificationSchema$1=object({method:literal("notifications/subscriptions/acknowledged"),params:object({_meta:NotificationMetaSchema.optional(),notifications:SubscriptionFilterSchema$1})}),CancelledNotificationParamsSchema$1=object({_meta:NotificationMetaSchema.optional(),requestId:RequestIdSchema$1,reason:string2().optional()}),CancelledNotificationSchema$1=object({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema$1}),notificationSchemas2026={"notifications/cancelled":CancelledNotificationSchema$1,"notifications/progress":ProgressNotificationSchema$1,"notifications/message":LoggingMessageNotificationSchema$1,"notifications/resources/updated":ResourceUpdatedNotificationSchema$1,"notifications/resources/list_changed":ResourceListChangedNotificationSchema$1,"notifications/tools/list_changed":ToolListChangedNotificationSchema$1,"notifications/prompts/list_changed":PromptListChangedNotificationSchema$1,"notifications/subscriptions/acknowledged":SubscriptionsAcknowledgedNotificationSchema$1},wireResultResponse=result=>object({jsonrpc:literal("2.0"),id:union([string2(),number2().int()]),result}).strict();return{JSONValueSchema:JSONValueSchema$1,JSONObjectSchema:JSONObjectSchema$1,ProgressTokenSchema:ProgressTokenSchema$1,CursorSchema:CursorSchema$1,RequestIdSchema:RequestIdSchema$1,RoleSchema:RoleSchema$1,LoggingLevelSchema:LoggingLevelSchema$1,TaskMetadataSchema:TaskMetadataSchema$1,RelatedTaskMetadataSchema:RelatedTaskMetadataSchema$1,RequestMetaSchema:RequestMetaSchema$1,BaseRequestParamsSchema:BaseRequestParamsSchema$1,TaskAugmentedRequestParamsSchema:TaskAugmentedRequestParamsSchema$1,NotificationsParamsSchema:NotificationsParamsSchema$1,NotificationSchema:NotificationSchema$1,IconSchema:IconSchema$1,IconsSchema:IconsSchema$1,BaseMetadataSchema:BaseMetadataSchema$1,ImplementationSchema:ImplementationSchema$1,ClientTasksCapabilitySchema:ClientTasksCapabilitySchema$1,ServerTasksCapabilitySchema:ServerTasksCapabilitySchema$1,ClientCapabilitiesSchema:ClientCapabilitiesSchema$1,ServerCapabilitiesSchema:ServerCapabilitiesSchema$1,ProgressSchema:ProgressSchema$1,ProgressNotificationParamsSchema:ProgressNotificationParamsSchema$1,ProgressNotificationSchema:ProgressNotificationSchema$1,LoggingMessageNotificationParamsSchema:LoggingMessageNotificationParamsSchema$1,LoggingMessageNotificationSchema:LoggingMessageNotificationSchema$1,ResourceContentsSchema:ResourceContentsSchema$1,TextResourceContentsSchema:TextResourceContentsSchema$1,BlobResourceContentsSchema:BlobResourceContentsSchema$1,AnnotationsSchema:AnnotationsSchema$1,ResourceSchema:ResourceSchema$1,ResourceTemplateSchema:ResourceTemplateSchema$1,ResourceListChangedNotificationSchema:ResourceListChangedNotificationSchema$1,ResourceUpdatedNotificationParamsSchema:ResourceUpdatedNotificationParamsSchema$1,ResourceUpdatedNotificationSchema:ResourceUpdatedNotificationSchema$1,PromptArgumentSchema:PromptArgumentSchema$1,PromptSchema:PromptSchema$1,PromptListChangedNotificationSchema:PromptListChangedNotificationSchema$1,TextContentSchema:TextContentSchema$1,ImageContentSchema:ImageContentSchema$1,AudioContentSchema:AudioContentSchema$1,ToolUseContentSchema:ToolUseContentSchema$1,EmbeddedResourceSchema:EmbeddedResourceSchema$1,ResourceLinkSchema:ResourceLinkSchema$1,ContentBlockSchema:ContentBlockSchema$1,PromptMessageSchema:PromptMessageSchema$1,ToolAnnotationsSchema:ToolAnnotationsSchema$1,ToolListChangedNotificationSchema:ToolListChangedNotificationSchema$1,ModelHintSchema:ModelHintSchema$1,ModelPreferencesSchema:ModelPreferencesSchema$1,ToolChoiceSchema:ToolChoiceSchema$1,BooleanSchemaSchema:BooleanSchemaSchema$1,StringSchemaSchema:StringSchemaSchema$1,NumberSchemaSchema:NumberSchemaSchema$1,UntitledSingleSelectEnumSchemaSchema:UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema:TitledSingleSelectEnumSchemaSchema$1,LegacyTitledEnumSchemaSchema:LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema:SingleSelectEnumSchemaSchema$1,UntitledMultiSelectEnumSchemaSchema:UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema:TitledMultiSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema:MultiSelectEnumSchemaSchema$1,EnumSchemaSchema:EnumSchemaSchema$1,PrimitiveSchemaDefinitionSchema:PrimitiveSchemaDefinitionSchema$1,ElicitRequestFormParamsSchema:ElicitRequestFormParamsSchema$1,ResourceTemplateReferenceSchema:ResourceTemplateReferenceSchema$1,PromptReferenceSchema:PromptReferenceSchema$1,RootSchema:RootSchema$1,ClientCapabilities2026Schema,ServerCapabilities2026Schema,RequestMetaEnvelopeSchema,ToolSchema:ToolSchema$1,ToolResultContentSchema:ToolResultContentSchema$1,SamplingMessageContentBlockSchema:SamplingMessageContentBlockSchema$1,SamplingMessageSchema:SamplingMessageSchema$1,ResultTypeSchema,ResultMetaSchema,ResultSchema:ResultSchema$1,PaginatedResultSchema:PaginatedResultSchema$1,CallToolResultSchema:CallToolResultSchema$1,ListToolsResultSchema:ListToolsResultSchema$1,ListPromptsResultSchema:ListPromptsResultSchema$1,GetPromptResultSchema:GetPromptResultSchema$1,ListResourcesResultSchema:ListResourcesResultSchema$1,ListResourceTemplatesResultSchema:ListResourceTemplatesResultSchema$1,ReadResourceResultSchema:ReadResourceResultSchema$1,CompleteResultSchema:CompleteResultSchema$1,CacheableResultSchema,DiscoverResultSchema:DiscoverResultSchema$1,CreateMessageRequestParamsSchema:CreateMessageRequestParamsSchema$1,CreateMessageRequestSchema:CreateMessageRequestSchema$1,ListRootsRequestSchema:ListRootsRequestSchema$1,CreateMessageResultSchema:CreateMessageResultSchema$1,ListRootsResultSchema:ListRootsResultSchema$1,ElicitResultSchema:ElicitResultSchema$1,ElicitRequestURLParamsSchema:ElicitRequestURLParamsSchema$1,ElicitRequestParamsSchema:ElicitRequestParamsSchema$1,ElicitRequestSchema:ElicitRequestSchema$1,InputRequestSchema,InputResponseSchema,InputRequestsSchema,InputResponsesSchema,InputRequiredResultSchema,InputResponseRequestParamsSchema,CallToolRequestSchema:CallToolRequestSchema$1,ListToolsRequestSchema:ListToolsRequestSchema$1,ListPromptsRequestSchema:ListPromptsRequestSchema$1,GetPromptRequestSchema:GetPromptRequestSchema$1,ListResourcesRequestSchema:ListResourcesRequestSchema$1,ListResourceTemplatesRequestSchema:ListResourceTemplatesRequestSchema$1,ReadResourceRequestSchema:ReadResourceRequestSchema$1,CompleteRequestSchema:CompleteRequestSchema$1,DiscoverRequestSchema:DiscoverRequestSchema$1,SubscriptionFilterSchema:SubscriptionFilterSchema$1,SubscriptionsListenRequestSchema:SubscriptionsListenRequestSchema$1,SubscriptionsListenResultMetaSchema:SubscriptionsListenResultMetaSchema$1,SubscriptionsListenResultSchema:SubscriptionsListenResultSchema$1,dispatchRequestSchemas,dispatchResultSchemas,NotificationMetaSchema,SubscriptionsAcknowledgedNotificationSchema:SubscriptionsAcknowledgedNotificationSchema$1,CancelledNotificationParamsSchema:CancelledNotificationParamsSchema$1,CancelledNotificationSchema:CancelledNotificationSchema$1,notificationSchemas2026,JSONRPCResultResponseSchema:wireResultResponse(ResultSchema$1),CallToolResultResponseSchema:wireResultResponse(union([CallToolResultSchema$1,InputRequiredResultSchema])),ListToolsResultResponseSchema:wireResultResponse(ListToolsResultSchema$1),ListPromptsResultResponseSchema:wireResultResponse(ListPromptsResultSchema$1),GetPromptResultResponseSchema:wireResultResponse(union([GetPromptResultSchema$1,InputRequiredResultSchema])),ListResourcesResultResponseSchema:wireResultResponse(ListResourcesResultSchema$1),ListResourceTemplatesResultResponseSchema:wireResultResponse(ListResourceTemplatesResultSchema$1),ReadResourceResultResponseSchema:wireResultResponse(union([ReadResourceResultSchema$1,InputRequiredResultSchema])),CompleteResultResponseSchema:wireResultResponse(CompleteResultSchema$1),DiscoverResultResponseSchema:wireResultResponse(DiscoverResultSchema$1),SubscriptionsListenResultResponseSchema:wireResultResponse(SubscriptionsListenResultSchema$1)}}function buildSchemas2026(){return memo??=build()}function isCacheableResultMethod(method){return CACHEABLE_RESULT_METHODS.includes(method)}function attachCacheHintFallback(result,hint){if(hint===void 0)return result;let attached=result[RESULT_CACHE_HINT_FALLBACK];if(attached===void 0)return{...result,[RESULT_CACHE_HINT_FALLBACK]:hint};let merged={},ttlMs=attached.ttlMs??hint.ttlMs;ttlMs!==void 0&&(merged.ttlMs=ttlMs);let cacheScope=attached.cacheScope??hint.cacheScope;return cacheScope!==void 0&&(merged.cacheScope=cacheScope),{...result,[RESULT_CACHE_HINT_FALLBACK]:merged}}function cacheHintFallbackOf(result){return result[RESULT_CACHE_HINT_FALLBACK]}function isValidCacheTtlMs(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0}function isValidCacheScope(value){return value==="public"||value==="private"}function assertValidCacheHint(hint,context){if(hint.ttlMs!==void 0&&!isValidCacheTtlMs(hint.ttlMs))throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`);if(hint.cacheScope!==void 0&&!isValidCacheScope(hint.cacheScope))throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`)}function stampResultType(method,result){let provided=result.resultType;if(provided===void 0)return{...result,resultType:"complete"};if(provided==="complete"||EXTENDED_RESULT_TYPE_METHODS.includes(method))return result;throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`)}function fillCacheFields(method,result){let fallback=cacheHintFallbackOf(result);if(result.resultType!=="complete"||!isCacheableResultMethod(method))return fallback===void 0?result:stripCacheHintFallback(result);let provided=result,ttlMs=isValidCacheTtlMs(provided.ttlMs)?provided.ttlMs:resolveTtlMs(fallback),cacheScope=isValidCacheScope(provided.cacheScope)?provided.cacheScope:resolveCacheScope(fallback),filled={...provided,ttlMs,cacheScope};return delete filled[RESULT_CACHE_HINT_FALLBACK],filled}function isPlainObject$5(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function stampServerInfoMeta(result,serverInfo){if(serverInfo===void 0)return result;let meta2=result._meta;return meta2===void 0?{...result,_meta:{[SERVER_INFO_META_KEY]:serverInfo}}:!isPlainObject$5(meta2)||meta2[SERVER_INFO_META_KEY]!==void 0?result:{...result,_meta:{...meta2,[SERVER_INFO_META_KEY]:serverInfo}}}function resolveTtlMs(fallback){return fallback!==void 0&&isValidCacheTtlMs(fallback.ttlMs)?fallback.ttlMs:DEFAULT_CACHE_TTL_MS}function resolveCacheScope(fallback){return fallback!==void 0&&isValidCacheScope(fallback.cacheScope)?fallback.cacheScope:DEFAULT_CACHE_SCOPE}function stripCacheHintFallback(result){let copy={...result};return delete copy[RESULT_CACHE_HINT_FALLBACK],copy}function inputSchemaMaps(){if(maps)return maps;let s=buildSchemas2026();return maps={request:{"elicitation/create":object({method:literal("elicitation/create"),params:s.ElicitRequestParamsSchema}),"sampling/createMessage":object({method:literal("sampling/createMessage"),params:s.CreateMessageRequestParamsSchema}),"roots/list":object({method:literal("roots/list"),params:looseObject({}).optional()})},response:{"elicitation/create":s.ElicitResultSchema,"sampling/createMessage":s.CreateMessageResultSchema,"roots/list":s.ListRootsResultSchema}},maps}function isInputRequestMethod2026(method){return INPUT_REQUEST_METHODS_2026.includes(method)}function getInputRequestSchema2026(method){return isInputRequestMethod2026(method)?inputSchemaMaps().request[method]:void 0}function getInputResponseSchema2026(method){return isInputRequestMethod2026(method)?inputSchemaMaps().response[method]:void 0}function hasRequestMethod2026(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys,method)}function hasNotificationMethod2026(method){return Object.prototype.hasOwnProperty.call(notificationMethodKeys,method)}function hasResultMethod2026(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys,method)}function getRequestSchema2026(method){return hasRequestMethod2026(method)?buildSchemas2026().dispatchRequestSchemas[method]:void 0}function getResultSchema2026(method){return hasResultMethod2026(method)?buildSchemas2026().dispatchResultSchemas[method]:void 0}function getNotificationSchema2026(method){return hasNotificationMethod2026(method)?buildSchemas2026().notificationSchemas2026[method]:void 0}function isPlainObject$4(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function triState(schema2,raw2){if(schema2===void 0)return{ok:!1,reason:"not-in-era"};let parsed=schema2.safeParse(raw2);return parsed.success?{ok:!0,value:parsed.data}:{ok:!1,reason:"invalid",message:String(parsed.error)}}function enforceDeletedFields(method,result){let next=result,copied=!1,copy=()=>(copied||(next={...next},copied=!0),next),tools=result.tools;method==="tools/list"&&Array.isArray(tools)&&tools.some(tool=>isPlainObject$4(tool)&&"execution"in tool)&&(copy().tools=tools.map(tool=>{if(!isPlainObject$4(tool)||!("execution"in tool))return tool;let rest={...tool};return delete rest.execution,rest}));let capabilities=result.capabilities;if(isPlainObject$4(capabilities)&&"tasks"in capabilities){let rest={...capabilities};delete rest.tasks,copy().capabilities=rest}return next}function getWireResultSchemas(){if(wireResultSchemasMemo)return wireResultSchemasMemo;let s=buildSchemas2026();return wireResultSchemasMemo={"tools/call":s.CallToolResultSchema,"tools/list":s.ListToolsResultSchema,"prompts/get":s.GetPromptResultSchema,"prompts/list":s.ListPromptsResultSchema,"resources/list":s.ListResourcesResultSchema,"resources/templates/list":s.ListResourceTemplatesResultSchema,"resources/read":s.ReadResourceResultSchema,"completion/complete":s.CompleteResultSchema,"server/discover":s.DiscoverResultSchema},wireResultSchemasMemo}function codecForVersion(version2){return version2!==void 0&&isModernProtocolVersion(version2)?rev2026Codec:rev2025Codec}function classifiedWireEra(classification){return classification.revision!==void 0?codecForVersion(classification.revision).era:classification.era==="modern"?rev2026Codec.era:rev2025Codec.era}function isSpecRequestMethod(method){return ALL_CODECS.some(codec=>codec.hasRequestMethod(method))}function isSpecNotificationMethod(method){return ALL_CODECS.some(codec=>codec.hasNotificationMethod(method))}function isExtensionReusedRequestMethod(method){return method==="tasks/get"||method==="tasks/cancel"}function isPlainObject$3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function requestMetaOf(params){if(!isPlainObject$3(params))return;let meta2=params._meta;return isPlainObject$3(meta2)?meta2:void 0}function hasEnvelopeClaim(params){let meta2=requestMetaOf(params);return meta2!==void 0&&PROTOCOL_VERSION_META_KEY in meta2}function envelopeClaimVersion(params){let value=requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY];return typeof value=="string"?value:void 0}function validateEnvelopeMeta(meta2){return codecForVersion(MODERN_WIRE_REVISION).validateEnvelopeMeta(meta2)}function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}function scanXMcpHeaderDeclarations(inputSchema2){let declarations=[],seenLower=new Map,visit=(node,path,reachable)=>{if(node===null||typeof node!="object")return;let schema2=node;if(X_MCP_HEADER_KEY in schema2){if(!reachable||path.length===0)return`${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let raw2=schema2[X_MCP_HEADER_KEY];if(typeof raw2!="string"||raw2.length===0)return`${pathName(path)}: x-mcp-header MUST be a non-empty string`;if(!RFC9110_TOKEN.test(raw2))return`${pathName(path)}: x-mcp-header '${raw2}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let type=typeof schema2.type=="string"?schema2.type:void 0;if(type===void 0||!PERMITTED_X_MCP_HEADER_TYPES.has(type))return`${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type??"<none>"}`;let lower=raw2.toLowerCase(),prior=seenLower.get(lower);if(prior!==void 0)return`x-mcp-header '${raw2}' is not case-insensitively unique (also declared as '${prior}')`;seenLower.set(lower,raw2),declarations.push({path,headerName:raw2,type})}let properties=schema2.properties;if(properties!==null&&typeof properties=="object")for(let[key,child]of Object.entries(properties)){let fault$1=visit(child,[...path,key],reachable);if(fault$1!==void 0)return fault$1}for(let k of NON_REACHABLE_SUBSCHEMA_KEYWORDS){let sub=schema2[k];if(sub===void 0)continue;let branches=Array.isArray(sub)?sub:sub!==null&&typeof sub=="object"&&OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k)?Object.values(sub):[sub];for(let branch of branches){let fault$1=visit(branch,[...path,`<${k}>`],!1);if(fault$1!==void 0)return fault$1}}},fault=visit(inputSchema2,[],!0);return fault===void 0?{valid:!0,declarations}:{valid:!1,reason:fault}}function pathName(path){return path.length===0?"<root>":path.join(".")}function mcpParamPrimitiveToString(value){if(typeof value=="string")return value;if(typeof value=="boolean")return value?"true":"false";if(typeof value=="number")return!Number.isFinite(value)||Number.isInteger(value)&&!Number.isSafeInteger(value)?void 0:String(value)}function base64ToUtf8(b64){let bin=atob(b64),bytes=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)bytes[i]=bin.codePointAt(i);return new TextDecoder("utf-8",{fatal:!0}).decode(bytes)}function decodeMcpParamValue(value){if(!(value.startsWith(BASE64_SENTINEL_PREFIX)&&value.endsWith(BASE64_SENTINEL_SUFFIX)))return value;let b64=value.slice(9,value.length-2);if(BASE64_CANONICAL.test(b64))try{return base64ToUtf8(b64)}catch{return}}function valueAtPath(root,path){let node=root;for(let key of path){if(node===null||typeof node!="object")return;node=node[key]}return node}function validateMcpParamHeaders(declarations,args,headers){for(let decl of declarations){let headerKey=`${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`,headerValue=headers.get(headerKey),bodyRaw=valueAtPath(args,decl.path);if(bodyRaw==null)continue;let bodyString=mcpParamPrimitiveToString(bodyRaw);if(bodyString===void 0)continue;if(headerValue===null)return paramHeaderMismatchRejection("param-header-missing",headerKey,`the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`);let decoded=decodeMcpParamValue(headerValue);if(decoded===void 0)return paramHeaderMismatchRejection("param-header-invalid-encoding",headerKey,`the ${headerKey} header carries an invalid Base64 sentinel value`);if(!((decl.type==="integer"||decl.type==="number")&&CANONICAL_DECIMAL.test(decoded)&&typeof bodyRaw=="number"?Number(decoded)===bodyRaw:decoded===bodyString))return paramHeaderMismatchRejection("param-header-mismatch",headerKey,`the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`)}}function paramHeaderMismatchRejection(cell,header,body){return{kind:"reject",rung:"param-header-validation",cell,httpStatus:400,code:HEADER_MISMATCH_ERROR_CODE,message:`Bad Request: the request headers and body disagree: ${body}`,data:{mismatch:{header,body}},settled:!0}}function httpStatusForErrorCode(code,origin){return origin==="in-band"?code===ProtocolErrorCode.MissingRequiredClientCapability?400:200:LADDER_ERROR_HTTP_STATUS[code]??400}function rejection(rung,cell,httpStatus,error3,settled){return{kind:"reject",rung,cell,httpStatus,code:error3.code,message:error3.message,...error3.data!==void 0&&{data:error3.data},settled}}function crossCheckMismatch(cell,header,body,rung="era-classification"){return rejection(rung,cell,400,new ProtocolError(HEADER_MISMATCH_ERROR_CODE,`Bad Request: the request headers and body disagree: ${body}`,{mismatch:{header,body}}),!0)}function mcpNameSource(method,params){let field=Object.hasOwn(MCP_NAME_HEADER_SOURCE,method)?MCP_NAME_HEADER_SOURCE[method]:void 0;if(field===void 0)return;let raw2=isPlainObject$2(params)?params[field]:void 0;return{field,value:typeof raw2=="string"?raw2:void 0}}function stripHttpOws(value){let start=0;for(;start<value.length;){let code=value.codePointAt(start);if(code!==9&&code!==32)break;start+=1}let end=value.length;for(;end>start;){let code=value.codePointAt(end-1);if(code!==9&&code!==32)break;end-=1}return start===0&&end===value.length?value:value.slice(start,end)}function validateStandardRequestHeaders(request,route){if(route.messageKind!=="request")return;let method=route.message.method;if(request.protocolVersionHeader===void 0){let claimed=route.classification.revision;return crossCheckMismatch("version-header-missing","(missing)",claimed===void 0?"the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent":`the body envelope names protocol version ${claimed} but the required MCP-Protocol-Version header is absent`,"standard-header-validation")}if(request.mcpMethodHeader===void 0)return crossCheckMismatch("method-header-missing","(missing)",`the body names method ${method} but the required Mcp-Method header is absent`,"standard-header-validation");let source=mcpNameSource(method,route.message.params);if(source===void 0)return;let{field:sourceField,value:bodyValue}=source;if(request.mcpNameHeader===void 0)return bodyValue===void 0?void 0:crossCheckMismatch("name-header-missing","(missing)",`the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`,"standard-header-validation");let normalizedNameHeader=stripHttpOws(request.mcpNameHeader),decoded=decodeMcpParamValue(normalizedNameHeader);if(decoded===void 0)return crossCheckMismatch("name-header-invalid-encoding",normalizedNameHeader,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation");if(bodyValue!==void 0&&decoded!==bodyValue)return crossCheckMismatch("name-header-mismatch",normalizedNameHeader,`the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`,"standard-header-validation")}function isPlainObject$2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function classificationForClaim(claimedVersion){return claimedVersion===void 0?{era:"modern"}:{era:isModernProtocolVersion(claimedVersion)?"modern":"legacy",revision:claimedVersion}}function carriesValidModernEnvelopeClaim(params){if(!hasEnvelopeClaim(params))return!1;let claimedVersion=envelopeClaimVersion(params);if(claimedVersion===void 0||!isModernProtocolVersion(claimedVersion))return!1;let meta2=requestMetaOf(params);return meta2!==void 0&&validateEnvelopeMeta(meta2).length===0}function classifyBatch(body){if(body.length===0)return rejection("jsonrpc-shape","empty-batch",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let element of body){if(hasEnvelopeClaim(isPlainObject$2(element)?element.params:void 0))return rejection("jsonrpc-shape","batch-with-modern-element",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(isJSONRPCRequest(element)||isJSONRPCNotification(element)||isJSONRPCResultResponse(element)||isJSONRPCErrorResponse(element)))return rejection("jsonrpc-shape","batch-with-invalid-element",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}function classifyRequestBody(request,body){let params=body.params,method=body.method,headerVersion=request.protocolVersionHeader,headerNamesModern=headerVersion!==void 0&&isModernProtocolVersion(headerVersion);if(method==="initialize"&&!carriesValidModernEnvelopeClaim(params)){if(headerNamesModern)return crossCheckMismatch("initialize-with-modern-header",headerVersion,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let requestedVersion=isPlainObject$2(params)&&typeof params.protocolVersion=="string"?params.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...requestedVersion!==void 0&&{requestedVersion}}}if(hasEnvelopeClaim(params)){let meta2=requestMetaOf(params),firstIssue=(meta2===void 0?[]:validateEnvelopeMeta(meta2))[0];if(firstIssue!==void 0)return rejection("envelope","envelope-invalid",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`,{envelope:firstIssue}),!0);let claimedVersion=envelopeClaimVersion(params);return headerVersion!==void 0&&claimedVersion!==void 0&&headerVersion!==claimedVersion?crossCheckMismatch("header-body-version-mismatch",headerVersion,`the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`):request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("method-header-mismatch",request.mcpMethodHeader,`the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:body,classification:classificationForClaim(claimedVersion)}}if(headerNamesModern){let meta2=requestMetaOf(params),missingFromEnvelope=validateEnvelopeMeta(meta2??{}).filter(issue2=>issue2.problem==="missing").map(issue2=>issue2.key),missing=meta2===void 0?["_meta"]:missingFromEnvelope.length>0?missingFromEnvelope:[PROTOCOL_VERSION_META_KEY];return rejection("envelope","modern-header-without-claim",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`,{envelope:{missing}}),!0)}return{kind:"legacy",reason:"no-claim",...headerVersion!==void 0&&{requestedVersion:headerVersion}}}function classifyNotificationBody(request,body){let params=body.params,method=body.method,headerVersion=request.protocolVersionHeader,headerNamesModern=headerVersion!==void 0&&isModernProtocolVersion(headerVersion);if(hasEnvelopeClaim(params)){let claimedVersion=envelopeClaimVersion(params);if(claimedVersion===void 0){let meta2=requestMetaOf(params),claimIssue=(meta2===void 0?[]:validateEnvelopeMeta(meta2)).find(issue2=>issue2.key===PROTOCOL_VERSION_META_KEY)??{key:PROTOCOL_VERSION_META_KEY,problem:"expected a protocol version string"};return rejection("envelope","notification-envelope-invalid",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`,{envelope:claimIssue}),!0)}if(headerVersion!==void 0&&headerVersion!==claimedVersion)return crossCheckMismatch("notification-header-body-version-mismatch",headerVersion,`the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`);let classification=classificationForClaim(claimedVersion);return classification.era==="modern"&&request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("notification-method-header-mismatch",request.mcpMethodHeader,`the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:body,classification}}return headerNamesModern?request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("notification-method-header-mismatch",request.mcpMethodHeader,`the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:body,classification:{era:"modern",revision:headerVersion}}:{kind:"legacy",reason:"notification",...headerVersion!==void 0&&{requestedVersion:headerVersion}}}function classifyInboundRequest(request){if(request={...request,...request.protocolVersionHeader!==void 0&&{protocolVersionHeader:stripHttpOws(request.protocolVersionHeader)},...request.mcpMethodHeader!==void 0&&{mcpMethodHeader:stripHttpOws(request.mcpMethodHeader)},...request.mcpNameHeader!==void 0&&{mcpNameHeader:stripHttpOws(request.mcpNameHeader)}},request.httpMethod.toUpperCase()!=="POST")return{kind:"legacy",reason:"http-method"};let body=request.body;return Array.isArray(body)?classifyBatch(body):isJSONRPCResultResponse(body)||isJSONRPCErrorResponse(body)?{kind:"legacy",reason:"response"}:isPlainObject$2(body)&&isJSONRPCRequest(body)?classifyRequestBody(request,body):isPlainObject$2(body)&&isJSONRPCNotification(body)?classifyNotificationBody(request,body):rejection("jsonrpc-shape","invalid-json-rpc-body",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}function modernOnlyStrictRejection(route,supportedVersions){switch(route.reason){case"http-method":return rejection("http-method","modern-only-method-not-allowed",405,new ProtocolError(-32e3,"Method not allowed."),!0);case"batch":return rejection("jsonrpc-shape","modern-only-batch-not-supported",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return rejection("jsonrpc-shape","modern-only-response-post",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let requested=route.requestedVersion;return rejection("era-classification","modern-only-missing-envelope",400,requested===void 0?new ProtocolError(ProtocolErrorCode.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...supportedVersions]}):new UnsupportedProtocolVersionError({supported:[...supportedVersions],requested}),!0)}}}function parseSchema(schema2,data){return safeParse2(schema2,data)}function shapeKeys(schemas){return new Set(schemas.flatMap(schema2=>Object.keys(schema2.shape)))}function isStandardSchema(schema2){if(schema2==null)return!1;let schemaType=typeof schema2;return schemaType!=="object"&&schemaType!=="function"||!("~standard"in schema2)?!1:typeof schema2["~standard"]?.validate=="function"}function standardSchemaToJsonSchema(schema2,io="input"){let std=schema2["~standard"],result;if(std.jsonSchema)result=std.jsonSchema[io]({target:JSON_SCHEMA_CONVERSION_TARGET});else if(std.vendor==="zod"){if(!("_zod"in schema2))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");warnedZodFallback||(warnedZodFallback=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),result=toJSONSchema(schema2,{target:JSON_SCHEMA_CONVERSION_TARGET,io})}else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(io==="output")return result.type!==void 0?result:isProvablyObjectShapedRoot(result)?{type:"object",...result}:result;if(result.type!==void 0&&result.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...result}}function isProvablyObjectShapedRoot(schema2){if("properties"in schema2||"patternProperties"in schema2||"additionalProperties"in schema2||"required"in schema2)return!0;for(let key of["oneOf","anyOf","allOf"]){let members=schema2[key];if(Array.isArray(members)&&members.length>0)return members.every(m=>m!==null&&typeof m=="object"&&(m.type==="object"||isProvablyObjectShapedRoot(m)))}return!1}function formatIssue(issue2){return issue2.path?.length?`${issue2.path.map(p=>String(typeof p=="object"?p.key:p)).join(".")}: ${issue2.message}`:issue2.message}async function validateStandardSchema(schema2,data){let result=await schema2["~standard"].validate(data);return result.issues&&result.issues.length>0?{success:!1,error:result.issues.map(i=>formatIssue(i)).join(", ")}:{success:!0,data:result.value}}function zodEmittedPattern(schema2){let jsonSchema=toJSONSchema(schema2,{target:JSON_SCHEMA_CONVERSION_TARGET,io:"input"});return typeof jsonSchema.pattern=="string"?jsonSchema.pattern:void 0}function datetimeReferenceSchemas(pattern){let fractionDigits=DATETIME_FRACTION_DIGITS.exec(pattern),precisions=[void 0,-1,0];return fractionDigits&&precisions.push(Number(fractionDigits[1])),[!1,!0].flatMap(local=>[!1,!0].flatMap(offset=>precisions.map(precision=>iso_exports.datetime({local,offset,precision}))))}function referencePatternsForFormat(format,pattern){let referenceSchemas;switch(format){case"email":referenceSchemas=[email2()];break;case"uri":referenceSchemas=[url()];break;case"date":referenceSchemas=[iso_exports.date()];break;case"date-time":referenceSchemas=datetimeReferenceSchemas(pattern);break}return new Set(referenceSchemas.map(schema2=>zodEmittedPattern(schema2)).filter(emitted=>emitted!==void 0))}function isLibraryFormatPattern(format,pattern,vendor){return vendor!=="zod"?!0:referencePatternsForFormat(format,pattern).has(pattern)}function promptArgumentsFromStandardSchema(schema2){let jsonSchema=standardSchemaToJsonSchema(schema2,"input"),properties=jsonSchema.properties||{},required2=jsonSchema.required||[];return Object.entries(properties).map(([name,prop])=>({name,description:prop?.description,required:required2.includes(name)}))}function isJsonObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function convertStandardElicitationSchema(schema2){try{return standardSchemaToJsonSchema(schema2,"input")}catch(error3){let detail=error3 instanceof Error?error3.message:String(error3);throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`)}}function isAnnotationOnlyJsonSchemaKeyword(key){return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key)||key.startsWith("x-")}function walkProperty(node,path,vendor,unsupported){if(!isJsonObject(node))return node;let allowedKeys=typeof node.type=="string"&&Object.hasOwn(PROPERTY_KEYS_BY_TYPE,node.type)?PROPERTY_KEYS_BY_TYPE[node.type]:void 0;if(allowedKeys===void 0)return node;let pruned={};for(let[key,value]of Object.entries(node))allowedKeys.has(key)||isAnnotationOnlyJsonSchemaKeyword(key)?pruned[key]=value:key==="pattern"&&node.type==="string"&&typeof node.format=="string"?SUPPORTED_STRING_FORMATS.has(node.format)?(typeof value!="string"||!isLibraryFormatPattern(node.format,value,vendor))&&unsupported.push(`${path}.${key}`):pruned[key]=value:unsupported.push(`${path}.${key}`);return pruned}function walkRequestedSchema(converted,vendor){let pruned={},unsupported=[];for(let[key,value]of Object.entries(converted))key==="properties"&&isJsonObject(value)?pruned[key]=Object.fromEntries(Object.entries(value).map(([name,node])=>[name,walkProperty(node,`properties.${name}`,vendor,unsupported)])):ROOT_KEYS.has(key)?pruned[key]=value:isAnnotationOnlyJsonSchemaKeyword(key)||unsupported.push(key);if(unsupported.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`);return pruned}function describeUnsupportedProperties(pruned,fallback){if(!isJsonObject(pruned.properties))return fallback;let offenders=Object.entries(pruned.properties).filter(([,node])=>!parseSchema(PrimitiveSchemaDefinitionSchema,node).success).map(([name])=>`properties.${name}`);return offenders.length>0?offenders.join(", "):fallback}function findDroppedConstraintPaths(original,parsed,path=""){return Array.isArray(original)&&Array.isArray(parsed)?original.flatMap((item,index)=>findDroppedConstraintPaths(item,parsed[index],`${path}[${index}]`)):!isJsonObject(original)||!isJsonObject(parsed)?[]:Object.entries(original).flatMap(([key,value])=>{let childPath=path?`${path}.${key}`:key;return Object.prototype.hasOwnProperty.call(parsed,key)?findDroppedConstraintPaths(value,parsed[key],childPath):isAnnotationOnlyJsonSchemaKeyword(key)?[]:[childPath]})}function normalizeElicitInputParams(input){if(!isStandardSchema(input.requestedSchema))return{...input,mode:"form",requestedSchema:input.requestedSchema};let vendor=input.requestedSchema["~standard"].vendor,pruned=walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema),vendor),parsed=parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema,pruned);if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned,parsed.error.message)}`);let droppedConstraints=findDroppedConstraintPaths(pruned,parsed.data);if(droppedConstraints.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`);let danglingRequired=(parsed.data.required??[]).filter(key=>!Object.prototype.hasOwnProperty.call(parsed.data.properties,key));if(danglingRequired.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`);return{...input,mode:"form",requestedSchema:parsed.data}}function buildInputRequired(spec){let hasInputRequests=spec.inputRequests!==void 0&&Object.keys(spec.inputRequests).length>0,hasRequestState=typeof spec.requestState=="string";if(!hasInputRequests&&!hasRequestState)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...spec.inputRequests!==void 0&&{inputRequests:spec.inputRequests},...spec.requestState!==void 0&&{requestState:spec.requestState}}}function acceptedContent(responses,key,schema2){let view=inputResponse(responses,key);if(view.kind!=="elicit"||view.action!=="accept"||view.content===void 0)return;if(schema2===void 0)return view.content;let outcome=schema2["~standard"].validate(view.content);if(outcome instanceof Promise)throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema");return outcome.issues===void 0?outcome.value:void 0}function inputResponse(responses,key){if(responses===void 0||typeof responses!="object"||responses===null)return{kind:"missing"};let entry=responses[key];if(entry===null||typeof entry!="object"||Array.isArray(entry))return{kind:"missing"};let candidate=entry;if(candidate.action==="accept"||candidate.action==="decline"||candidate.action==="cancel"){let content=candidate.content;return{kind:"elicit",action:candidate.action,...content!==null&&typeof content=="object"&&!Array.isArray(content)&&{content}}}return Array.isArray(candidate.roots)?{kind:"roots",roots:candidate.roots}:typeof candidate.role=="string"&&candidate.content!==void 0?{kind:"sampling",result:candidate}:{kind:"missing"}}function inputRequiredRoundsExceededMessage(method,maxRounds){return`Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(signal.reason instanceof SdkError?signal.reason:new SdkError(SdkErrorCode.RequestTimeout,String(signal.reason)));return}let timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{clearTimeout(timer),reject(signal?.reason instanceof SdkError?signal.reason:new SdkError(SdkErrorCode.RequestTimeout,String(signal?.reason)))};signal?.addEventListener("abort",onAbort,{once:!0})})}function linkedRoundAbort(outer){let controller=new AbortController,onOuterAbort=()=>controller.abort(outer?.reason);return outer?.addEventListener("abort",onOuterAbort,{once:!0}),outer?.aborted&&controller.abort(outer.reason),{signal:controller.signal,abort:reason=>controller.abort(reason),dispose:()=>outer?.removeEventListener("abort",onOuterAbort)}}function register(key,schema2){let name=key.slice(0,-6);_specTypeSchemas[name]=schema2,_isSpecType[name]=v=>schema2.safeParse(v).success}function bootstrapOutboundCodec(method){switch(method){case"initialize":case"notifications/initialized":return codecForVersion(void 0);case"server/discover":return codecForVersion(MODERN_WIRE_REVISION);default:return}}function liftWireOnlyMaterial(message,kind){let params=message.params;if(!isPlainObject$1(params))return{message,lifted:{}};let meta2=params._meta,envelopeKeys=isPlainObject$1(meta2)?RESERVED_ENVELOPE_META_KEYS.filter(key=>key in meta2):[],retryKeys=kind==="request"?RETRY_PARAMS_KEYS.filter(key=>key in params):[];if(envelopeKeys.length===0&&retryKeys.length===0)return{message,lifted:{}};let lifted={},nextParams={...params};if(envelopeKeys.length>0&&isPlainObject$1(meta2)){let envelope={},nextMeta={...meta2};for(let key of envelopeKeys)envelope[key]=meta2[key],delete nextMeta[key];lifted.envelope=envelope,Object.keys(nextMeta).length>0?nextParams._meta=nextMeta:delete nextParams._meta}for(let key of retryKeys)key==="inputResponses"&&(lifted.inputResponses=nextParams[key]),key==="requestState"&&(lifted.requestState=nextParams[key]),delete nextParams[key];return{message:{...message,params:nextParams},lifted}}function codecResultValidator(codec,method){let probe=codec.validateResult(method,void 0);if(!(!probe.ok&&probe.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(value){let outcome=codec.validateResult(method,value);return outcome.ok?{value:outcome.value}:{issues:[{message:outcome.reason==="invalid"?outcome.message:`not-in-era: ${method}`}]}}}}}function requestStateAccessor(value){return()=>value}function withRequestStateValue(ctx,value){return{...ctx,mcpReq:{...ctx.mcpReq,requestState:requestStateAccessor(value)}}}function setNegotiatedProtocolVersion(instance,version2){writeNegotiatedProtocolVersion(instance,version2)}function isPlainObject$1(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];result[k]=isPlainObject$1(baseValue)&&isPlainObject$1(addValue)?{...baseValue,...addValue}:addValue}return result}function isPlainObject2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function partitionInputResponses(inputResponses){let accepted={},droppedKeys=[];if(!isPlainObject2(inputResponses))return{accepted,droppedKeys};for(let[key,entry]of Object.entries(inputResponses)){if(!isPlainObject2(entry)||"method"in entry||"result"in entry){droppedKeys.push(key);continue}accepted[key]=entry}return{accepted,droppedKeys}}function manualInputRequiredValue(decoded){return{resultType:"input_required",inputRequests:decoded.inputRequests,...decoded.requestState!==void 0&&{requestState:decoded.requestState},...decoded._meta!==void 0&&{_meta:decoded._meta}}}function mediaTypeEssence(header){if(header)try{return import_content_type.parse(header).type}catch{let essence=(header.split(";",1)[0]??"").trim().toLowerCase();return essence===""||header.slice(essence.length).includes(",")?void 0:essence}}function isJsonContentType(header){return header==="application/json"?!0:mediaTypeEssence(header)==="application/json"}function validateToolName(name){let warnings=[];if(name.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(name.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]};if(name.includes(" ")&&warnings.push("Tool name contains spaces, which may cause parsing issues"),name.includes(",")&&warnings.push("Tool name contains commas, which may cause parsing issues"),(name.startsWith("-")||name.endsWith("-"))&&warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(name.startsWith(".")||name.endsWith("."))&&warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!TOOL_NAME_REGEX.test(name)){let invalidChars=[...name].filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index,arr)=>arr.indexOf(char)===index);return warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c=>`"${c}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings}}return{isValid:!0,warnings}}function issueToolNameWarning(name,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name}":`);for(let warning of warnings)console.warn(` - ${warning}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function validateAndWarnToolName(name){let result=validateToolName(name);return issueToolNameWarning(name,result.warnings),result.isValid}function isZodV4Schema(v){return typeof v=="object"&&v!==null&&"_zod"in v}function looksLikeZodV3(v){return typeof v=="object"&&v!==null&&!("_zod"in v)&&"_def"in v&&typeof v._def?.typeName=="string"}function isZodRawShape(obj){if(typeof obj!="object"||obj===null||isStandardSchema(obj))return!1;let proto=Object.getPrototypeOf(obj);return proto!==Object.prototype&&proto!==null?!1:Object.values(obj).every(v=>isZodV4Schema(v))}function normalizeRawShapeSchema(schema2){if(schema2!==void 0){if(isZodRawShape(schema2))return object(schema2);if(typeof schema2=="object"&&schema2!==null&&!isStandardSchema(schema2)&&Object.values(schema2).some(v=>looksLikeZodV3(v)))throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!isStandardSchema(schema2))throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return schema2}}function fromJsonSchema(schema2,validator){let check=validator.getValidator(schema2);return{"~standard":{version:1,vendor:"mcp",jsonSchema:{input:()=>schema2,output:()=>schema2},validate:data=>{let result=check(data);return result.valid?{value:result.data}:{issues:[{message:result.errorMessage}]}}}}}var BRANDS,OAuthErrorCode,OAuthError,SdkErrorCode,SdkError,SdkHttpError,REQUIRED_CLIENT_CAPABILITIES_BY_METHOD,FIRST_MODERN_PROTOCOL_VERSION,SUPPORTED_MODERN_PROTOCOL_VERSIONS,TOOL_RESULT_FOREIGN_FAMILY_KEYS,memo$1,REF_REWRITE_DATA_POSITION_KEYS,REF_REWRITE_NAME_MAP_KEYS,requestMethodKeys$1,notificationMethodKeys$1,resultMethodKeys,maps$1,rev2025RequestMethods,rev2025NotificationMethods,NOT_IN_ERA$1,rev2025Codec,memo,CACHEABLE_RESULT_METHODS,RESULT_CACHE_HINT_FALLBACK,ProtocolErrorCode,ProtocolError,ResourceNotFoundError,UrlElicitationRequiredError,UnsupportedProtocolVersionError,MissingRequiredClientCapabilityError,DEFAULT_CACHE_TTL_MS,DEFAULT_CACHE_SCOPE,EXTENDED_RESULT_TYPE_METHODS,INPUT_REQUEST_METHODS_2026,maps,requestMethodKeys,notificationMethodKeys,rev2026RequestMethods,rev2026NotificationMethods,NOT_IN_ERA,REQUIRED_ENVELOPE_KEYS,rev2026Codec,wireResultSchemasMemo,MODERN_WIRE_REVISION,ALL_CODECS,schemas_exports2,isJSONRPCRequest,isJSONRPCNotification,isJSONRPCResultResponse,isJSONRPCErrorResponse,isInputRequiredResult,isInitializeRequest,MCP_PARAM_HEADER_PREFIX,X_MCP_HEADER_KEY,RFC9110_TOKEN,PERMITTED_X_MCP_HEADER_TYPES,NON_REACHABLE_SUBSCHEMA_KEYWORDS,OBJECT_VALUED_SUBSCHEMA_KEYWORDS,BASE64_SENTINEL_PREFIX,BASE64_SENTINEL_SUFFIX,BASE64_CANONICAL,CANONICAL_DECIMAL,HEADER_MISMATCH_ERROR_CODE,INBOUND_VALIDATION_LADDER,LADDER_ERROR_HTTP_STATUS,MCP_NAME_HEADER_SOURCE,warnedZodFallback,JSON_SCHEMA_CONVERSION_TARGET,DATETIME_FRACTION_DIGITS,ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS,ROOT_KEYS,PROPERTY_KEYS_BY_TYPE,SUPPORTED_STRING_FORMATS,inputRequired,REQUEST_STATE_ONLY_LEG_PACING_MS,SPEC_SCHEMA_KEYS,authSchemas,_specTypeSchemas,_isSpecType,specTypeSchemas,isSpecType,DEFAULT_REQUEST_TIMEOUT_MSEC,RESERVED_ENVELOPE_META_KEYS,RETRY_PARAMS_KEYS,NO_REQUEST_STATE,writeNegotiatedProtocolVersion,Protocol,require_content_type,import_content_type,STDIO_DEFAULT_MAX_BUFFER_SIZE,TOOL_NAME_REGEX,MAX_TEMPLATE_LENGTH,MAX_VARIABLE_LENGTH,MAX_TEMPLATE_EXPRESSIONS,MAX_REGEX_LENGTH,UriTemplate,init_src_Cqbh3MYc=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/src-Cqbh3MYc.mjs"(){"use strict";init_chunk_Br0eD_fh();init_dialects_DoSzNhcb();init_internal();init_v4();BRANDS=Symbol.for("mcp.sdk.errorBrands");OAuthErrorCode=(function(OAuthErrorCode$1){return OAuthErrorCode$1.InvalidRequest="invalid_request",OAuthErrorCode$1.InvalidClient="invalid_client",OAuthErrorCode$1.InvalidGrant="invalid_grant",OAuthErrorCode$1.UnauthorizedClient="unauthorized_client",OAuthErrorCode$1.UnsupportedGrantType="unsupported_grant_type",OAuthErrorCode$1.InvalidScope="invalid_scope",OAuthErrorCode$1.AccessDenied="access_denied",OAuthErrorCode$1.ServerError="server_error",OAuthErrorCode$1.TemporarilyUnavailable="temporarily_unavailable",OAuthErrorCode$1.UnsupportedResponseType="unsupported_response_type",OAuthErrorCode$1.UnsupportedTokenType="unsupported_token_type",OAuthErrorCode$1.InvalidToken="invalid_token",OAuthErrorCode$1.MethodNotAllowed="method_not_allowed",OAuthErrorCode$1.TooManyRequests="too_many_requests",OAuthErrorCode$1.InvalidClientMetadata="invalid_client_metadata",OAuthErrorCode$1.InvalidRedirectUri="invalid_redirect_uri",OAuthErrorCode$1.InsufficientScope="insufficient_scope",OAuthErrorCode$1.InvalidTarget="invalid_target",OAuthErrorCode$1.InvalidDpopProof="invalid_dpop_proof",OAuthErrorCode$1.UseDpopNonce="use_dpop_nonce",OAuthErrorCode$1})({}),OAuthError=class OAuthError2 extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,errorUri){super(message),this.code=code,this.errorUri=errorUri,this.name="OAuthError",stampErrorBrands(this,new.target)}toResponseObject(){let response={error:this.code,error_description:this.message};return this.errorUri&&(response.error_uri=this.errorUri),response}static fromResponse(response){return new OAuthError2(response.error,response.error_description??response.error,response.error_uri)}},SdkErrorCode=(function(SdkErrorCode$1){return SdkErrorCode$1.NotConnected="NOT_CONNECTED",SdkErrorCode$1.AlreadyConnected="ALREADY_CONNECTED",SdkErrorCode$1.NotInitialized="NOT_INITIALIZED",SdkErrorCode$1.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",SdkErrorCode$1.RequestTimeout="REQUEST_TIMEOUT",SdkErrorCode$1.ConnectionClosed="CONNECTION_CLOSED",SdkErrorCode$1.SendFailed="SEND_FAILED",SdkErrorCode$1.InvalidResult="INVALID_RESULT",SdkErrorCode$1.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",SdkErrorCode$1.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",SdkErrorCode$1.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",SdkErrorCode$1.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",SdkErrorCode$1.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",SdkErrorCode$1.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",SdkErrorCode$1.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",SdkErrorCode$1.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",SdkErrorCode$1.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",SdkErrorCode$1.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",SdkErrorCode$1.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",SdkErrorCode$1})({}),SdkError=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,data,options){super(message,options),this.code=code,this.data=data,this.name="SdkError",stampErrorBrands(this,new.target)}},SdkHttpError=class extends SdkError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(code,message,data,options){super(code,message,data,options),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}},REQUIRED_CLIENT_CAPABILITIES_BY_METHOD={};FIRST_MODERN_PROTOCOL_VERSION="2026-07-28",SUPPORTED_MODERN_PROTOCOL_VERSIONS=[FIRST_MODERN_PROTOCOL_VERSION];TOOL_RESULT_FOREIGN_FAMILY_KEYS=["task","inputRequests","requestState"];REF_REWRITE_DATA_POSITION_KEYS=new Set(["const","enum","default","examples"]),REF_REWRITE_NAME_MAP_KEYS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);requestMethodKeys$1={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},notificationMethodKeys$1={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},resultMethodKeys={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};rev2025RequestMethods=Object.keys(requestMethodKeys$1),rev2025NotificationMethods=Object.keys(notificationMethodKeys$1);NOT_IN_ERA$1={ok:!1,reason:"not-in-era"};rev2025Codec={era:"2025-11-25",hasRequestMethod:hasRequestMethod2025,hasNotificationMethod:hasNotificationMethod2025,validateRequest:(method,raw2)=>triState$1(getRequestSchema(method),raw2),validateResult:(method,raw2)=>triState$1(getResultSchema(method),raw2),validateNotification:(method,raw2)=>triState$1(getNotificationSchema(method),raw2),hasInputRequestMethod:()=>!1,validateInputRequest:()=>NOT_IN_ERA$1,validateInputResponse:()=>NOT_IN_ERA$1,samplingResultVariant:((hasTools,raw2)=>{let s=buildSchemas2025();return triState$1(hasTools?s.CreateMessageResultWithToolsSchema:s.CreateMessageResultSchema,raw2)}),outboundEnvelope:_material=>{},validateEnvelopeMeta:_meta=>[],projectCallToolResult(result,advertisedOutputSchema){let withText=appendTextFallbackForNonObject(result),sc=withText.structuredContent;if(sc===void 0)return withText;let valueIsNonObject=typeof sc!="object"||sc===null||Array.isArray(sc),schemaWrapped=advertisedOutputSchema!==void 0&&isNonObjectJsonSchemaRoot(advertisedOutputSchema);return!valueIsNonObject&&!schemaWrapped?withText:{...withText,structuredContent:{result:sc}}},decodeResult(_method,raw2){if(isPlainObject$6(raw2)&&"resultType"in raw2){let stripped={...raw2};return delete stripped.resultType,{kind:"complete",result:stripped}}return{kind:"complete",result:raw2}},encodeResult(method,result){if(method!=="tools/list")return result;let tools=result.tools;return!Array.isArray(tools)||!tools.some(t=>toolNeedsLegacyWrap(t))?result:{...result,tools:tools.map(t=>toolNeedsLegacyWrap(t)?{...t,outputSchema:wrapOutputSchemaForLegacy(t.outputSchema)}:t)}},encodeErrorCode:code=>code===-32002?-32602:code,checkInboundEnvelope:_material=>{}};CACHEABLE_RESULT_METHODS=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];RESULT_CACHE_HINT_FALLBACK=Symbol("modelcontextprotocol.resultCacheHintFallback");ProtocolErrorCode=(function(ProtocolErrorCode$1){return ProtocolErrorCode$1[ProtocolErrorCode$1.ParseError=-32700]="ParseError",ProtocolErrorCode$1[ProtocolErrorCode$1.InvalidRequest=-32600]="InvalidRequest",ProtocolErrorCode$1[ProtocolErrorCode$1.MethodNotFound=-32601]="MethodNotFound",ProtocolErrorCode$1[ProtocolErrorCode$1.InvalidParams=-32602]="InvalidParams",ProtocolErrorCode$1[ProtocolErrorCode$1.InternalError=-32603]="InternalError",ProtocolErrorCode$1[ProtocolErrorCode$1.ResourceNotFound=-32002]="ResourceNotFound",ProtocolErrorCode$1[ProtocolErrorCode$1.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",ProtocolErrorCode$1[ProtocolErrorCode$1.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",ProtocolErrorCode$1[ProtocolErrorCode$1.UrlElicitationRequired=-32042]="UrlElicitationRequired",ProtocolErrorCode$1})({}),ProtocolError=class ProtocolError2 extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,data){super(message),this.code=code,this.data=data,this.name="ProtocolError",stampErrorBrands(this,new.target)}static fromError(code,message,data){if(code===ProtocolErrorCode.UrlElicitationRequired&&data){let errorData=data;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}if(code===ProtocolErrorCode.UnsupportedProtocolVersion&&data){let errorData=data;if(Array.isArray(errorData.supported)&&typeof errorData.requested=="string")return new UnsupportedProtocolVersionError({supported:errorData.supported,requested:errorData.requested},message)}if(code===ProtocolErrorCode.InvalidParams||code===ProtocolErrorCode.ResourceNotFound){let errorData=data;if(typeof errorData?.uri=="string"&&(code===ProtocolErrorCode.ResourceNotFound||Object.keys(errorData).length===1))return new ResourceNotFoundError(errorData.uri,message)}if(code===ProtocolErrorCode.MissingRequiredClientCapability&&data){let errorData=data;if(errorData.requiredCapabilities!==null&&typeof errorData.requiredCapabilities=="object"&&!Array.isArray(errorData.requiredCapabilities))return new MissingRequiredClientCapabilityError({requiredCapabilities:errorData.requiredCapabilities},message)}return new ProtocolError2(code,message,data)}},ResourceNotFoundError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(uri,message=`Resource not found: ${uri}`){super(ProtocolErrorCode.InvalidParams,message,{uri})}get uri(){return this.data.uri}},UrlElicitationRequiredError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ProtocolErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}},UnsupportedProtocolVersionError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(data,message=`Unsupported protocol version: ${data.requested}`){super(ProtocolErrorCode.UnsupportedProtocolVersion,message,data)}get supported(){return this.data.supported}get requested(){return this.data.requested}},MissingRequiredClientCapabilityError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(data,message=`Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`){super(ProtocolErrorCode.MissingRequiredClientCapability,message,data)}get requiredCapabilities(){return this.data.requiredCapabilities}},DEFAULT_CACHE_TTL_MS=0,DEFAULT_CACHE_SCOPE="private",EXTENDED_RESULT_TYPE_METHODS=["tools/call","prompts/get","resources/read"];INPUT_REQUEST_METHODS_2026=["elicitation/create","sampling/createMessage","roots/list"];requestMethodKeys={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},notificationMethodKeys={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};rev2026RequestMethods=Object.keys(requestMethodKeys),rev2026NotificationMethods=Object.keys(notificationMethodKeys);NOT_IN_ERA={ok:!1,reason:"not-in-era"},REQUIRED_ENVELOPE_KEYS=[PROTOCOL_VERSION_META_KEY,CLIENT_CAPABILITIES_META_KEY];rev2026Codec={era:"2026-07-28",hasRequestMethod:hasRequestMethod2026,hasNotificationMethod:hasNotificationMethod2026,hasInputRequestMethod:method=>getInputRequestSchema2026(method)!==void 0,validateRequest:(method,raw2)=>triState(getRequestSchema2026(method),raw2),validateResult:(method,raw2)=>triState(getResultSchema2026(method),raw2),validateNotification:(method,raw2)=>triState(getNotificationSchema2026(method),raw2),validateInputRequest:(method,raw2)=>triState(getInputRequestSchema2026(method),raw2),validateInputResponse:(method,raw2)=>triState(getInputResponseSchema2026(method),raw2),samplingResultVariant:()=>NOT_IN_ERA,outboundEnvelope(material){return{[PROTOCOL_VERSION_META_KEY]:material.protocolVersion,[CLIENT_INFO_META_KEY]:material.clientInfo,[CLIENT_CAPABILITIES_META_KEY]:material.clientCapabilities,...material.logLevel!==void 0&&{[LOG_LEVEL_META_KEY]:material.logLevel}}},validateEnvelopeMeta(meta2){let issues=[];for(let key of REQUIRED_ENVELOPE_KEYS)key in meta2||issues.push({key,problem:"missing"});let parsed=buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta2);if(!parsed.success)for(let issue2 of parsed.error.issues){let path=issue2.path.map(String),key=path.length>0?path.join("."):"_meta";path.length===1&&issues.some(existing=>existing.key===key&&existing.problem==="missing")||issues.push({key,problem:issue2.message})}return issues},projectCallToolResult:result=>appendTextFallbackForNonObject(result),inputRequestSchema:getInputRequestSchema2026,decodeResult(method,raw2){if(!isPlainObject$4(raw2))return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: not an object`,{method})};let rawResultType=raw2.resultType;if(rawResultType===void 0)return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method,violation:"missing-resultType"})};if(typeof rawResultType!="string")return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: non-string resultType`,{method,resultType:rawResultType})};if(rawResultType==="input_required"){let rawInputRequests=raw2.inputRequests,inputRequests=isPlainObject$4(rawInputRequests)?rawInputRequests:{},requestState=raw2.requestState,metaParse=raw2._meta===void 0?void 0:buildSchemas2026().ResultMetaSchema.safeParse(raw2._meta),meta2=metaParse?.success?metaParse.data:void 0;return Object.keys(inputRequests).length===0&&typeof requestState!="string"?{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests,...typeof requestState=="string"&&{requestState},...meta2!==void 0&&{_meta:meta2}}}if(rawResultType!=="complete")return{kind:"invalid",error:new SdkError(SdkErrorCode.UnsupportedResultType,`Unsupported result type '${rawResultType}' for ${method}`,{resultType:rawResultType,method})};let wireResultSchemas=getWireResultSchemas(),wireSchema=Object.hasOwn(wireResultSchemas,method)?wireResultSchemas[method]:void 0;if(wireSchema!==void 0){let parsed=wireSchema.safeParse(raw2);if(!parsed.success)return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: ${parsed.error}`,{method})}}let lifted={...raw2};return delete lifted.resultType,{kind:"complete",result:lifted}},encodeResult(method,result,serverInfo){return stampServerInfoMeta(fillCacheFields(method,stampResultType(method,enforceDeletedFields(method,result))),serverInfo)},encodeErrorCode:code=>code===-32002?-32602:code,checkInboundEnvelope(material){if(material.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let parsed=buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope);if(!parsed.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map(issue2=>issue2.message).join("; ")}`}};MODERN_WIRE_REVISION="2026-07-28";ALL_CODECS=[rev2025Codec,rev2026Codec];schemas_exports2=__exportAll({AnnotationsSchema:()=>AnnotationsSchema,AudioContentSchema:()=>AudioContentSchema,BaseMetadataSchema:()=>BaseMetadataSchema,BaseRequestParamsSchema:()=>BaseRequestParamsSchema,BlobResourceContentsSchema:()=>BlobResourceContentsSchema,BooleanSchemaSchema:()=>BooleanSchemaSchema,CallToolRequestParamsSchema:()=>CallToolRequestParamsSchema,CallToolRequestSchema:()=>CallToolRequestSchema,CallToolResultSchema:()=>CallToolResultSchema,CancelTaskRequestSchema:()=>CancelTaskRequestSchema,CancelTaskResultSchema:()=>CancelTaskResultSchema,CancelledNotificationParamsSchema:()=>CancelledNotificationParamsSchema,CancelledNotificationSchema:()=>CancelledNotificationSchema,ClientCapabilitiesSchema:()=>ClientCapabilitiesSchema,ClientNotificationSchema:()=>ClientNotificationSchema,ClientRequestSchema:()=>ClientRequestSchema,ClientResultSchema:()=>ClientResultSchema,ClientTasksCapabilitySchema:()=>ClientTasksCapabilitySchema,CompatibilityCallToolResultSchema:()=>CompatibilityCallToolResultSchema,CompleteRequestParamsSchema:()=>CompleteRequestParamsSchema,CompleteRequestSchema:()=>CompleteRequestSchema,CompleteResultSchema:()=>CompleteResultSchema,ContentBlockSchema:()=>ContentBlockSchema,CreateMessageRequestParamsSchema:()=>CreateMessageRequestParamsSchema,CreateMessageRequestSchema:()=>CreateMessageRequestSchema,CreateMessageResultSchema:()=>CreateMessageResultSchema,CreateMessageResultWithToolsSchema:()=>CreateMessageResultWithToolsSchema,CreateTaskResultSchema:()=>CreateTaskResultSchema,CursorSchema:()=>CursorSchema,DiscoverRequestSchema:()=>DiscoverRequestSchema,DiscoverResultSchema:()=>DiscoverResultSchema,ElicitRequestFormParamsSchema:()=>ElicitRequestFormParamsSchema,ElicitRequestParamsSchema:()=>ElicitRequestParamsSchema,ElicitRequestSchema:()=>ElicitRequestSchema,ElicitRequestURLParamsSchema:()=>ElicitRequestURLParamsSchema,ElicitResultSchema:()=>ElicitResultSchema,ElicitationCompleteNotificationParamsSchema:()=>ElicitationCompleteNotificationParamsSchema,ElicitationCompleteNotificationSchema:()=>ElicitationCompleteNotificationSchema,EmbeddedResourceSchema:()=>EmbeddedResourceSchema,EmptyResultSchema:()=>EmptyResultSchema,EnumSchemaSchema:()=>EnumSchemaSchema,GetPromptRequestParamsSchema:()=>GetPromptRequestParamsSchema,GetPromptRequestSchema:()=>GetPromptRequestSchema,GetPromptResultSchema:()=>GetPromptResultSchema,GetTaskPayloadRequestSchema:()=>GetTaskPayloadRequestSchema,GetTaskPayloadResultSchema:()=>GetTaskPayloadResultSchema,GetTaskRequestSchema:()=>GetTaskRequestSchema,GetTaskResultSchema:()=>GetTaskResultSchema,IconSchema:()=>IconSchema,IconsSchema:()=>IconsSchema,ImageContentSchema:()=>ImageContentSchema,ImplementationSchema:()=>ImplementationSchema,InitializeRequestParamsSchema:()=>InitializeRequestParamsSchema,InitializeRequestSchema:()=>InitializeRequestSchema,InitializeResultSchema:()=>InitializeResultSchema,InitializedNotificationSchema:()=>InitializedNotificationSchema,JSONArraySchema:()=>JSONArraySchema,JSONObjectSchema:()=>JSONObjectSchema,JSONRPCErrorResponseSchema:()=>JSONRPCErrorResponseSchema,JSONRPCMessageSchema:()=>JSONRPCMessageSchema,JSONRPCNotificationSchema:()=>JSONRPCNotificationSchema,JSONRPCRequestSchema:()=>JSONRPCRequestSchema,JSONRPCResponseSchema:()=>JSONRPCResponseSchema,JSONRPCResultResponseSchema:()=>JSONRPCResultResponseSchema,JSONValueSchema:()=>JSONValueSchema,LegacyTitledEnumSchemaSchema:()=>LegacyTitledEnumSchemaSchema,ListChangedOptionsBaseSchema:()=>ListChangedOptionsBaseSchema,ListPromptsRequestSchema:()=>ListPromptsRequestSchema,ListPromptsResultSchema:()=>ListPromptsResultSchema,ListResourceTemplatesRequestSchema:()=>ListResourceTemplatesRequestSchema,ListResourceTemplatesResultSchema:()=>ListResourceTemplatesResultSchema,ListResourcesRequestSchema:()=>ListResourcesRequestSchema,ListResourcesResultSchema:()=>ListResourcesResultSchema,ListRootsRequestSchema:()=>ListRootsRequestSchema,ListRootsResultSchema:()=>ListRootsResultSchema,ListTasksRequestSchema:()=>ListTasksRequestSchema,ListTasksResultSchema:()=>ListTasksResultSchema,ListToolsRequestSchema:()=>ListToolsRequestSchema,ListToolsResultSchema:()=>ListToolsResultSchema,LoggingLevelSchema:()=>LoggingLevelSchema,LoggingMessageNotificationParamsSchema:()=>LoggingMessageNotificationParamsSchema,LoggingMessageNotificationSchema:()=>LoggingMessageNotificationSchema,ModelHintSchema:()=>ModelHintSchema,ModelPreferencesSchema:()=>ModelPreferencesSchema,MultiSelectEnumSchemaSchema:()=>MultiSelectEnumSchemaSchema,NotificationSchema:()=>NotificationSchema,NotificationsParamsSchema:()=>NotificationsParamsSchema,NumberSchemaSchema:()=>NumberSchemaSchema,PaginatedRequestParamsSchema:()=>PaginatedRequestParamsSchema,PaginatedRequestSchema:()=>PaginatedRequestSchema,PaginatedResultSchema:()=>PaginatedResultSchema,PingRequestSchema:()=>PingRequestSchema,PrimitiveSchemaDefinitionSchema:()=>PrimitiveSchemaDefinitionSchema,ProgressNotificationParamsSchema:()=>ProgressNotificationParamsSchema,ProgressNotificationSchema:()=>ProgressNotificationSchema,ProgressSchema:()=>ProgressSchema,ProgressTokenSchema:()=>ProgressTokenSchema,PromptArgumentSchema:()=>PromptArgumentSchema,PromptListChangedNotificationSchema:()=>PromptListChangedNotificationSchema,PromptMessageSchema:()=>PromptMessageSchema,PromptReferenceSchema:()=>PromptReferenceSchema,PromptSchema:()=>PromptSchema,ReadResourceRequestParamsSchema:()=>ReadResourceRequestParamsSchema,ReadResourceRequestSchema:()=>ReadResourceRequestSchema,ReadResourceResultSchema:()=>ReadResourceResultSchema,RelatedTaskMetadataSchema:()=>RelatedTaskMetadataSchema,RequestIdSchema:()=>RequestIdSchema,RequestMetaSchema:()=>RequestMetaSchema,RequestSchema:()=>RequestSchema,ResourceContentsSchema:()=>ResourceContentsSchema,ResourceLinkSchema:()=>ResourceLinkSchema,ResourceListChangedNotificationSchema:()=>ResourceListChangedNotificationSchema,ResourceRequestParamsSchema:()=>ResourceRequestParamsSchema,ResourceSchema:()=>ResourceSchema,ResourceTemplateReferenceSchema:()=>ResourceTemplateReferenceSchema,ResourceTemplateSchema:()=>ResourceTemplateSchema,ResourceUpdatedNotificationParamsSchema:()=>ResourceUpdatedNotificationParamsSchema,ResourceUpdatedNotificationSchema:()=>ResourceUpdatedNotificationSchema,ResultMetaObjectSchema:()=>ResultMetaObjectSchema,ResultSchema:()=>ResultSchema,RoleSchema:()=>RoleSchema,RootSchema:()=>RootSchema,RootsListChangedNotificationSchema:()=>RootsListChangedNotificationSchema,SamplingContentSchema:()=>SamplingContentSchema,SamplingMessageContentBlockSchema:()=>SamplingMessageContentBlockSchema,SamplingMessageSchema:()=>SamplingMessageSchema,ServerCapabilitiesSchema:()=>ServerCapabilitiesSchema,ServerNotificationSchema:()=>ServerNotificationSchema,ServerRequestSchema:()=>ServerRequestSchema,ServerResultSchema:()=>ServerResultSchema,ServerTasksCapabilitySchema:()=>ServerTasksCapabilitySchema,SetLevelRequestParamsSchema:()=>SetLevelRequestParamsSchema,SetLevelRequestSchema:()=>SetLevelRequestSchema,SingleSelectEnumSchemaSchema:()=>SingleSelectEnumSchemaSchema,StringSchemaSchema:()=>StringSchemaSchema,SubscribeRequestParamsSchema:()=>SubscribeRequestParamsSchema,SubscribeRequestSchema:()=>SubscribeRequestSchema,SubscriptionFilterSchema:()=>SubscriptionFilterSchema,SubscriptionsAcknowledgedNotificationParamsSchema:()=>SubscriptionsAcknowledgedNotificationParamsSchema,SubscriptionsAcknowledgedNotificationSchema:()=>SubscriptionsAcknowledgedNotificationSchema,SubscriptionsListenRequestParamsSchema:()=>SubscriptionsListenRequestParamsSchema,SubscriptionsListenRequestSchema:()=>SubscriptionsListenRequestSchema,SubscriptionsListenResultMetaSchema:()=>SubscriptionsListenResultMetaSchema,SubscriptionsListenResultSchema:()=>SubscriptionsListenResultSchema,TaskAugmentedRequestParamsSchema:()=>TaskAugmentedRequestParamsSchema,TaskCreationParamsSchema:()=>TaskCreationParamsSchema,TaskMetadataSchema:()=>TaskMetadataSchema,TaskSchema:()=>TaskSchema,TaskStatusNotificationParamsSchema:()=>TaskStatusNotificationParamsSchema,TaskStatusNotificationSchema:()=>TaskStatusNotificationSchema,TaskStatusSchema:()=>TaskStatusSchema,TextContentSchema:()=>TextContentSchema,TextResourceContentsSchema:()=>TextResourceContentsSchema,TitledMultiSelectEnumSchemaSchema:()=>TitledMultiSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema:()=>TitledSingleSelectEnumSchemaSchema,ToolAnnotationsSchema:()=>ToolAnnotationsSchema,ToolChoiceSchema:()=>ToolChoiceSchema,ToolExecutionSchema:()=>ToolExecutionSchema,ToolListChangedNotificationSchema:()=>ToolListChangedNotificationSchema,ToolResultContentSchema:()=>ToolResultContentSchema,ToolSchema:()=>ToolSchema,ToolUseContentSchema:()=>ToolUseContentSchema,UnsubscribeRequestParamsSchema:()=>UnsubscribeRequestParamsSchema,UnsubscribeRequestSchema:()=>UnsubscribeRequestSchema,UntitledMultiSelectEnumSchemaSchema:()=>UntitledMultiSelectEnumSchemaSchema,UntitledSingleSelectEnumSchemaSchema:()=>UntitledSingleSelectEnumSchemaSchema}),isJSONRPCRequest=value=>JSONRPCRequestSchema.safeParse(value).success,isJSONRPCNotification=value=>JSONRPCNotificationSchema.safeParse(value).success,isJSONRPCResultResponse=value=>typeof value=="object"&&value!==null&&Object.hasOwn(value,"result")&&JSONRPCResultResponseSchema.safeParse(value).success,isJSONRPCErrorResponse=value=>typeof value=="object"&&value!==null&&Object.hasOwn(value,"error")&&JSONRPCErrorResponseSchema.safeParse(value).success,isInputRequiredResult=value=>typeof value=="object"&&value!==null&&!Array.isArray(value)&&value.resultType==="input_required",isInitializeRequest=value=>InitializeRequestSchema.safeParse(value).success;MCP_PARAM_HEADER_PREFIX="Mcp-Param-",X_MCP_HEADER_KEY="x-mcp-header",RFC9110_TOKEN=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,PERMITTED_X_MCP_HEADER_TYPES=new Set(["string","integer","boolean","number"]);NON_REACHABLE_SUBSCHEMA_KEYWORDS=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],OBJECT_VALUED_SUBSCHEMA_KEYWORDS=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);BASE64_SENTINEL_PREFIX="=?base64?",BASE64_SENTINEL_SUFFIX="?=",BASE64_CANONICAL=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,CANONICAL_DECIMAL=/^-?\d+(\.\d+)?$/;HEADER_MISMATCH_ERROR_CODE=-32020,INBOUND_VALIDATION_LADDER=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[ProtocolErrorCode.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[HEADER_MISMATCH_ERROR_CODE,ProtocolErrorCode.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[ProtocolErrorCode.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[ProtocolErrorCode.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[ProtocolErrorCode.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[HEADER_MISMATCH_ERROR_CODE],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[ProtocolErrorCode.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[HEADER_MISMATCH_ERROR_CODE],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],LADDER_ERROR_HTTP_STATUS={[ProtocolErrorCode.ParseError]:400,[ProtocolErrorCode.InvalidRequest]:400,[ProtocolErrorCode.MethodNotFound]:404,[ProtocolErrorCode.UnsupportedProtocolVersion]:400,[ProtocolErrorCode.MissingRequiredClientCapability]:400,[HEADER_MISMATCH_ERROR_CODE]:400};MCP_NAME_HEADER_SOURCE={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};warnedZodFallback=!1,JSON_SCHEMA_CONVERSION_TARGET="draft-2020-12";DATETIME_FRACTION_DIGITS=/\\\.\\d\{(\d+)\}/;ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);ROOT_KEYS=new Set(["$schema",...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]),PROPERTY_KEYS_BY_TYPE={string:shapeKeys([StringSchemaSchema,UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema,LegacyTitledEnumSchemaSchema]),number:shapeKeys([NumberSchemaSchema]),integer:shapeKeys([NumberSchemaSchema]),boolean:shapeKeys([BooleanSchemaSchema]),array:shapeKeys([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema])},SUPPORTED_STRING_FORMATS=new Set(StringSchemaSchema.shape.format.unwrap().options);inputRequired=Object.assign(buildInputRequired,{elicit(params){try{return{method:"elicitation/create",params:normalizeElicitInputParams(params)}}catch(error3){throw error3 instanceof ProtocolError?new TypeError(error3.message,{cause:error3}):error3}},elicitUrl(params){return{method:"elicitation/create",params:{...params,mode:"url"}}},createMessage(params){return{method:"sampling/createMessage",params}},listRoots(){return{method:"roots/list"}}});REQUEST_STATE_ONLY_LEG_PACING_MS=250;SPEC_SCHEMA_KEYS=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],authSchemas={IdJagTokenExchangeResponseSchema,OAuthClientInformationFullSchema,OAuthClientInformationSchema,OAuthClientMetadataSchema,OAuthClientRegistrationErrorSchema,OAuthErrorResponseSchema,OAuthMetadataSchema,OAuthProtectedResourceMetadataSchema,OAuthTokenRevocationRequestSchema,OAuthTokensSchema,OpenIdProviderDiscoveryMetadataSchema,OpenIdProviderMetadataSchema},_specTypeSchemas={},_isSpecType={};for(let key of SPEC_SCHEMA_KEYS)register(key,schemas_exports2[key]);for(let[key,schema2]of Object.entries(authSchemas))register(key,schema2);specTypeSchemas=Object.freeze(_specTypeSchemas),isSpecType=Object.freeze(_isSpecType);DEFAULT_REQUEST_TIMEOUT_MSEC=6e4,RESERVED_ENVELOPE_META_KEYS=[PROTOCOL_VERSION_META_KEY,CLIENT_INFO_META_KEY,CLIENT_CAPABILITIES_META_KEY,LOG_LEVEL_META_KEY],RETRY_PARAMS_KEYS=["inputResponses","requestState"];NO_REQUEST_STATE=requestStateAccessor(void 0);Protocol=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{writeNegotiatedProtocolVersion=(instance,version2)=>{instance._negotiatedProtocolVersion=version2}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(_options){this._options=_options,this._supportedProtocolVersions=_options?.supportedProtocolVersions??SUPPORTED_PROTOCOL_VERSIONS,this.setNotificationHandler("notifications/cancelled",notification=>{this._oncancel(notification)}),this.setNotificationHandler("notifications/progress",notification=>{this._onprogress(notification)}),this.setRequestHandler("ping",_request=>({}))}_shouldDropInbound(_message){}_outboundMetaEnvelope(){}_envelopeOutbound(message){let envelope=this._outboundMetaEnvelope();if(envelope===void 0)return message;let params=message.params??{};return{...message,params:{...params,_meta:{...envelope,...params._meta}}}}_resolveNonCompleteResult(decoded,flow){return Promise.reject(new SdkError(SdkErrorCode.UnsupportedResultType,`Unsupported result type '${decoded.kind}' for ${flow.request.method}`,{resultType:decoded.kind,method:flow.request.method}))}_getRequestHandler(method){return this._requestHandlers.get(method)}async _oncancel(notification){notification.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),new SdkError(SdkErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);info&&(clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId))}async connect(transport){this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{try{_onclose?.()}finally{this._onclose()}};let _onerror=this.transport?.onerror;this._transport.onerror=error3=>{_onerror?.(error3),this._onerror(error3)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?this._onresponse(message):isJSONRPCRequest(message)?this._onrequest(message,extra):isJSONRPCNotification(message)?this._onnotification(message,extra):this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))},transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let info of this._timeoutInfo.values())clearTimeout(info.timeoutId);this._timeoutInfo.clear();let requestHandlerAbortControllers=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let error3=new SdkError(SdkErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let handler of responseHandlers.values())handler(error3);for(let controller of requestHandlerAbortControllers.values())controller.abort(error3)}}_onerror(error3){this.onerror?.(error3)}_onnotification(rawNotification,extra){let{message:notification}=liftWireOnlyMaterial(rawNotification,"notification"),codec=this._negotiatedWireCodec();if(extra?.classification===void 0&&this._shouldDropInbound(rawNotification)==="drop")return;if(extra?.classification!==void 0){let classified=classifiedWireEra(extra.classification);if(classified!==codec.era){this._onerror(new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`));return}}if(isSpecNotificationMethod(notification.method)&&!codec.hasNotificationMethod(notification.method))return;let handler=this._notificationHandlers.get(notification.method),fallback=this.fallbackNotificationHandler;handler===void 0&&fallback===void 0||Promise.resolve().then(()=>handler===void 0?fallback(notification):handler(notification,codec)).catch(error3=>this._onerror(new Error(`Uncaught error in notification handler: ${error3}`)))}_onrequest(rawRequest,extra){let{message:request,lifted}=liftWireOnlyMaterial(rawRequest,"request"),codec=this._negotiatedWireCodec();if(extra?.classification===void 0&&this._shouldDropInbound(rawRequest)==="drop"){this._onerror(new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`));return}let capturedTransport=this._transport,sendErrorResponse=(code,message,data)=>{let errorResponse={jsonrpc:"2.0",id:request.id,error:{code,message,...data!==void 0&&{data}}};capturedTransport?.send(errorResponse).catch(error3=>this._onerror(new Error(`Failed to send an error response: ${error3}`)))};if(extra?.classification!==void 0){let classified=classifiedWireEra(extra.classification);if(classified!==codec.era){this._onerror(new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`));let requested=extra.classification.revision??classified;sendErrorResponse(ProtocolErrorCode.UnsupportedProtocolVersion,`Unsupported protocol version: ${requested}`,{supported:this._supportedProtocolVersions,requested});return}}if(isSpecRequestMethod(request.method)&&!codec.hasRequestMethod(request.method)&&!(isExtensionReusedRequestMethod(request.method)&&this._customSchemaRequestMethods.has(request.method))){sendErrorResponse(ProtocolErrorCode.MethodNotFound,"Method not found");return}let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler;if(handler===void 0){sendErrorResponse(ProtocolErrorCode.MethodNotFound,"Method not found");return}let envelopeError=codec.checkInboundEnvelope(lifted);if(envelopeError!==void 0){sendErrorResponse(ProtocolErrorCode.InvalidParams,envelopeError);return}let sendNotification=(notification,options)=>this._notificationViaCodec(this._resolveOutboundCodec(notification.method),notification,{...options,relatedRequestId:request.id}),sendRequest=(r,resultSchema,options)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method),r,resultSchema,{...options,relatedRequestId:request.id}),abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let partitionedInputResponses=lifted.inputResponses===void 0?void 0:partitionInputResponses(lifted.inputResponses),baseCtx={sessionId:capturedTransport?.sessionId,mcpReq:{id:request.id,method:request.method,_meta:request.params?._meta,...lifted.envelope!==void 0&&{envelope:lifted.envelope},...partitionedInputResponses!==void 0&&{inputResponses:partitionedInputResponses.accepted},...partitionedInputResponses!==void 0&&partitionedInputResponses.droppedKeys.length>0&&{droppedInputResponseKeys:partitionedInputResponses.droppedKeys},requestState:lifted.requestState===void 0?NO_REQUEST_STATE:requestStateAccessor(lifted.requestState),signal:abortController.signal,send:((r,schemaOrOptions,maybeOptions)=>{let sendCodec=this._resolveOutboundCodec(r.method);if(this._assertOutboundRequestInEra(sendCodec,r.method),isStandardSchema(schemaOrOptions))return sendRequest(r,schemaOrOptions,maybeOptions);let validate=codecResultValidator(sendCodec,r.method);if(validate===void 0)throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return sendRequest(r,validate,schemaOrOptions)}),notify:sendNotification},http:extra?.authInfo?{authInfo:extra.authInfo}:void 0},ctx=this.buildContext(baseCtx,extra);Promise.resolve().then(()=>handler(request,ctx)).then(async result=>{if(abortController.signal.aborted)return;let encoded;try{encoded=codec.encodeResult(request.method,result,this._outboundServerInfo())}catch(error3){this._onerror(new Error(`Failed to encode result for ${request.method}: ${error3}`)),sendErrorResponse(ProtocolErrorCode.InternalError,"Internal error");return}let response={result:encoded,jsonrpc:"2.0",id:request.id};await capturedTransport?.send(response)},async error3=>{if(abortController.signal.aborted)return;let thrownCode=Number.isSafeInteger(error3.code)?error3.code:ProtocolErrorCode.InternalError,errorResponse={jsonrpc:"2.0",id:request.id,error:{code:codec.encodeErrorCode(thrownCode),message:error3.message??"Internal error",...error3.data!==void 0&&{data:error3.data}}};await capturedTransport?.send(errorResponse)}).catch(error3=>this._onerror(new Error(`Failed to send response: ${error3}`))).finally(()=>{this._requestHandlerAbortControllers.get(request.id)===abortController&&this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error3){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error3);return}handler(params)}_onresponse(response){let messageId=Number(response.id),handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId),this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response)?handler(response):handler(ProtocolError.fromError(response.error.code,response.error.message,response.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(request,schemaOrOptions,maybeOptions){let codec=this._resolveOutboundCodec(request.method);if(isStandardSchema(schemaOrOptions))return isExtensionReusedRequestMethod(request.method)||this._assertOutboundRequestInEra(codec,request.method),this._requestWithSchemaViaCodec(codec,request,schemaOrOptions,maybeOptions);this._assertOutboundRequestInEra(codec,request.method);let validate=codecResultValidator(codec,request.method);if(validate===void 0)throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(codec,request,validate,schemaOrOptions)}_negotiatedWireCodec(){return codecForVersion(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(method){if(this._negotiatedProtocolVersion===void 0){let pinned=bootstrapOutboundCodec(method);if(pinned)return pinned}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(codec,method){if(isSpecRequestMethod(method)&&!codec.hasRequestMethod(method))throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,{method,era:codec.era})}_requestWithSchema(request,resultSchema,options){let codec=this._resolveOutboundCodec(request.method);return this._assertOutboundRequestInEra(codec,request.method),this._requestWithSchemaViaCodec(codec,request,resultSchema,options)}_requestWithSchemaViaCodec(codec,request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,headers}=options??{},flowStartedAt=Date.now(),onAbort,cleanupMessageId;return new Promise((resolve,reject)=>{let earlyReject=error3=>{reject(error3)};if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method)}catch(error3){earlyReject(error3);return}if(options?.signal?.aborted){let reason=options.signal.reason;throw reason instanceof SdkError?reason:new SdkError(SdkErrorCode.RequestTimeout,String(reason))}let requestAbort=codec.era===MODERN_WIRE_REVISION&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,messageId=this._requestMessageId++;cleanupMessageId=messageId;let jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};options?.onprogress&&(this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta,progressToken:messageId}});let outbound=this._envelopeOutbound(jsonrpcRequest),responseReceived=!1,cancel=reason=>{responseReceived||(this._progressHandlers.delete(messageId),requestAbort===void 0?request.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}}),{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error3=>this._onerror(new Error(`Failed to send cancellation: ${error3}`))):requestAbort.abort(),reject(reason instanceof SdkError?reason:new SdkError(SdkErrorCode.RequestTimeout,String(reason))))};this._responseHandlers.set(messageId,response=>{if(options?.signal?.aborted)return;if(responseReceived=!0,response instanceof Error)return reject(response);let decoded;try{decoded=codec.decodeResult(request.method,response.result)}catch(error3){return reject(error3 instanceof Error?error3:new Error(String(error3)))}if(decoded.kind==="invalid")return reject(decoded.error);if(decoded.kind==="input_required"){if(options?.allowInputRequired===!0)return resolve(manualInputRequiredValue(decoded));let flow={codec,request,resultSchema,options,flowStartedAt,retry:(params,legOptions)=>this._requestWithSchemaViaCodec(codec,params===void 0?{method:request.method}:{method:request.method,params},resultSchema,legOptions)};return resolve(this._resolveNonCompleteResult(decoded,flow))}let result=decoded.result;validateStandardSchema(resultSchema,result).then(parseResult=>{parseResult.success?resolve(parseResult.data):reject(new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${request.method}: ${parseResult.error}`))},reject)}),onAbort=()=>cancel(options?.signal?.reason),options?.signal?.addEventListener("abort",onAbort,{once:!0});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=()=>cancel(new SdkError(SdkErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1),this._transport.send(outbound,{relatedRequestId,resumptionToken,onresumptiontoken,headers,requestSignal:requestAbort?.signal}).catch(error3=>{this._progressHandlers.delete(messageId),reject(error3)})}).finally(()=>{onAbort&&options?.signal?.removeEventListener("abort",onAbort),cleanupMessageId!==void 0&&(this._responseHandlers.delete(cleanupMessageId),this._cleanupTimeout(cleanupMessageId))})}async notification(notification,options){return await this._notificationViaCodec(this._resolveOutboundCodec(notification.method),notification,options)}async _notificationViaCodec(codec,notification,options){if(!this._transport)throw new SdkError(SdkErrorCode.NotConnected,"Not connected");if(isSpecNotificationMethod(notification.method)&&!codec.hasNotificationMethod(notification.method))throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,{method:notification.method,era:codec.era});this.assertNotificationCapability(notification.method);let jsonrpcNotification=this._envelopeOutbound({jsonrpc:"2.0",...notification});if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&options?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(notification.method),this._transport&&this._transport?.send(jsonrpcNotification,options).catch(error3=>this._onerror(error3))});return}await this._transport.send(jsonrpcNotification,options)}setRequestHandler(method,schemasOrHandler,maybeHandler){this.assertRequestHandlerCapability(method);let stored;if(typeof schemasOrHandler=="function"){if(!isSpecRequestMethod(method))throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);stored=(request,ctx)=>{let dispatchCodec=this._negotiatedWireCodec(),outcome=dispatchCodec.validateRequest(method,request);if(!outcome.ok&&outcome.reason==="not-in-era"&&(outcome=dispatchCodec.validateInputRequest(method,request)),!outcome.ok)throw outcome.reason==="not-in-era"?new ProtocolError(ProtocolErrorCode.InternalError,`No wire schema for ${method} in the resolved era`):new Error(outcome.message);return Promise.resolve(schemasOrHandler(outcome.value,ctx))}}else if(maybeHandler)stored=async(request,ctx)=>{let parsed=await validateStandardSchema(schemasOrHandler.params,{...request.params});if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params for ${method}: ${parsed.error}`);return maybeHandler(parsed.data,ctx)};else throw new TypeError("setRequestHandler: handler is required");typeof schemasOrHandler=="function"?this._customSchemaRequestMethods.delete(method):this._customSchemaRequestMethods.add(method),this._requestHandlers.set(method,this._wrapHandler(method,stored))}_wrapHandler(_method,handler){return handler}_outboundServerInfo(){}removeRequestHandler(method){this._requestHandlers.delete(method),this._customSchemaRequestMethods.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw new Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(method,schemasOrHandler,maybeHandler){if(typeof schemasOrHandler=="function"){if(!isSpecNotificationMethod(method))throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(method,(notification,codec)=>{let outcome=codec.validateNotification(method,notification);if(!outcome.ok)throw outcome.reason==="not-in-era"?new ProtocolError(ProtocolErrorCode.InternalError,`No wire schema for ${method} in the resolved era`):new Error(outcome.message);return Promise.resolve(schemasOrHandler(outcome.value))});return}if(!maybeHandler)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(method,async notification=>{let parsed=await validateStandardSchema(schemasOrHandler.params,{...notification.params});if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params for notification ${method}: ${parsed.error}`);await maybeHandler(parsed.data,notification)})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}};require_content_type=__commonJSMin((exports=>{var PARAM_REGEXP=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,QESC_REGEXP=/\\([\u000b\u0020-\u00ff])/g,TYPE_REGEXP=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;exports.parse=parse4;function parse4(string4){if(!string4)throw new TypeError("argument string is required");var header=typeof string4=="object"?getcontenttype(string4):string4;if(typeof header!="string")throw new TypeError("argument string is required to be a string");var index=header.indexOf(";"),type=index!==-1?header.slice(0,index).trim():header.trim();if(!TYPE_REGEXP.test(type))throw new TypeError("invalid media type");var obj=new ContentType(type.toLowerCase());if(index!==-1){var key,match2,value;for(PARAM_REGEXP.lastIndex=index;match2=PARAM_REGEXP.exec(header);){if(match2.index!==index)throw new TypeError("invalid parameter format");index+=match2[0].length,key=match2[1].toLowerCase(),value=match2[2],value.charCodeAt(0)===34&&(value=value.slice(1,-1),value.indexOf("\\")!==-1&&(value=value.replace(QESC_REGEXP,"$1"))),obj.parameters[key]=value}if(index!==header.length)throw new TypeError("invalid parameter format")}return obj}function getcontenttype(obj){var header;if(typeof obj.getHeader=="function"?header=obj.getHeader("content-type"):typeof obj.headers=="object"&&(header=obj.headers&&obj.headers["content-type"]),typeof header!="string")throw new TypeError("content-type header is missing from object");return header}function ContentType(type){this.parameters=Object.create(null),this.type=type}})),import_content_type=__toESM(require_content_type(),1);STDIO_DEFAULT_MAX_BUFFER_SIZE=10*1024*1024,TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;MAX_TEMPLATE_LENGTH=1e6,MAX_VARIABLE_LENGTH=1e6,MAX_TEMPLATE_EXPRESSIONS=1e4,MAX_REGEX_LENGTH=1e6,UriTemplate=class UriTemplate2{static isTemplate(str){return/\{[^}\s]+\}/.test(str)}static validateLength(str,max,context){if(str.length>max)throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`)}template;parts;get variableNames(){return this.parts.flatMap(part=>typeof part=="string"?[]:part.names)}constructor(template){UriTemplate2.validateLength(template,MAX_TEMPLATE_LENGTH,"Template"),this.template=template,this.parts=this.parse(template)}toString(){return this.template}parse(template){let parts=[],currentText="",i=0,expressionCount=0;for(;i<template.length;)if(template[i]==="{"){currentText&&(parts.push(currentText),currentText="");let end=template.indexOf("}",i);if(end===-1)throw new Error("Unclosed template expression");if(expressionCount++,expressionCount>MAX_TEMPLATE_EXPRESSIONS)throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);let expr=template.slice(i+1,end),operator=this.getOperator(expr),exploded=expr.includes("*"),names=this.getNames(expr),name=names[0];for(let name$1 of names)UriTemplate2.validateLength(name$1,MAX_VARIABLE_LENGTH,"Variable name");parts.push({name,operator,names,exploded}),i=end+1}else currentText+=template[i],i++;return currentText&&parts.push(currentText),parts}getOperator(expr){return["+","#",".","/","?","&"].find(op=>expr.startsWith(op))||""}getNames(expr){let operator=this.getOperator(expr);return expr.slice(operator.length).split(",").map(name=>name.replace("*","").trim()).filter(name=>name.length>0)}encodeValue(value,operator){return UriTemplate2.validateLength(value,MAX_VARIABLE_LENGTH,"Variable value"),operator==="+"||operator==="#"?encodeURI(value):encodeURIComponent(value)}expandPart(part,variables){if(part.operator==="?"||part.operator==="&"){let pairs=part.names.map(name=>{let value$1=variables[name];return value$1===void 0?"":`${name}=${Array.isArray(value$1)?value$1.map(v=>this.encodeValue(v,part.operator)).join(","):this.encodeValue(value$1.toString(),part.operator)}`}).filter(pair=>pair.length>0);return pairs.length===0?"":(part.operator==="?"?"?":"&")+pairs.join("&")}if(part.names.length>1){let values=part.names.map(name=>variables[name]).filter(v=>v!==void 0);return values.length===0?"":values.map(v=>Array.isArray(v)?v[0]:v).join(",")}let value=variables[part.name];if(value===void 0)return"";let encoded=(Array.isArray(value)?value:[value]).map(v=>this.encodeValue(v,part.operator));switch(part.operator){case"":return encoded.join(",");case"+":return encoded.join(",");case"#":return"#"+encoded.join(",");case".":return"."+encoded.join(".");case"/":return"/"+encoded.join("/");default:return encoded.join(",")}}expand(variables){let result="",hasQueryParam=!1;for(let part of this.parts){if(typeof part=="string"){result+=part;continue}let expanded=this.expandPart(part,variables);expanded&&(result+=(part.operator==="?"||part.operator==="&")&&hasQueryParam?expanded.replace("?","&"):expanded,(part.operator==="?"||part.operator==="&")&&(hasQueryParam=!0))}return result}escapeRegExp(str){return str.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(part){let patterns=[];for(let name$1 of part.names)UriTemplate2.validateLength(name$1,MAX_VARIABLE_LENGTH,"Variable name");if(part.operator==="?"||part.operator==="&"){for(let i=0;i<part.names.length;i++){let name$1=part.names[i],prefix=i===0?"\\"+part.operator:"&";patterns.push({pattern:prefix+this.escapeRegExp(name$1)+"=([^&]+)",name:name$1})}return patterns}let pattern,name=part.name;switch(part.operator){case"":pattern=part.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":pattern="(.+)";break;case".":pattern=String.raw`\.([^/,]+)`;break;case"/":pattern="/"+(part.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:pattern="([^/]+)"}return patterns.push({pattern,name}),patterns}match(uri){UriTemplate2.validateLength(uri,MAX_TEMPLATE_LENGTH,"URI");let pattern="^",names=[];for(let part of this.parts)if(typeof part=="string")pattern+=this.escapeRegExp(part);else{let patterns=this.partToRegExp(part);for(let{pattern:partPattern,name}of patterns)pattern+=partPattern,names.push({name,exploded:part.exploded})}pattern+="$",UriTemplate2.validateLength(pattern,MAX_REGEX_LENGTH,"Generated regex pattern");let regex=new RegExp(pattern),match2=uri.match(regex);if(!match2)return null;let result={};for(let[i,name_]of names.entries()){let{name,exploded}=name_,value=match2[i+1],cleanName=name.replace("*","");result[cleanName]=exploded&&value.includes(",")?value.split(","):value}return result}}}});function createDefaultAjvInstance(engineClass){let ajv=new engineClass({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return addFormats(ajv),ajv}var require_code$1,require_scope,require_codegen,require_util,require_names,require_errors,require_boolSchema,require_rules,require_applicability,require_dataType,require_defaults,require_code,require_keyword,require_subschema,require_fast_deep_equal,require_json_schema_traverse,require_resolve,require_validate,require_validation_error,require_ref_error,require_compile,require_data,require_utils,require_schemes,require_fast_uri,require_uri,require_core$3,require_id,require_ref,require_core$2,require_limitNumber,require_multipleOf,require_ucs2length,require_limitLength,require_pattern,require_limitProperties,require_required,require_limitItems,require_equal,require_uniqueItems,require_const,require_enum,require_validation$2,require_additionalItems,require_items,require_prefixItems,require_items2020,require_contains,require_dependencies,require_propertyNames,require_additionalProperties,require_properties,require_patternProperties,require_not,require_anyOf,require_oneOf,require_allOf,require_if,require_thenElse,require_applicator$2,require_format$2,require_format$1,require_metadata,require_draft7,require_types,require_discriminator,require_json_schema_draft_07,require_ajv,require_dynamicAnchor,require_dynamicRef,require_recursiveAnchor,require_recursiveRef,require_dynamic,require_dependentRequired,require_dependentSchemas,require_limitContains,require_next,require_unevaluatedProperties,require_unevaluatedItems,require_unevaluated$1,require_schema$1,require_applicator$1,require_content$1,require_core$1,require_format,require_meta_data$1,require_validation$1,require_json_schema_2019_09,require__2019,require_draft2020,require_schema,require_applicator,require_unevaluated,require_content,require_core,require_format_annotation,require_meta_data,require_validation,require_json_schema_2020_12,require__2020,require_formats,require_limit,require_dist,import_ajv,import__2019,import__2020,import_dist,addFormats,AjvJsonSchemaValidator,Ajv,init_ajvProvider_CEoC_sr=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs"(){"use strict";init_chunk_Br0eD_fh();init_dialects_DoSzNhcb();require_code$1=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.regexpCode=exports.getEsmExportName=exports.getProperty=exports.safeStringify=exports.stringify=exports.strConcat=exports.addCodeArg=exports.str=exports._=exports.nil=exports._Code=exports.Name=exports.IDENTIFIER=exports._CodeOrName=void 0;var _CodeOrName=class{};exports._CodeOrName=_CodeOrName,exports.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Name=class extends _CodeOrName{constructor(s){if(super(),!exports.IDENTIFIER.test(s))throw new Error("CodeGen: name must be a valid identifier");this.str=s}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};exports.Name=Name;var _Code=class extends _CodeOrName{constructor(code){super(),this._items=typeof code=="string"?[code]:code}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let item=this._items[0];return item===""||item==='""'}get str(){var _a3;return(_a3=this._str)!==null&&_a3!==void 0?_a3:this._str=this._items.reduce((s,c)=>`${s}${c}`,"")}get names(){var _a3;return(_a3=this._names)!==null&&_a3!==void 0?_a3:this._names=this._items.reduce((names,c)=>(c instanceof Name&&(names[c.str]=(names[c.str]||0)+1),names),{})}};exports._Code=_Code,exports.nil=new _Code("");function _(strs,...args){let code=[strs[0]],i=0;for(;i<args.length;)addCodeArg(code,args[i]),code.push(strs[++i]);return new _Code(code)}exports._=_;let plus=new _Code("+");function str(strs,...args){let expr=[safeStringify(strs[0])],i=0;for(;i<args.length;)expr.push(plus),addCodeArg(expr,args[i]),expr.push(plus,safeStringify(strs[++i]));return optimize(expr),new _Code(expr)}exports.str=str;function addCodeArg(code,arg){arg instanceof _Code?code.push(...arg._items):arg instanceof Name?code.push(arg):code.push(interpolate(arg))}exports.addCodeArg=addCodeArg;function optimize(expr){let i=1;for(;i<expr.length-1;){if(expr[i]===plus){let res=mergeExprItems(expr[i-1],expr[i+1]);if(res!==void 0){expr.splice(i-1,3,res);continue}expr[i++]="+"}i++}}function mergeExprItems(a,b){if(b==='""')return a;if(a==='""')return b;if(typeof a=="string")return b instanceof Name||a[a.length-1]!=='"'?void 0:typeof b!="string"?`${a.slice(0,-1)}${b}"`:b[0]==='"'?a.slice(0,-1)+b.slice(1):void 0;if(typeof b=="string"&&b[0]==='"'&&!(a instanceof Name))return`"${a}${b.slice(1)}`}function strConcat(c1,c2){return c2.emptyStr()?c1:c1.emptyStr()?c2:str`${c1}${c2}`}exports.strConcat=strConcat;function interpolate(x){return typeof x=="number"||typeof x=="boolean"||x===null?x:safeStringify(Array.isArray(x)?x.join(","):x)}function stringify(x){return new _Code(safeStringify(x))}exports.stringify=stringify;function safeStringify(x){return JSON.stringify(x).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}exports.safeStringify=safeStringify;function getProperty(key){return typeof key=="string"&&exports.IDENTIFIER.test(key)?new _Code(`.${key}`):_`[${key}]`}exports.getProperty=getProperty;function getEsmExportName(key){if(typeof key=="string"&&exports.IDENTIFIER.test(key))return new _Code(`${key}`);throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)}exports.getEsmExportName=getEsmExportName;function regexpCode(rx){return new _Code(rx.toString())}exports.regexpCode=regexpCode})),require_scope=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.ValueScope=exports.ValueScopeName=exports.Scope=exports.varKinds=exports.UsedValueState=void 0;let code_1=require_code$1();var ValueError=class extends Error{constructor(name){super(`CodeGen: "code" for ${name} not defined`),this.value=name.value}},UsedValueState;(function(UsedValueState2){UsedValueState2[UsedValueState2.Started=0]="Started",UsedValueState2[UsedValueState2.Completed=1]="Completed"})(UsedValueState||(exports.UsedValueState=UsedValueState={})),exports.varKinds={const:new code_1.Name("const"),let:new code_1.Name("let"),var:new code_1.Name("var")};var Scope=class{constructor({prefixes,parent}={}){this._names={},this._prefixes=prefixes,this._parent=parent}toName(nameOrPrefix){return nameOrPrefix instanceof code_1.Name?nameOrPrefix:this.name(nameOrPrefix)}name(prefix){return new code_1.Name(this._newName(prefix))}_newName(prefix){let ng=this._names[prefix]||this._nameGroup(prefix);return`${prefix}${ng.index++}`}_nameGroup(prefix){var _a3,_b;if(!((_b=(_a3=this._parent)===null||_a3===void 0?void 0:_a3._prefixes)===null||_b===void 0)&&_b.has(prefix)||this._prefixes&&!this._prefixes.has(prefix))throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);return this._names[prefix]={prefix,index:0}}};exports.Scope=Scope;var ValueScopeName=class extends code_1.Name{constructor(prefix,nameStr){super(nameStr),this.prefix=prefix}setValue(value,{property,itemIndex}){this.value=value,this.scopePath=(0,code_1._)`.${new code_1.Name(property)}[${itemIndex}]`}};exports.ValueScopeName=ValueScopeName;let line=(0,code_1._)`\n`;var ValueScope=class extends Scope{constructor(opts){super(opts),this._values={},this._scope=opts.scope,this.opts={...opts,_n:opts.lines?line:code_1.nil}}get(){return this._scope}name(prefix){return new ValueScopeName(prefix,this._newName(prefix))}value(nameOrPrefix,value){var _a3;if(value.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let name=this.toName(nameOrPrefix),{prefix}=name,valueKey=(_a3=value.key)!==null&&_a3!==void 0?_a3:value.ref,vs=this._values[prefix];if(vs){let _name=vs.get(valueKey);if(_name)return _name}else vs=this._values[prefix]=new Map;vs.set(valueKey,name);let s=this._scope[prefix]||(this._scope[prefix]=[]),itemIndex=s.length;return s[itemIndex]=value.ref,name.setValue(value,{property:prefix,itemIndex}),name}getValue(prefix,keyOrRef){let vs=this._values[prefix];if(vs)return vs.get(keyOrRef)}scopeRefs(scopeName,values=this._values){return this._reduceValues(values,name=>{if(name.scopePath===void 0)throw new Error(`CodeGen: name "${name}" has no value`);return(0,code_1._)`${scopeName}${name.scopePath}`})}scopeCode(values=this._values,usedValues,getCode){return this._reduceValues(values,name=>{if(name.value===void 0)throw new Error(`CodeGen: name "${name}" has no value`);return name.value.code},usedValues,getCode)}_reduceValues(values,valueCode,usedValues={},getCode){let code=code_1.nil;for(let prefix in values){let vs=values[prefix];if(!vs)continue;let nameSet=usedValues[prefix]=usedValues[prefix]||new Map;vs.forEach(name=>{if(nameSet.has(name))return;nameSet.set(name,UsedValueState.Started);let c=valueCode(name);if(c){let def=this.opts.es5?exports.varKinds.var:exports.varKinds.const;code=(0,code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`}else if(c=getCode?.(name))code=(0,code_1._)`${code}${c}${this.opts._n}`;else throw new ValueError(name);nameSet.set(name,UsedValueState.Completed)})}return code}};exports.ValueScope=ValueScope})),require_codegen=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.or=exports.and=exports.not=exports.CodeGen=exports.operators=exports.varKinds=exports.ValueScopeName=exports.ValueScope=exports.Scope=exports.Name=exports.regexpCode=exports.stringify=exports.getProperty=exports.nil=exports.strConcat=exports.str=exports._=void 0;let code_1=require_code$1(),scope_1=require_scope();var code_2=require_code$1();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return code_2._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return code_2.str}}),Object.defineProperty(exports,"strConcat",{enumerable:!0,get:function(){return code_2.strConcat}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return code_2.nil}}),Object.defineProperty(exports,"getProperty",{enumerable:!0,get:function(){return code_2.getProperty}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return code_2.stringify}}),Object.defineProperty(exports,"regexpCode",{enumerable:!0,get:function(){return code_2.regexpCode}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return code_2.Name}});var scope_2=require_scope();Object.defineProperty(exports,"Scope",{enumerable:!0,get:function(){return scope_2.Scope}}),Object.defineProperty(exports,"ValueScope",{enumerable:!0,get:function(){return scope_2.ValueScope}}),Object.defineProperty(exports,"ValueScopeName",{enumerable:!0,get:function(){return scope_2.ValueScopeName}}),Object.defineProperty(exports,"varKinds",{enumerable:!0,get:function(){return scope_2.varKinds}}),exports.operators={GT:new code_1._Code(">"),GTE:new code_1._Code(">="),LT:new code_1._Code("<"),LTE:new code_1._Code("<="),EQ:new code_1._Code("==="),NEQ:new code_1._Code("!=="),NOT:new code_1._Code("!"),OR:new code_1._Code("||"),AND:new code_1._Code("&&"),ADD:new code_1._Code("+")};var Node5=class{optimizeNodes(){return this}optimizeNames(_names,_constants){return this}},Def=class extends Node5{constructor(varKind,name,rhs){super(),this.varKind=varKind,this.name=name,this.rhs=rhs}render({es5,_n}){let varKind=es5?scope_1.varKinds.var:this.varKind,rhs=this.rhs===void 0?"":` = ${this.rhs}`;return`${varKind} ${this.name}${rhs};`+_n}optimizeNames(names,constants){if(names[this.name.str])return this.rhs&&(this.rhs=optimizeExpr(this.rhs,names,constants)),this}get names(){return this.rhs instanceof code_1._CodeOrName?this.rhs.names:{}}},Assign=class extends Node5{constructor(lhs,rhs,sideEffects){super(),this.lhs=lhs,this.rhs=rhs,this.sideEffects=sideEffects}render({_n}){return`${this.lhs} = ${this.rhs};`+_n}optimizeNames(names,constants){if(!(this.lhs instanceof code_1.Name&&!names[this.lhs.str]&&!this.sideEffects))return this.rhs=optimizeExpr(this.rhs,names,constants),this}get names(){return addExprNames(this.lhs instanceof code_1.Name?{}:{...this.lhs.names},this.rhs)}},AssignOp=class extends Assign{constructor(lhs,op,rhs,sideEffects){super(lhs,rhs,sideEffects),this.op=op}render({_n}){return`${this.lhs} ${this.op}= ${this.rhs};`+_n}},Label=class extends Node5{constructor(label){super(),this.label=label,this.names={}}render({_n}){return`${this.label}:`+_n}},Break=class extends Node5{constructor(label){super(),this.label=label,this.names={}}render({_n}){return`break${this.label?` ${this.label}`:""};`+_n}},Throw=class extends Node5{constructor(error3){super(),this.error=error3}render({_n}){return`throw ${this.error};`+_n}get names(){return this.error.names}},AnyCode=class extends Node5{constructor(code){super(),this.code=code}render({_n}){return`${this.code};`+_n}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(names,constants){return this.code=optimizeExpr(this.code,names,constants),this}get names(){return this.code instanceof code_1._CodeOrName?this.code.names:{}}},ParentNode=class extends Node5{constructor(nodes=[]){super(),this.nodes=nodes}render(opts){return this.nodes.reduce((code,n)=>code+n.render(opts),"")}optimizeNodes(){let{nodes}=this,i=nodes.length;for(;i--;){let n=nodes[i].optimizeNodes();Array.isArray(n)?nodes.splice(i,1,...n):n?nodes[i]=n:nodes.splice(i,1)}return nodes.length>0?this:void 0}optimizeNames(names,constants){let{nodes}=this,i=nodes.length;for(;i--;){let n=nodes[i];n.optimizeNames(names,constants)||(subtractNames(names,n.names),nodes.splice(i,1))}return nodes.length>0?this:void 0}get names(){return this.nodes.reduce((names,n)=>addNames(names,n.names),{})}},BlockNode=class extends ParentNode{render(opts){return"{"+opts._n+super.render(opts)+"}"+opts._n}},Root=class extends ParentNode{},Else=class extends BlockNode{};Else.kind="else";var If=class If2 extends BlockNode{constructor(condition,nodes){super(nodes),this.condition=condition}render(opts){let code=`if(${this.condition})`+super.render(opts);return this.else&&(code+="else "+this.else.render(opts)),code}optimizeNodes(){super.optimizeNodes();let cond=this.condition;if(cond===!0)return this.nodes;let e=this.else;if(e){let ns=e.optimizeNodes();e=this.else=Array.isArray(ns)?new Else(ns):ns}if(e)return cond===!1?e instanceof If2?e:e.nodes:this.nodes.length?this:new If2(not(cond),e instanceof If2?[e]:e.nodes);if(!(cond===!1||!this.nodes.length))return this}optimizeNames(names,constants){var _a3;if(this.else=(_a3=this.else)===null||_a3===void 0?void 0:_a3.optimizeNames(names,constants),!!(super.optimizeNames(names,constants)||this.else))return this.condition=optimizeExpr(this.condition,names,constants),this}get names(){let names=super.names;return addExprNames(names,this.condition),this.else&&addNames(names,this.else.names),names}};If.kind="if";var For=class extends BlockNode{};For.kind="for";var ForLoop=class extends For{constructor(iteration){super(),this.iteration=iteration}render(opts){return`for(${this.iteration})`+super.render(opts)}optimizeNames(names,constants){if(super.optimizeNames(names,constants))return this.iteration=optimizeExpr(this.iteration,names,constants),this}get names(){return addNames(super.names,this.iteration.names)}},ForRange=class extends For{constructor(varKind,name,from,to){super(),this.varKind=varKind,this.name=name,this.from=from,this.to=to}render(opts){let varKind=opts.es5?scope_1.varKinds.var:this.varKind,{name,from,to}=this;return`for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)`+super.render(opts)}get names(){return addExprNames(addExprNames(super.names,this.from),this.to)}},ForIter=class extends For{constructor(loop,varKind,name,iterable){super(),this.loop=loop,this.varKind=varKind,this.name=name,this.iterable=iterable}render(opts){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(opts)}optimizeNames(names,constants){if(super.optimizeNames(names,constants))return this.iterable=optimizeExpr(this.iterable,names,constants),this}get names(){return addNames(super.names,this.iterable.names)}},Func=class extends BlockNode{constructor(name,args,async){super(),this.name=name,this.args=args,this.async=async}render(opts){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(opts)}};Func.kind="func";var Return=class extends ParentNode{render(opts){return"return "+super.render(opts)}};Return.kind="return";var Try=class extends BlockNode{render(opts){let code="try"+super.render(opts);return this.catch&&(code+=this.catch.render(opts)),this.finally&&(code+=this.finally.render(opts)),code}optimizeNodes(){var _a3,_b;return super.optimizeNodes(),(_a3=this.catch)===null||_a3===void 0||_a3.optimizeNodes(),(_b=this.finally)===null||_b===void 0||_b.optimizeNodes(),this}optimizeNames(names,constants){var _a3,_b;return super.optimizeNames(names,constants),(_a3=this.catch)===null||_a3===void 0||_a3.optimizeNames(names,constants),(_b=this.finally)===null||_b===void 0||_b.optimizeNames(names,constants),this}get names(){let names=super.names;return this.catch&&addNames(names,this.catch.names),this.finally&&addNames(names,this.finally.names),names}},Catch=class extends BlockNode{constructor(error3){super(),this.error=error3}render(opts){return`catch(${this.error})`+super.render(opts)}};Catch.kind="catch";var Finally=class extends BlockNode{render(opts){return"finally"+super.render(opts)}};Finally.kind="finally";var CodeGen=class{constructor(extScope,opts={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...opts,_n:opts.lines?`
65
- `:""},this._extScope=extScope,this._scope=new scope_1.Scope({parent:extScope}),this._nodes=[new Root]}toString(){return this._root.render(this.opts)}name(prefix){return this._scope.name(prefix)}scopeName(prefix){return this._extScope.name(prefix)}scopeValue(prefixOrName,value){let name=this._extScope.value(prefixOrName,value);return(this._values[name.prefix]||(this._values[name.prefix]=new Set)).add(name),name}getScopeValue(prefix,keyOrRef){return this._extScope.getValue(prefix,keyOrRef)}scopeRefs(scopeName){return this._extScope.scopeRefs(scopeName,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(varKind,nameOrPrefix,rhs,constant){let name=this._scope.toName(nameOrPrefix);return rhs!==void 0&&constant&&(this._constants[name.str]=rhs),this._leafNode(new Def(varKind,name,rhs)),name}const(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.const,nameOrPrefix,rhs,_constant)}let(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.let,nameOrPrefix,rhs,_constant)}var(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.var,nameOrPrefix,rhs,_constant)}assign(lhs,rhs,sideEffects){return this._leafNode(new Assign(lhs,rhs,sideEffects))}add(lhs,rhs){return this._leafNode(new AssignOp(lhs,exports.operators.ADD,rhs))}code(c){return typeof c=="function"?c():c!==code_1.nil&&this._leafNode(new AnyCode(c)),this}object(...keyValues){let code=["{"];for(let[key,value]of keyValues)code.length>1&&code.push(","),code.push(key),(key!==value||this.opts.es5)&&(code.push(":"),(0,code_1.addCodeArg)(code,value));return code.push("}"),new code_1._Code(code)}if(condition,thenBody,elseBody){if(this._blockNode(new If(condition)),thenBody&&elseBody)this.code(thenBody).else().code(elseBody).endIf();else if(thenBody)this.code(thenBody).endIf();else if(elseBody)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(condition){return this._elseNode(new If(condition))}else(){return this._elseNode(new Else)}endIf(){return this._endBlockNode(If,Else)}_for(node,forBody){return this._blockNode(node),forBody&&this.code(forBody).endFor(),this}for(iteration,forBody){return this._for(new ForLoop(iteration),forBody)}forRange(nameOrPrefix,from,to,forBody,varKind=this.opts.es5?scope_1.varKinds.var:scope_1.varKinds.let){let name=this._scope.toName(nameOrPrefix);return this._for(new ForRange(varKind,name,from,to),()=>forBody(name))}forOf(nameOrPrefix,iterable,forBody,varKind=scope_1.varKinds.const){let name=this._scope.toName(nameOrPrefix);if(this.opts.es5){let arr=iterable instanceof code_1.Name?iterable:this.var("_arr",iterable);return this.forRange("_i",0,(0,code_1._)`${arr}.length`,i=>{this.var(name,(0,code_1._)`${arr}[${i}]`),forBody(name)})}return this._for(new ForIter("of",varKind,name,iterable),()=>forBody(name))}forIn(nameOrPrefix,obj,forBody,varKind=this.opts.es5?scope_1.varKinds.var:scope_1.varKinds.const){if(this.opts.ownProperties)return this.forOf(nameOrPrefix,(0,code_1._)`Object.keys(${obj})`,forBody);let name=this._scope.toName(nameOrPrefix);return this._for(new ForIter("in",varKind,name,obj),()=>forBody(name))}endFor(){return this._endBlockNode(For)}label(label){return this._leafNode(new Label(label))}break(label){return this._leafNode(new Break(label))}return(value){let node=new Return;if(this._blockNode(node),this.code(value),node.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Return)}try(tryBody,catchCode,finallyCode){if(!catchCode&&!finallyCode)throw new Error('CodeGen: "try" without "catch" and "finally"');let node=new Try;if(this._blockNode(node),this.code(tryBody),catchCode){let error3=this.name("e");this._currNode=node.catch=new Catch(error3),catchCode(error3)}return finallyCode&&(this._currNode=node.finally=new Finally,this.code(finallyCode)),this._endBlockNode(Catch,Finally)}throw(error3){return this._leafNode(new Throw(error3))}block(body,nodeCount){return this._blockStarts.push(this._nodes.length),body&&this.code(body).endBlock(nodeCount),this}endBlock(nodeCount){let len=this._blockStarts.pop();if(len===void 0)throw new Error("CodeGen: not in self-balancing block");let toClose=this._nodes.length-len;if(toClose<0||nodeCount!==void 0&&toClose!==nodeCount)throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);return this._nodes.length=len,this}func(name,args=code_1.nil,async,funcBody){return this._blockNode(new Func(name,args,async)),funcBody&&this.code(funcBody).endFunc(),this}endFunc(){return this._endBlockNode(Func)}optimize(n=1){for(;n-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(node){return this._currNode.nodes.push(node),this}_blockNode(node){this._currNode.nodes.push(node),this._nodes.push(node)}_endBlockNode(N1,N2){let n=this._currNode;if(n instanceof N1||N2&&n instanceof N2)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${N2?`${N1.kind}/${N2.kind}`:N1.kind}"`)}_elseNode(node){let n=this._currNode;if(!(n instanceof If))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=node,this}get _root(){return this._nodes[0]}get _currNode(){let ns=this._nodes;return ns[ns.length-1]}set _currNode(node){let ns=this._nodes;ns[ns.length-1]=node}};exports.CodeGen=CodeGen;function addNames(names,from){for(let n in from)names[n]=(names[n]||0)+(from[n]||0);return names}function addExprNames(names,from){return from instanceof code_1._CodeOrName?addNames(names,from.names):names}function optimizeExpr(expr,names,constants){if(expr instanceof code_1.Name)return replaceName(expr);if(!canOptimize(expr))return expr;return new code_1._Code(expr._items.reduce((items,c)=>(c instanceof code_1.Name&&(c=replaceName(c)),c instanceof code_1._Code?items.push(...c._items):items.push(c),items),[]));function replaceName(n){let c=constants[n.str];return c===void 0||names[n.str]!==1?n:(delete names[n.str],c)}function canOptimize(e){return e instanceof code_1._Code&&e._items.some(c=>c instanceof code_1.Name&&names[c.str]===1&&constants[c.str]!==void 0)}}function subtractNames(names,from){for(let n in from)names[n]=(names[n]||0)-(from[n]||0)}function not(x){return typeof x=="boolean"||typeof x=="number"||x===null?!x:(0,code_1._)`!${par(x)}`}exports.not=not;let andCode=mappend(exports.operators.AND);function and(...args){return args.reduce(andCode)}exports.and=and;let orCode=mappend(exports.operators.OR);function or(...args){return args.reduce(orCode)}exports.or=or;function mappend(op){return(x,y)=>x===code_1.nil?y:y===code_1.nil?x:(0,code_1._)`${par(x)} ${op} ${par(y)}`}function par(x){return x instanceof code_1.Name?x:(0,code_1._)`(${x})`}})),require_util=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkStrictMode=exports.getErrorPath=exports.Type=exports.useFunc=exports.setEvaluated=exports.evaluatedPropsToName=exports.mergeEvaluated=exports.eachItem=exports.unescapeJsonPointer=exports.escapeJsonPointer=exports.escapeFragment=exports.unescapeFragment=exports.schemaRefOrVal=exports.schemaHasRulesButRef=exports.schemaHasRules=exports.checkUnknownRules=exports.alwaysValidSchema=exports.toHash=void 0;let codegen_1=require_codegen(),code_1=require_code$1();function toHash(arr){let hash={};for(let item of arr)hash[item]=!0;return hash}exports.toHash=toHash;function alwaysValidSchema(it,schema2){return typeof schema2=="boolean"?schema2:Object.keys(schema2).length===0?!0:(checkUnknownRules(it,schema2),!schemaHasRules(schema2,it.self.RULES.all))}exports.alwaysValidSchema=alwaysValidSchema;function checkUnknownRules(it,schema2=it.schema){let{opts,self}=it;if(!opts.strictSchema||typeof schema2=="boolean")return;let rules=self.RULES.keywords;for(let key in schema2)rules[key]||checkStrictMode(it,`unknown keyword: "${key}"`)}exports.checkUnknownRules=checkUnknownRules;function schemaHasRules(schema2,rules){if(typeof schema2=="boolean")return!schema2;for(let key in schema2)if(rules[key])return!0;return!1}exports.schemaHasRules=schemaHasRules;function schemaHasRulesButRef(schema2,RULES){if(typeof schema2=="boolean")return!schema2;for(let key in schema2)if(key!=="$ref"&&RULES.all[key])return!0;return!1}exports.schemaHasRulesButRef=schemaHasRulesButRef;function schemaRefOrVal({topSchemaRef,schemaPath},schema2,keyword,$data){if(!$data){if(typeof schema2=="number"||typeof schema2=="boolean")return schema2;if(typeof schema2=="string")return(0,codegen_1._)`${schema2}`}return(0,codegen_1._)`${topSchemaRef}${schemaPath}${(0,codegen_1.getProperty)(keyword)}`}exports.schemaRefOrVal=schemaRefOrVal;function unescapeFragment(str){return unescapeJsonPointer(decodeURIComponent(str))}exports.unescapeFragment=unescapeFragment;function escapeFragment(str){return encodeURIComponent(escapeJsonPointer(str))}exports.escapeFragment=escapeFragment;function escapeJsonPointer(str){return typeof str=="number"?`${str}`:str.replace(/~/g,"~0").replace(/\//g,"~1")}exports.escapeJsonPointer=escapeJsonPointer;function unescapeJsonPointer(str){return str.replace(/~1/g,"/").replace(/~0/g,"~")}exports.unescapeJsonPointer=unescapeJsonPointer;function eachItem(xs,f){if(Array.isArray(xs))for(let x of xs)f(x);else f(xs)}exports.eachItem=eachItem;function makeMergeEvaluated({mergeNames,mergeToName,mergeValues:mergeValues2,resultToName}){return(gen,from,to,toName)=>{let res=to===void 0?from:to instanceof codegen_1.Name?(from instanceof codegen_1.Name?mergeNames(gen,from,to):mergeToName(gen,from,to),to):from instanceof codegen_1.Name?(mergeToName(gen,to,from),from):mergeValues2(from,to);return toName===codegen_1.Name&&!(res instanceof codegen_1.Name)?resultToName(gen,res):res}}exports.mergeEvaluated={props:makeMergeEvaluated({mergeNames:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true && ${from} !== undefined`,()=>{gen.if((0,codegen_1._)`${from} === true`,()=>gen.assign(to,!0),()=>gen.assign(to,(0,codegen_1._)`${to} || {}`).code((0,codegen_1._)`Object.assign(${to}, ${from})`))}),mergeToName:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true`,()=>{from===!0?gen.assign(to,!0):(gen.assign(to,(0,codegen_1._)`${to} || {}`),setEvaluated(gen,to,from))}),mergeValues:(from,to)=>from===!0?!0:{...from,...to},resultToName:evaluatedPropsToName}),items:makeMergeEvaluated({mergeNames:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true && ${from} !== undefined`,()=>gen.assign(to,(0,codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),mergeToName:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true`,()=>gen.assign(to,from===!0?!0:(0,codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),mergeValues:(from,to)=>from===!0?!0:Math.max(from,to),resultToName:(gen,items)=>gen.var("items",items)})};function evaluatedPropsToName(gen,ps){if(ps===!0)return gen.var("props",!0);let props=gen.var("props",(0,codegen_1._)`{}`);return ps!==void 0&&setEvaluated(gen,props,ps),props}exports.evaluatedPropsToName=evaluatedPropsToName;function setEvaluated(gen,props,ps){Object.keys(ps).forEach(p=>gen.assign((0,codegen_1._)`${props}${(0,codegen_1.getProperty)(p)}`,!0))}exports.setEvaluated=setEvaluated;let snippets={};function useFunc(gen,f){return gen.scopeValue("func",{ref:f,code:snippets[f.code]||(snippets[f.code]=new code_1._Code(f.code))})}exports.useFunc=useFunc;var Type;(function(Type2){Type2[Type2.Num=0]="Num",Type2[Type2.Str=1]="Str"})(Type||(exports.Type=Type={}));function getErrorPath(dataProp,dataPropType,jsPropertySyntax){if(dataProp instanceof codegen_1.Name){let isNumber=dataPropType===Type.Num;return jsPropertySyntax?isNumber?(0,codegen_1._)`"[" + ${dataProp} + "]"`:(0,codegen_1._)`"['" + ${dataProp} + "']"`:isNumber?(0,codegen_1._)`"/" + ${dataProp}`:(0,codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return jsPropertySyntax?(0,codegen_1.getProperty)(dataProp).toString():"/"+escapeJsonPointer(dataProp)}exports.getErrorPath=getErrorPath;function checkStrictMode(it,msg,mode=it.opts.strictSchema){if(mode){if(msg=`strict mode: ${msg}`,mode===!0)throw new Error(msg);it.self.logger.warn(msg)}}exports.checkStrictMode=checkStrictMode})),require_names=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),names={data:new codegen_1.Name("data"),valCxt:new codegen_1.Name("valCxt"),instancePath:new codegen_1.Name("instancePath"),parentData:new codegen_1.Name("parentData"),parentDataProperty:new codegen_1.Name("parentDataProperty"),rootData:new codegen_1.Name("rootData"),dynamicAnchors:new codegen_1.Name("dynamicAnchors"),vErrors:new codegen_1.Name("vErrors"),errors:new codegen_1.Name("errors"),this:new codegen_1.Name("this"),self:new codegen_1.Name("self"),scope:new codegen_1.Name("scope"),json:new codegen_1.Name("json"),jsonPos:new codegen_1.Name("jsonPos"),jsonLen:new codegen_1.Name("jsonLen"),jsonPart:new codegen_1.Name("jsonPart")};exports.default=names})),require_errors=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.extendErrors=exports.resetErrorsCount=exports.reportExtraError=exports.reportError=exports.keyword$DataError=exports.keywordError=void 0;let codegen_1=require_codegen(),util_1=require_util(),names_1=require_names();exports.keywordError={message:({keyword})=>(0,codegen_1.str)`must pass "${keyword}" keyword validation`},exports.keyword$DataError={message:({keyword,schemaType})=>schemaType?(0,codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)`:(0,codegen_1.str)`"${keyword}" keyword is invalid ($data)`};function reportError(cxt,error3=exports.keywordError,errorPaths,overrideAllErrors){let{it}=cxt,{gen,compositeRule,allErrors}=it,errObj=errorObjectCode(cxt,error3,errorPaths);overrideAllErrors??(compositeRule||allErrors)?addError(gen,errObj):returnErrors(it,(0,codegen_1._)`[${errObj}]`)}exports.reportError=reportError;function reportExtraError(cxt,error3=exports.keywordError,errorPaths){let{it}=cxt,{gen,compositeRule,allErrors}=it;addError(gen,errorObjectCode(cxt,error3,errorPaths)),compositeRule||allErrors||returnErrors(it,names_1.default.vErrors)}exports.reportExtraError=reportExtraError;function resetErrorsCount(gen,errsCount){gen.assign(names_1.default.errors,errsCount),gen.if((0,codegen_1._)`${names_1.default.vErrors} !== null`,()=>gen.if(errsCount,()=>gen.assign((0,codegen_1._)`${names_1.default.vErrors}.length`,errsCount),()=>gen.assign(names_1.default.vErrors,null)))}exports.resetErrorsCount=resetErrorsCount;function extendErrors({gen,keyword,schemaValue,data,errsCount,it}){if(errsCount===void 0)throw new Error("ajv implementation error");let err=gen.name("err");gen.forRange("i",errsCount,names_1.default.errors,i=>{gen.const(err,(0,codegen_1._)`${names_1.default.vErrors}[${i}]`),gen.if((0,codegen_1._)`${err}.instancePath === undefined`,()=>gen.assign((0,codegen_1._)`${err}.instancePath`,(0,codegen_1.strConcat)(names_1.default.instancePath,it.errorPath))),gen.assign((0,codegen_1._)`${err}.schemaPath`,(0,codegen_1.str)`${it.errSchemaPath}/${keyword}`),it.opts.verbose&&(gen.assign((0,codegen_1._)`${err}.schema`,schemaValue),gen.assign((0,codegen_1._)`${err}.data`,data))})}exports.extendErrors=extendErrors;function addError(gen,errObj){let err=gen.const("err",errObj);gen.if((0,codegen_1._)`${names_1.default.vErrors} === null`,()=>gen.assign(names_1.default.vErrors,(0,codegen_1._)`[${err}]`),(0,codegen_1._)`${names_1.default.vErrors}.push(${err})`),gen.code((0,codegen_1._)`${names_1.default.errors}++`)}function returnErrors(it,errs){let{gen,validateName,schemaEnv}=it;schemaEnv.$async?gen.throw((0,codegen_1._)`new ${it.ValidationError}(${errs})`):(gen.assign((0,codegen_1._)`${validateName}.errors`,errs),gen.return(!1))}let E={keyword:new codegen_1.Name("keyword"),schemaPath:new codegen_1.Name("schemaPath"),params:new codegen_1.Name("params"),propertyName:new codegen_1.Name("propertyName"),message:new codegen_1.Name("message"),schema:new codegen_1.Name("schema"),parentSchema:new codegen_1.Name("parentSchema")};function errorObjectCode(cxt,error3,errorPaths){let{createErrors}=cxt.it;return createErrors===!1?(0,codegen_1._)`{}`:errorObject(cxt,error3,errorPaths)}function errorObject(cxt,error3,errorPaths={}){let{gen,it}=cxt,keyValues=[errorInstancePath(it,errorPaths),errorSchemaPath(cxt,errorPaths)];return extraErrorProps(cxt,error3,keyValues),gen.object(...keyValues)}function errorInstancePath({errorPath},{instancePath}){let instPath=instancePath?(0,codegen_1.str)`${errorPath}${(0,util_1.getErrorPath)(instancePath,util_1.Type.Str)}`:errorPath;return[names_1.default.instancePath,(0,codegen_1.strConcat)(names_1.default.instancePath,instPath)]}function errorSchemaPath({keyword,it:{errSchemaPath}},{schemaPath,parentSchema}){let schPath=parentSchema?errSchemaPath:(0,codegen_1.str)`${errSchemaPath}/${keyword}`;return schemaPath&&(schPath=(0,codegen_1.str)`${schPath}${(0,util_1.getErrorPath)(schemaPath,util_1.Type.Str)}`),[E.schemaPath,schPath]}function extraErrorProps(cxt,{params,message},keyValues){let{keyword,data,schemaValue,it}=cxt,{opts,propertyName,topSchemaRef,schemaPath}=it;keyValues.push([E.keyword,keyword],[E.params,typeof params=="function"?params(cxt):params||(0,codegen_1._)`{}`]),opts.messages&&keyValues.push([E.message,typeof message=="function"?message(cxt):message]),opts.verbose&&keyValues.push([E.schema,schemaValue],[E.parentSchema,(0,codegen_1._)`${topSchemaRef}${schemaPath}`],[names_1.default.data,data]),propertyName&&keyValues.push([E.propertyName,propertyName])}})),require_boolSchema=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.boolOrEmptySchema=exports.topBoolOrEmptySchema=void 0;let errors_1=require_errors(),codegen_1=require_codegen(),names_1=require_names(),boolError={message:"boolean schema is false"};function topBoolOrEmptySchema(it){let{gen,schema:schema2,validateName}=it;schema2===!1?falseSchemaError(it,!1):typeof schema2=="object"&&schema2.$async===!0?gen.return(names_1.default.data):(gen.assign((0,codegen_1._)`${validateName}.errors`,null),gen.return(!0))}exports.topBoolOrEmptySchema=topBoolOrEmptySchema;function boolOrEmptySchema(it,valid){let{gen,schema:schema2}=it;schema2===!1?(gen.var(valid,!1),falseSchemaError(it)):gen.var(valid,!0)}exports.boolOrEmptySchema=boolOrEmptySchema;function falseSchemaError(it,overrideAllErrors){let{gen,data}=it,cxt={gen,keyword:"false schema",data,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it};(0,errors_1.reportError)(cxt,boolError,void 0,overrideAllErrors)}})),require_rules=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.getRules=exports.isJSONType=void 0;let jsonTypes=new Set(["string","number","integer","boolean","null","object","array"]);function isJSONType(x){return typeof x=="string"&&jsonTypes.has(x)}exports.isJSONType=isJSONType;function getRules(){let groups={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...groups,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},groups.number,groups.string,groups.array,groups.object],post:{rules:[]},all:{},keywords:{}}}exports.getRules=getRules})),require_applicability=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.shouldUseRule=exports.shouldUseGroup=exports.schemaHasRulesForType=void 0;function schemaHasRulesForType({schema:schema2,self},type){let group=self.RULES.types[type];return group&&group!==!0&&shouldUseGroup(schema2,group)}exports.schemaHasRulesForType=schemaHasRulesForType;function shouldUseGroup(schema2,group){return group.rules.some(rule=>shouldUseRule(schema2,rule))}exports.shouldUseGroup=shouldUseGroup;function shouldUseRule(schema2,rule){var _a3;return schema2[rule.keyword]!==void 0||((_a3=rule.definition.implements)===null||_a3===void 0?void 0:_a3.some(kwd=>schema2[kwd]!==void 0))}exports.shouldUseRule=shouldUseRule})),require_dataType=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.reportTypeError=exports.checkDataTypes=exports.checkDataType=exports.coerceAndCheckDataType=exports.getJSONTypes=exports.getSchemaTypes=exports.DataType=void 0;let rules_1=require_rules(),applicability_1=require_applicability(),errors_1=require_errors(),codegen_1=require_codegen(),util_1=require_util();var DataType;(function(DataType2){DataType2[DataType2.Correct=0]="Correct",DataType2[DataType2.Wrong=1]="Wrong"})(DataType||(exports.DataType=DataType={}));function getSchemaTypes(schema2){let types=getJSONTypes(schema2.type);if(types.includes("null")){if(schema2.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!types.length&&schema2.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');schema2.nullable===!0&&types.push("null")}return types}exports.getSchemaTypes=getSchemaTypes;function getJSONTypes(ts){let types=Array.isArray(ts)?ts:ts?[ts]:[];if(types.every(rules_1.isJSONType))return types;throw new Error("type must be JSONType or JSONType[]: "+types.join(","))}exports.getJSONTypes=getJSONTypes;function coerceAndCheckDataType(it,types){let{gen,data,opts}=it,coerceTo=coerceToTypes(types,opts.coerceTypes),checkTypes=types.length>0&&!(coerceTo.length===0&&types.length===1&&(0,applicability_1.schemaHasRulesForType)(it,types[0]));if(checkTypes){let wrongType=checkDataTypes(types,data,opts.strictNumbers,DataType.Wrong);gen.if(wrongType,()=>{coerceTo.length?coerceData(it,types,coerceTo):reportTypeError(it)})}return checkTypes}exports.coerceAndCheckDataType=coerceAndCheckDataType;let COERCIBLE=new Set(["string","number","integer","boolean","null"]);function coerceToTypes(types,coerceTypes){return coerceTypes?types.filter(t=>COERCIBLE.has(t)||coerceTypes==="array"&&t==="array"):[]}function coerceData(it,types,coerceTo){let{gen,data,opts}=it,dataType=gen.let("dataType",(0,codegen_1._)`typeof ${data}`),coerced=gen.let("coerced",(0,codegen_1._)`undefined`);opts.coerceTypes==="array"&&gen.if((0,codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`,()=>gen.assign(data,(0,codegen_1._)`${data}[0]`).assign(dataType,(0,codegen_1._)`typeof ${data}`).if(checkDataTypes(types,data,opts.strictNumbers),()=>gen.assign(coerced,data))),gen.if((0,codegen_1._)`${coerced} !== undefined`);for(let t of coerceTo)(COERCIBLE.has(t)||t==="array"&&opts.coerceTypes==="array")&&coerceSpecificType(t);gen.else(),reportTypeError(it),gen.endIf(),gen.if((0,codegen_1._)`${coerced} !== undefined`,()=>{gen.assign(data,coerced),assignParentData(it,coerced)});function coerceSpecificType(t){switch(t){case"string":gen.elseIf((0,codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced,(0,codegen_1._)`"" + ${data}`).elseIf((0,codegen_1._)`${data} === null`).assign(coerced,(0,codegen_1._)`""`);return;case"number":gen.elseIf((0,codegen_1._)`${dataType} == "boolean" || ${data} === null
57
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema2===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema2!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}seen.count>1&&ctx.reused==="ref"&&extractToDef(entry)}ctx.external&&(ctx.sharedDefsExtractedFor=ctx.external)}function compactTypeUnion(schema2){let options=schema2.anyOf;if(!Array.isArray(options)||options.length===0||schema2.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!="object")return;compactTypeUnion(option);let keys2=Object.keys(option);if(keys2.length!==1||keys2[0]!=="type")return;let type=option.type;for(let member of Array.isArray(type)?type:[type]){if(typeof member!="string")return;types.includes(member)||types.push(member)}}delete schema2.anyOf,schema2.type=types.length===1?types[0]:types}function undeclaredConstraint(member){let extra=member.additionalProperties;return extra===void 0||extra===!1||typeof extra!="object"||extra===null?null:Object.keys(extra).length?extra:null}function foldObjects(members2){let objects=[];for(let member of members2){if(typeof member!="object"||member.type!=="object")return null;for(let key in member)if(!FOLDABLE_KEYS.has(key))return null;objects.push(member)}let properties={},required2=new Set;for(let object5 of objects){for(let key in object5.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part=other.properties?.[key]??undeclaredConstraint(other);part!=null&&(parts.some(seen=>JSON.stringify(seen)===JSON.stringify(part))||parts.push(part))}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(let key of object5.required??[])required2.add(key)}let folded={type:"object",properties};if(required2.size&&(folded.required=[...required2]),objects.every(object5=>object5.additionalProperties===!1))folded.additionalProperties=!1;else{let constraints=[];for(let object5 of objects){let constraint=undeclaredConstraint(object5);constraint&&!constraints.some(seen=>JSON.stringify(seen)===JSON.stringify(constraint))&&constraints.push(constraint)}constraints.length===1?folded.additionalProperties=constraints[0]:constraints.length>1&&(folded.additionalProperties={allOf:constraints})}return folded}function foldIntersection(json){let allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key of FOLDABLE_KEYS)if(key in json)return;let unions=allOf.filter(m=>UNION_KEYS.some(k=>Array.isArray(m[k]))),folded=null;if(!unions.length)folded=foldObjects(allOf);else{let union2=unions[0],keyword=UNION_KEYS.find(k=>Array.isArray(union2[k]));if(Object.keys(union2).length!==1)return;let rest=allOf.filter(m=>m!==union2),branches=union2[keyword].map(branch=>foldObjects([...rest,branch]));if(branches.some(b=>!b))return;folded={[keyword]:branches}}folded&&(delete json.allOf,assignProps(json,folded))}function finalize(ctx,schema2){let root=ctx.seen.get(schema2);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema3=seen.def??seen.schema,_cached={...schema3},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema3.allOf=schema3.allOf??[],schema3.allOf.push(refSchema)):assignProps(schema3,refSchema),assignProps(schema3,_cached),zodSchema._zod.parent===ref)for(let key in schema3)key==="$ref"||key==="allOf"||key in _cached||delete schema3[key];if(refSchema.$ref&&refSeen.def)for(let key in schema3)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema3[key])===JSON.stringify(refSeen.def[key])&&delete schema3[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema3.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema3)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema3[key])===JSON.stringify(parentSeen.def[key])&&delete schema3[key]}ctx.override({zodSchema,jsonSchema:schema3,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json of[seen.schema,seen.def]){let allOf=json?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);existing?existing.push(json):carriers.set(allOf,[json])}for(let allOf of ctx.intersections)for(let json of carriers.get(allOf)??[])foldIntersection(json)}}let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema2)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema2)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,assignProp(defs,seen.defId,seen.def))}ctx.external&&(ctx.sharedEmitDoneFor=ctx.external),ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema2["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema2,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema2,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var FOLDABLE_KEYS,UNION_KEYS,createToJSONSchemaMethod,createStandardJSONSchemaMethod,init_to_json_schema=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js"(){"use strict";init_registries();init_util();FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]),UNION_KEYS=["oneOf","anyOf"];createToJSONSchemaMethod=(schema2,processors={})=>params=>{let ctx=initializeContext({...params,processors});return processSchema(schema2,ctx),extractDefs(ctx,schema2),finalize(ctx,schema2)},createStandardJSONSchemaMethod=(schema2,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema2,ctx),extractDefs(ctx,schema2),finalize(ctx,schema2)}}});function aggregateChecks(schema2){let agg={},def=schema2._zod.def,list=schema2._zod.traits.has("$ZodCheck")?[schema2,...def.checks??[]]:def.checks??[];for(let ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);let bag=schema2._zod.bag;bag.minimum!==void 0&&narrowMin(agg,"minimum",bag.minimum),bag.exclusiveMinimum!==void 0&&narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum),bag.maximum!==void 0&&narrowMax(agg,"maximum",bag.maximum),bag.exclusiveMaximum!==void 0&&narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum),bag.multipleOf!==void 0&&addDivisor(agg,bag.multipleOf),bag.format!==void 0&&(agg.format??(agg.format=bag.format),bag.format.includes("int")&&(agg.isInt=!0)),bag.mime&&intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}function inputOptin(schema2){let def=schema2._zod.def;return def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")?inputOptin(def.out):def.type==="catch"?inputOptin(def.innerType):schema2._zod.optin}function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);let def=bySchema.get(json)?.def;if(!def)return json;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map(branch=>stringifyKeyNames(bySchema,branch,visited));mapped.some((branch,i)=>branch!==branches[i])&&(json={...json,[keyword]:mapped})}let types=Array.isArray(json.type)?json.type:[json.type],numericType=!types.includes("string")&&types.some(t=>t==="number"||t==="integer"),values=json.enum??(json.const!==void 0?[json.const]:void 0);if(!numericType&&!values?.some(v=>typeof v=="number"))return json;let{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json;return rest.enum?rest.enum=rest.enum.map(v=>typeof v=="number"?String(v):v):typeof rest.const=="number"&&(rest.const=String(rest.const)),numericType&&(rest.type="string",values||(rest.pattern=(types.includes("number")?number:integer).source)),rest}function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())entry.def&&!bySchema.has(entry.schema)&&bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record5 of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record5),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);rewritten!==names&&rewrites.set(names,rewritten)}if(rewrites.size)for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);rewritten&&(carrier.propertyNames=rewritten)}}function serializeDefaultValue(value,schema2,ctx,json,params){let unrepresentable=!1,serialized=JSON.stringify(value,(_,val)=>typeof val!="bigint"?val:(unrepresentable=!0,null));return unrepresentable?(handleUnrepresentable(schema2,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT):JSON.parse(serialized)}function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema2]=entry;processSchema(schema2,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema2]=entry;extractDefs(ctx2,schema2),assignProp(schemas,key,finalize(ctx2,schema2))}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return processSchema(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var narrowMin,narrowMax,narrowBoth,addDivisor,addPattern,intersectMime,setFormat,minContributor,maxContributor,formatContributor,contributors,formatMap,exactPatterns,exactPattern,stringProcessor,numberProcessor,booleanProcessor,bigintProcessor,symbolProcessor,nullProcessor,undefinedProcessor,voidProcessor,neverProcessor,anyProcessor,unknownProcessor,dateProcessor,enumProcessor,literalProcessor,nanProcessor,templateLiteralProcessor,fileProcessor,successProcessor,customProcessor,functionProcessor,transformProcessor,mapProcessor,setProcessor,arrayProcessor,objectProcessor,unionProcessor,intersectionProcessor,tupleProcessor,pendingRecords,recordProcessor,nullableProcessor,nonoptionalProcessor,UNREPRESENTABLE_DEFAULT,defaultProcessor,prefaultProcessor,catchProcessor,pipeProcessor,readonlyProcessor,promiseProcessor,optionalProcessor,lazyProcessor,allProcessors,init_json_schema_processors=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js"(){"use strict";init_regexes();init_schemas();init_to_json_schema();init_util();narrowMin=(agg,key,value)=>{(agg[key]===void 0||value>agg[key])&&(agg[key]=value)},narrowMax=(agg,key,value)=>{(agg[key]===void 0||value<agg[key])&&(agg[key]=value)},narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value),narrowMax(agg,"maximum",value)},addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]),agg.multipleOf.includes(value)||agg.multipleOf.push(value)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter(m=>mime.includes(m)):[...mime]},setFormat=(agg,format)=>{agg.format=format,format.includes("int")&&(agg.isInt=!0)},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=ranges=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format),def.pattern&&addPattern(agg,def.pattern),(def.format==="base64"||def.format==="base64url")&&(agg.contentEncoding=def.format),(def.local||def.precision===-1)&&(agg.laxFormat=!0)},mime_type:(agg,def)=>intersectMime(agg,def.mime)};formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=p=>exactPatterns.get(p)??p,stringProcessor=(schema2,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema2);if(typeof minimum=="number"&&(json.minLength=minimum),typeof maximum=="number"&&(json.maxLength=maximum),format&&(json.format=formatMap[format]??format,json.format===""&&delete json.format,(format==="time"||laxFormat)&&delete json.format),contentEncoding&&(json.contentEncoding=contentEncoding),patterns&&patterns.size>0){let patternList=[...patterns].map(exactPattern);patternList.length===1?json.pattern=patternList[0].source:patternList.length>1&&(json.allOf=[...patternList.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema2,ctx,_json,params)=>{let json=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema2);json.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin?legacy?(json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0):json.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json.minimum=minimum),exMax?legacy?(json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0):json.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json.maximum=maximum),multipleOf){let divisors=new Set;for(let divisor of multipleOf)Number.isFinite(divisor)&&divisor!==0?divisors.add(Math.abs(divisor)):handleUnrepresentable(schema2,ctx,json,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);let[first,...rest]=divisors;first!==void 0&&(json.multipleOf=first),rest.length&&(json.allOf=[...json.allOf??[],...rest.map(m=>({multipleOf:m}))])}},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"BigInt cannot be represented in JSON Schema")},symbolProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{ctx.target==="openapi-3.0"?(json.type="string",json.nullable=!0,json.enum=[null]):json.type="null"},undefinedProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"Undefined cannot be represented in JSON Schema")},voidProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"Date cannot be represented in JSON Schema")},enumProcessor=(schema2,_ctx,json,_params)=>{let def=schema2._zod.def,values=getEnumValues(def.entries);if(values.length===0){json.not={};return}values.every(v=>typeof v=="number")&&(json.type="number"),values.every(v=>typeof v=="string")&&(json.type="string"),json.enum=values},literalProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;if(def.values.length===0){json.not={};return}let vals=[];for(let val of def.values)if(val===void 0){if(handleUnrepresentable(schema2,ctx,json,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val=="bigint"){if(handleUnrepresentable(schema2,ctx,json,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json.enum=[val]:json.const=val}else vals.every(v=>typeof v=="number")&&(json.type="number"),vals.every(v=>typeof v=="string")&&(json.type="string"),vals.every(v=>typeof v=="boolean")&&(json.type="boolean"),vals.every(v=>v===null)&&(json.type="null"),json.enum=vals},nanProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema2,_ctx,json,_params)=>{let _json=json,pattern=schema2._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema2,_ctx,json,_params)=>{let _json=json;_json.type="string",_json.format="binary",_json.contentEncoding="binary";let{minimum,maximum,mime}=aggregateChecks(schema2);minimum!==void 0&&(_json.minLength=minimum),maximum!==void 0&&(_json.maxLength=maximum),mime&&(mime.length===0?_json.not={}:mime.length===1?_json.contentMediaType=mime[0]:_json.anyOf=mime.map(m=>({contentMediaType:m})))},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"Custom types cannot be represented in JSON Schema")},functionProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"Function types cannot be represented in JSON Schema")},transformProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"Transforms cannot be represented in JSON Schema")},mapProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"Map cannot be represented in JSON Schema")},setProcessor=(schema2,ctx,json,params)=>{handleUnrepresentable(schema2,ctx,json,params,"Set cannot be represented in JSON Schema")},arrayProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def,{minimum,maximum}=aggregateChecks(schema2);typeof minimum=="number"&&(json.minItems=minimum),typeof maximum=="number"&&(json.maxItems=maximum),json.type="array",json.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};objectProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema2,ctx,json,params,"Symbol keys cannot be represented in JSON Schema"))return;json.type="object",json.properties={};for(let key in shape)assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}));let requiredKeys=[];for(let key of Object.keys(shape)){let field=def.shape[key];(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)&&requiredKeys.push(key)}requiredKeys.length>0&&(json.required=requiredKeys),def.catchall?._zod.def.type==="never"?json.additionalProperties=!1:def.catchall?def.catchall&&(json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json.additionalProperties=!1)},unionProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));isExclusive?json.oneOf=options:json.anyOf=options},intersectionProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf,ctx.intersections.push(allOf)},tupleProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null,minItems=def.items.length;for(;minItems>0;){let item=def.items[minItems-1];if(!(ctx.io==="input"?inputOptin(item)!==void 0:item._zod.optout==="optional"))break;minItems--}let maxItems=def.items.length,isClosed=!def.rest;ctx.target==="draft-2020-12"?(json.prefixItems=prefixItems,isClosed?json.items=!1:rest&&(json.items=rest),minItems>0&&(json.minItems=minItems),isClosed&&(json.maxItems=maxItems)):ctx.target==="openapi-3.0"?(json.items={anyOf:prefixItems},rest&&json.items.anyOf.push(rest),minItems>0&&(json.minItems=minItems),isClosed&&(json.maxItems=maxItems)):(json.items=prefixItems,isClosed?json.additionalItems=!1:rest&&(json.additionalItems=rest),minItems>0&&(json.minItems=minItems),isClosed&&(json.maxItems=maxItems));let{minimum,maximum}=aggregateChecks(schema2);typeof minimum=="number"&&(json.minItems=minimum),typeof maximum=="number"&&(json.maxItems=maximum)};pendingRecords=new WeakMap;recordProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)assignProp(json.patternProperties,exactPattern(pattern).source,valueSchema)}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending2=pendingRecords.get(ctx);pending2||(pending2=[],pendingRecords.set(ctx,pending2),ctx.deferred.push(()=>rewriteKeyNames(ctx))),pending2.push(schema2)}json.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json.required=validKeyValues.map(String))}},nullableProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema2);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json.nullable=!0):json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();defaultProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType;let value=serializeDefaultValue(def.defaultValue,schema2,ctx,json,params);value!==UNREPRESENTABLE_DEFAULT&&(json.default=value)},prefaultProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);if(seen.ref=def.innerType,ctx.io!=="input")return;let value=serializeDefaultValue(def.defaultValue,schema2,ctx,json,params);value!==UNREPRESENTABLE_DEFAULT&&(json._prefault=value)},catchProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema2,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue},pipeProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=innerType},readonlyProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},optionalProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},lazyProcessor=(schema2,ctx,_json,params)=>{let innerType=schema2._zod.innerType;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}}});var init_json_schema=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js"(){"use strict"}});var init_core2=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js"(){"use strict";init_core();init_parse();init_errors();init_schemas();init_memoizer();init_checks();init_versions();init_util();init_regexes();init_locales();init_registries();init_doc();init_compile();init_api();init_to_json_schema();init_json_schema()}});var init_checks2=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js"(){"use strict";init_core2()}});function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let value=make(this);return Object.defineProperty(this,key,{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,key,{value,configurable:!0,writable:!0})}})}var _installedErrorProtos,initializer2,ZodRealError,init_errors2=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js"(){"use strict";init_core2();init_core2();init_util();_installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let proto=Object.getPrototypeOf(inst);_installedErrorProtos.has(proto)||(_installedErrorProtos.add(proto),_lazyMethod(proto,"format",self=>mapper=>formatError(self,mapper)),_lazyMethod(proto,"flatten",self=>mapper=>flattenError(self,mapper)),_lazyMethod(proto,"addIssue",self=>issue2=>{self.issues.push(issue2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),_lazyMethod(proto,"addIssues",self=>issues2=>{self.issues.push(...issues2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),Object.defineProperty(proto,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error})}});var parse,parseAsync,safeParse,safeParseAsync,encode,decode,encodeAsync,decodeAsync,safeEncode,safeDecode,safeEncodeAsync,safeDecodeAsync,init_parse2=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js"(){"use strict";init_core2();init_errors2();init_core2();parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError)}});function _ensureDefaultLocale(){globalConfig.localeError||config(en_default())}function _ensureDefaultMemoizer(){globalConfig.memoizer||config({memoizer:memoizer()})}function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function url(params){return _url(ZodURL,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function array(element,params){return _array(ZodArray,element,params)}function object(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function _enum(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}function transform(fn){return new ZodTransform({type:"transform",transform:fn})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function _default(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}function _catch(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:util_exports.constantCatch(catchValue)})}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function preprocess(fn,schema2){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema2})}var ZodType,_ZodString,ZodString,ZodStringFormat,ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodDate,ZodArray,ZodObject,ZodUnion,ZodDiscriminatedUnion,ZodIntersection,ZodRecord,ZodEnum,ZodLiteral,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodCatch,ZodPipe,ZodPreprocess,ZodReadonly,ZodLazy,ZodCustom,init_schemas2=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js"(){"use strict";init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_en();init_checks2();init_parse2();ZodType=$constructor("ZodType",(inst,def)=>(_ensureDefaultLocale(),$ZodType.init(inst,def),inst.def=def,inst.type=def.type,inst),{check(...chks){let def=this.def;return this.clone(util_exports.mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch=>typeof ch=="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta2){return reg.add(this,meta2),this},refine(check,params){return this.check(refine(check,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get"~standard"(){return util_exports.hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set"~standard"(value){util_exports.own(this,"~standard",value)},parse:function _parse2(data,params){return parse(this,data,params,{callee:_parse2})},parseAsync:async function _parseAsync2(data,params){return await parseAsync(this,data,params,{callee:_parseAsync2})},safeParse(data,params){return safeParse(this,data,params)},async safeParseAsync(data,params){return safeParseAsync(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){util_exports.own(this,"spa",value)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode2(data,params){return encode(this,data,params,{callee:_encode2})},decode:function _decode2(data,params){return decode(this,data,params,{callee:_decode2})},encodeAsync:async function _encodeAsync2(data,params){return await encodeAsync(this,data,params,{callee:_encodeAsync2})},decodeAsync:async function _decodeAsync2(data,params){return await decodeAsync(this,data,params,{callee:_decodeAsync2})},safeEncode(data,params){return safeEncode(this,data,params)},safeDecode(data,params){return safeDecode(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params)},util_exports.derived({format:inst=>aggregateChecks(inst).format??null,minLength:inst=>aggregateChecks(inst).minimum??null,maxLength:inst=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)}),ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)}),ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)}),ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)}),ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)}),ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.isFinite=!0},util_exports.derived({minValue:inst=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:inst=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:inst=>{let{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:inst=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params)},util_exports.derived({minValue:inst=>aggregateChecks(inst).minimum??null,maxValue:inst=>aggregateChecks(inst).maximum??null,format:inst=>aggregateChecks(inst).format??null},{gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},gt(value,params){return this.check(_gt(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value,params){return this.check(_multipleOf(value,params))}})),ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>dateProcessor(inst,ctx,json,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params))},util_exports.derived({minDate:inst=>{let{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:inst=>{let{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{})),ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),util_exports.installLazyProp(inst,"shape",self=>self._zod.def.shape,!1)},{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},exactPartial(...args){return util_exports.partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys2=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys2.has(value))newEntries[value]=def.entries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys2.has(value))delete newEntries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output=def.transform(payload.value,payload);return output instanceof Promise?output.then(output2=>(payload.value=output2,payload)):(payload.value=output,payload)}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>lazyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.getter()});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)})}});var ZodIssueCode,ZodFirstPartyTypeKind,init_compat=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js"(){"use strict";ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={})}});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date2,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var init_iso=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js"(){"use strict";init_core2();init_schemas2();init_schemas2()}});var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint2,boolean:()=>boolean3,date:()=>date3,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint2(params){return _coercedBigint(ZodBigInt,params)}function date3(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js"(){"use strict";init_core2();init_schemas2()}});var init_external=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js"(){"use strict";init_core2();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();init_core2();init_json_schema_processors();init_locales();init_iso();init_coerce()}});var init_classic=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/index.js"(){"use strict";init_external()}});var init_v4=__esm({"../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/index.js"(){"use strict";init_classic()}});var LATEST_PROTOCOL_VERSION,DEFAULT_NEGOTIATED_PROTOCOL_VERSION,SUPPORTED_PROTOCOL_VERSIONS,RELATED_TASK_META_KEY,PROTOCOL_VERSION_META_KEY,CLIENT_INFO_META_KEY,SERVER_INFO_META_KEY,CLIENT_CAPABILITIES_META_KEY,SUBSCRIPTION_ID_META_KEY,LOG_LEVEL_META_KEY,JSONRPC_VERSION,INVALID_PARAMS,JSONValueSchema,JSONObjectSchema,JSONArraySchema,ProgressTokenSchema,CursorSchema,TaskMetadataSchema,RelatedTaskMetadataSchema,RequestMetaSchema,BaseRequestParamsSchema,TaskAugmentedRequestParamsSchema,RequestSchema,NotificationsParamsSchema,NotificationSchema,ResultMetaObjectSchema,ResultSchema,RequestIdSchema,JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema,JSONRPCMessageSchema,JSONRPCResponseSchema,EmptyResultSchema,CancelledNotificationParamsSchema,CancelledNotificationSchema,IconSchema,IconsSchema,BaseMetadataSchema,ImplementationSchema,FormElicitationCapabilitySchema,ElicitationCapabilitySchema,ClientTasksCapabilitySchema,ServerTasksCapabilitySchema,ClientCapabilitiesSchema,InitializeRequestParamsSchema,InitializeRequestSchema,ServerCapabilitiesSchema,InitializeResultSchema,InitializedNotificationSchema,DiscoverRequestSchema,DiscoverResultSchema,PingRequestSchema,ProgressSchema,ProgressNotificationParamsSchema,ProgressNotificationSchema,PaginatedRequestParamsSchema,PaginatedRequestSchema,PaginatedResultSchema,ResourceContentsSchema,TextResourceContentsSchema,Base64Schema,BlobResourceContentsSchema,RoleSchema,AnnotationsSchema,ResourceSchema,ResourceTemplateSchema,ListResourcesRequestSchema,ListResourcesResultSchema,ListResourceTemplatesRequestSchema,ListResourceTemplatesResultSchema,ResourceRequestParamsSchema,ReadResourceRequestParamsSchema,ReadResourceRequestSchema,ReadResourceResultSchema,ResourceListChangedNotificationSchema,SubscribeRequestParamsSchema,SubscribeRequestSchema,UnsubscribeRequestParamsSchema,UnsubscribeRequestSchema,SubscriptionFilterSchema,SubscriptionsListenRequestParamsSchema,SubscriptionsListenRequestSchema,SubscriptionsAcknowledgedNotificationParamsSchema,SubscriptionsAcknowledgedNotificationSchema,SubscriptionsListenResultMetaSchema,SubscriptionsListenResultSchema,ResourceUpdatedNotificationParamsSchema,ResourceUpdatedNotificationSchema,PromptArgumentSchema,PromptSchema,ListPromptsRequestSchema,ListPromptsResultSchema,GetPromptRequestParamsSchema,GetPromptRequestSchema,TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,EmbeddedResourceSchema,ResourceLinkSchema,ContentBlockSchema,PromptMessageSchema,GetPromptResultSchema,PromptListChangedNotificationSchema,ToolAnnotationsSchema,ToolExecutionSchema,ToolSchema,ListToolsRequestSchema,ListToolsResultSchema,CallToolResultSchema,CompatibilityCallToolResultSchema,CallToolRequestParamsSchema,CallToolRequestSchema,ToolListChangedNotificationSchema,ListChangedOptionsBaseSchema,LoggingLevelSchema,SetLevelRequestParamsSchema,SetLevelRequestSchema,LoggingMessageNotificationParamsSchema,LoggingMessageNotificationSchema,ModelHintSchema,ModelPreferencesSchema,ToolChoiceSchema,ToolResultContentSchema,SamplingContentSchema,SamplingMessageContentBlockSchema,SamplingMessageSchema,CreateMessageRequestParamsSchema,CreateMessageRequestSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema,UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema,LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema,EnumSchemaSchema,PrimitiveSchemaDefinitionSchema,ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema,ElicitRequestParamsSchema,ElicitRequestSchema,ElicitationCompleteNotificationParamsSchema,ElicitationCompleteNotificationSchema,ElicitResultSchema,ResourceTemplateReferenceSchema,PromptReferenceSchema,CompleteRequestParamsSchema,CompleteRequestSchema,CompleteResultSchema,RootSchema,ListRootsRequestSchema,ListRootsResultSchema,RootsListChangedNotificationSchema,TaskCreationParamsSchema,TaskStatusSchema,TaskSchema,CreateTaskResultSchema,TaskStatusNotificationParamsSchema,TaskStatusNotificationSchema,GetTaskRequestSchema,GetTaskResultSchema,GetTaskPayloadRequestSchema,GetTaskPayloadResultSchema,ListTasksRequestSchema,ListTasksResultSchema,CancelTaskRequestSchema,CancelTaskResultSchema,ClientRequestSchema,ClientNotificationSchema,ClientResultSchema,ServerRequestSchema,ServerNotificationSchema,ServerResultSchema,SafeUrlSchema,OAuthProtectedResourceMetadataSchema,OAuthMetadataSchema,OpenIdProviderMetadataSchema,OpenIdProviderDiscoveryMetadataSchema,OAuthTokensSchema,IdJagTokenExchangeResponseSchema,OAuthErrorResponseSchema,OptionalSafeUrlSchema,OAuthClientMetadataSchema,OAuthClientInformationSchema,OAuthClientInformationFullSchema,OAuthClientRegistrationErrorSchema,OAuthTokenRevocationRequestSchema,init_auth_BNDyLTqp=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+core@2.3.1/node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs"(){"use strict";init_v4();LATEST_PROTOCOL_VERSION="2025-11-25",DEFAULT_NEGOTIATED_PROTOCOL_VERSION="2025-03-26",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",PROTOCOL_VERSION_META_KEY="io.modelcontextprotocol/protocolVersion",CLIENT_INFO_META_KEY="io.modelcontextprotocol/clientInfo",SERVER_INFO_META_KEY="io.modelcontextprotocol/serverInfo",CLIENT_CAPABILITIES_META_KEY="io.modelcontextprotocol/clientCapabilities",SUBSCRIPTION_ID_META_KEY="io.modelcontextprotocol/subscriptionId",LOG_LEVEL_META_KEY="io.modelcontextprotocol/logLevel",JSONRPC_VERSION="2.0",INVALID_PARAMS=-32602,JSONValueSchema=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema),array(JSONValueSchema)])),JSONObjectSchema=record(string2(),JSONValueSchema),JSONArraySchema=array(JSONValueSchema),ProgressTokenSchema=union([string2(),number2().int()]),CursorSchema=string2(),TaskMetadataSchema=object({ttl:number2().optional()}),RelatedTaskMetadataSchema=object({taskId:string2()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),RequestSchema=object({method:string2(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object({_meta:RequestMetaSchema.optional()}),NotificationSchema=object({method:string2(),params:NotificationsParamsSchema.loose().optional()}),ResultMetaObjectSchema=looseObject({get[SERVER_INFO_META_KEY](){return ImplementationSchema.optional().catch(void 0)}}),ResultSchema=looseObject({_meta:ResultMetaObjectSchema.optional()}),RequestIdSchema=union([string2(),number2().int()]),JSONRPCRequestSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),JSONRPCNotificationSchema=object({jsonrpc:literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),JSONRPCResultResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),JSONRPCErrorResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:object({code:number2().int(),message:string2(),data:unknown().optional()})}).strict(),JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string2().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema=object({icons:array(IconSchema).optional()}),BaseMetadataSchema=object({name:string2(),title:string2().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema),ElicitationCapabilitySchema=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema.optional(),url:JSONObjectSchema.optional()}),JSONObjectSchema.optional())),ClientTasksCapabilitySchema=looseObject({list:JSONObjectSchema.optional(),cancel:JSONObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:JSONObjectSchema.optional(),cancel:JSONObjectSchema.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object({experimental:record(string2(),JSONObjectSchema).optional(),sampling:object({context:JSONObjectSchema.optional(),tools:JSONObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string2(),JSONObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal("initialize"),params:InitializeRequestParamsSchema}),ServerCapabilitiesSchema=object({experimental:record(string2(),JSONObjectSchema).optional(),logging:JSONObjectSchema.optional(),completions:JSONObjectSchema.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string2(),JSONObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string2().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()}),DiscoverRequestSchema=RequestSchema.extend({method:literal("server/discover"),params:BaseRequestParamsSchema.optional()}),DiscoverResultSchema=ResultSchema.extend({supportedVersions:array(string2()),capabilities:ServerCapabilitiesSchema,instructions:string2().optional()}),PingRequestSchema=RequestSchema.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema=object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),ResourceContentsSchema=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string2()}),Base64Schema=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum(["user","assistant"]),AnnotationsSchema=object({audience:array(RoleSchema).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string2()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),SubscriptionFilterSchema=object({toolsListChanged:boolean2().optional(),promptsListChanged:boolean2().optional(),resourcesListChanged:boolean2().optional(),resourceSubscriptions:array(string2()).optional()}),SubscriptionsListenRequestParamsSchema=BaseRequestParamsSchema.extend({notifications:SubscriptionFilterSchema}),SubscriptionsListenRequestSchema=RequestSchema.extend({method:literal("subscriptions/listen"),params:SubscriptionsListenRequestParamsSchema}),SubscriptionsAcknowledgedNotificationParamsSchema=NotificationsParamsSchema.extend({notifications:SubscriptionFilterSchema}),SubscriptionsAcknowledgedNotificationSchema=NotificationSchema.extend({method:literal("notifications/subscriptions/acknowledged"),params:SubscriptionsAcknowledgedNotificationParamsSchema}),SubscriptionsListenResultMetaSchema=ResultMetaObjectSchema.extend({[SUBSCRIPTION_ID_META_KEY]:RequestIdSchema}),SubscriptionsListenResultSchema=ResultSchema.extend({_meta:SubscriptionsListenResultMetaSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string2()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string2(),arguments:record(string2(),string2()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema=object({type:literal("image"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema=object({type:literal("audio"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema=object({type:literal("resource"),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal("resource_link")}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string2().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolExecutionSchema=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string2().optional(),inputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:looseObject({$schema:string2().optional()}).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string2(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:unknown().optional(),isError:boolean2().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string2(),arguments:record(string2(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object({autoRefresh:boolean2().default(!0),debounceMs:number2().int().nonnegative().default(300)}),LoggingLevelSchema=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object({name:string2().optional()}),ModelPreferencesSchema=object({hints:array(ModelHintSchema).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema=object({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema),structuredContent:unknown().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string2(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema),required:array(string2()).optional()}).catchall(unknown())}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string2()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional())}),ResourceTemplateReferenceSchema=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema=object({type:literal("ref/prompt"),name:string2()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema}),CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})}),RootSchema=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),TaskCreationParamsSchema=looseObject({ttl:number2().optional(),pollInterval:number2().optional()}),TaskStatusSchema=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=object({taskId:string2(),status:TaskStatusSchema,ttl:union([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,DiscoverRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,SubscriptionsListenRequestSchema,CallToolRequestSchema,ListToolsRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,SubscriptionsAcknowledgedNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,DiscoverResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,SubscriptionsListenResultSchema]),SafeUrlSchema=url().superRefine((val,ctx)=>{if(!URL.canParse(val))return ctx.addIssue({code:ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),NEVER}).refine(url2=>{let u=new URL(url2);return u.protocol!=="javascript:"&&u.protocol!=="data:"&&u.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),OAuthProtectedResourceMetadataSchema=looseObject({resource:string2().url(),authorization_servers:array(SafeUrlSchema).optional(),jwks_uri:string2().url().optional(),scopes_supported:array(string2()).optional(),bearer_methods_supported:array(string2()).optional(),resource_signing_alg_values_supported:array(string2()).optional(),resource_name:string2().optional(),resource_documentation:string2().optional(),resource_policy_uri:string2().url().optional(),resource_tos_uri:string2().url().optional(),tls_client_certificate_bound_access_tokens:boolean2().optional(),authorization_details_types_supported:array(string2()).optional(),dpop_signing_alg_values_supported:array(string2()).optional(),dpop_bound_access_tokens_required:boolean2().optional()}),OAuthMetadataSchema=looseObject({issuer:string2(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array(string2()).optional(),response_types_supported:array(string2()),response_modes_supported:array(string2()).optional(),grant_types_supported:array(string2()).optional(),token_endpoint_auth_methods_supported:array(string2()).optional(),token_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),service_documentation:SafeUrlSchema.optional(),revocation_endpoint:SafeUrlSchema.optional(),revocation_endpoint_auth_methods_supported:array(string2()).optional(),revocation_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),introspection_endpoint:string2().optional(),introspection_endpoint_auth_methods_supported:array(string2()).optional(),introspection_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),code_challenge_methods_supported:array(string2()).optional(),client_id_metadata_document_supported:boolean2().optional(),authorization_response_iss_parameter_supported:boolean2().optional().catch(void 0),dpop_signing_alg_values_supported:array(string2()).optional()}),OpenIdProviderMetadataSchema=looseObject({issuer:string2(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,userinfo_endpoint:SafeUrlSchema.optional(),jwks_uri:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array(string2()).optional(),response_types_supported:array(string2()),response_modes_supported:array(string2()).optional(),grant_types_supported:array(string2()).optional(),acr_values_supported:array(string2()).optional(),subject_types_supported:array(string2()),id_token_signing_alg_values_supported:array(string2()),id_token_encryption_alg_values_supported:array(string2()).optional(),id_token_encryption_enc_values_supported:array(string2()).optional(),userinfo_signing_alg_values_supported:array(string2()).optional(),userinfo_encryption_alg_values_supported:array(string2()).optional(),userinfo_encryption_enc_values_supported:array(string2()).optional(),request_object_signing_alg_values_supported:array(string2()).optional(),request_object_encryption_alg_values_supported:array(string2()).optional(),request_object_encryption_enc_values_supported:array(string2()).optional(),token_endpoint_auth_methods_supported:array(string2()).optional(),token_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),display_values_supported:array(string2()).optional(),claim_types_supported:array(string2()).optional(),claims_supported:array(string2()).optional(),service_documentation:string2().optional(),claims_locales_supported:array(string2()).optional(),ui_locales_supported:array(string2()).optional(),claims_parameter_supported:boolean2().optional(),request_parameter_supported:boolean2().optional(),request_uri_parameter_supported:boolean2().optional(),require_request_uri_registration:boolean2().optional(),op_policy_uri:SafeUrlSchema.optional(),op_tos_uri:SafeUrlSchema.optional(),client_id_metadata_document_supported:boolean2().optional(),authorization_response_iss_parameter_supported:boolean2().optional().catch(void 0)}),OpenIdProviderDiscoveryMetadataSchema=object({...OpenIdProviderMetadataSchema.shape,...OAuthMetadataSchema.pick({code_challenge_methods_supported:!0}).shape}),OAuthTokensSchema=object({access_token:string2(),id_token:string2().optional(),token_type:string2(),expires_in:coerce_exports.number().optional(),scope:string2().optional(),refresh_token:string2().optional(),issuer:string2().optional().catch(void 0)}).strip(),IdJagTokenExchangeResponseSchema=object({issued_token_type:literal("urn:ietf:params:oauth:token-type:id-jag"),access_token:string2(),token_type:string2().optional(),expires_in:number2().optional(),scope:string2().optional()}).strip(),OAuthErrorResponseSchema=object({error:string2(),error_description:string2().optional(),error_uri:string2().optional()}),OptionalSafeUrlSchema=SafeUrlSchema.optional().or(literal("").transform(()=>{})),OAuthClientMetadataSchema=object({redirect_uris:array(SafeUrlSchema),token_endpoint_auth_method:string2().optional(),grant_types:array(string2()).optional(),response_types:array(string2()).optional(),application_type:string2().optional(),client_name:string2().optional(),client_uri:SafeUrlSchema.optional(),logo_uri:OptionalSafeUrlSchema,scope:string2().optional(),contacts:array(string2()).optional(),tos_uri:OptionalSafeUrlSchema,policy_uri:string2().optional(),jwks_uri:SafeUrlSchema.optional(),jwks:any().optional(),software_id:string2().optional(),software_version:string2().optional(),software_statement:string2().optional()}).strip(),OAuthClientInformationSchema=object({client_id:string2(),client_secret:string2().optional(),client_id_issued_at:number2().optional(),client_secret_expires_at:number2().optional(),issuer:string2().optional().catch(void 0)}).strip(),OAuthClientInformationFullSchema=OAuthClientMetadataSchema.merge(OAuthClientInformationSchema),OAuthClientRegistrationErrorSchema=object({error:string2(),error_description:string2().optional()}).strip(),OAuthTokenRevocationRequestSchema=object({token:string2(),token_type_hint:string2().optional()}).strip()}});var init_internal=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+core@2.3.1/node_modules/@modelcontextprotocol/core/dist/internal.mjs"(){"use strict";init_auth_BNDyLTqp()}});function stampErrorBrands(instance,ctor){let brands=new Set,current=ctor;for(;typeof current=="function";){let brand=current.mcpBrand;Object.prototype.hasOwnProperty.call(current,"mcpBrand")&&typeof brand=="string"&&brands.add(brand),current=Object.getPrototypeOf(current)}brands.size!==0&&Object.defineProperty(instance,BRANDS,{value:brands,enumerable:!1,configurable:!0})}function brandedHasInstance(cls,value){try{if(typeof value=="object"&&value!==null&&Object.prototype.hasOwnProperty.call(cls,"mcpBrand")&&typeof cls.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(value,BRANDS)){let carried=value[BRANDS];if(carried&&typeof carried.has=="function"&&carried.has(cls.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(cls,value)}function requiredClientCapabilitiesForRequest(method){return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD,method)?REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method]:void 0}function isPlainObject$7(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isImpliedCapabilityMember(capability,member,declaredValue){return capability==="elicitation"&&member==="form"&&declaredValue.form===void 0&&declaredValue.url===void 0}function requiredClientCapabilitiesForInputRequest(entry){switch(entry.method){case"elicitation/create":return entry.params?.mode==="url"?{elicitation:{url:{}}}:{elicitation:{form:{}}};case"sampling/createMessage":{let params=entry.params;return params!==void 0&&(params.tools!==void 0||params.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case"roots/list":return{roots:{}};default:return}}function missingClientCapabilities(required2,declared){let missing={};for(let[capability,requirement]of Object.entries(required2)){if(requirement===void 0)continue;let declaredValue=declared===void 0?void 0:declared[capability];if(declaredValue===void 0){missing[capability]=requirement;continue}if(isPlainObject$7(requirement)&&isPlainObject$7(declaredValue)){let missingMembers={};for(let[member,memberRequirement]of Object.entries(requirement))memberRequirement!==void 0&&declaredValue[member]===void 0&&!isImpliedCapabilityMember(capability,member,declaredValue)&&(missingMembers[member]=memberRequirement);Object.keys(missingMembers).length>0&&(missing[capability]=missingMembers)}}return Object.keys(missing).length>0?missing:void 0}function isModernProtocolVersion(version2){return version2>=FIRST_MODERN_PROTOCOL_VERSION}function legacyProtocolVersions(versions){return versions.filter(version2=>!isModernProtocolVersion(version2))}function modernProtocolVersions(versions){return versions.filter(version2=>isModernProtocolVersion(version2))}function appendTextFallbackForNonObject(result){let sc=result.structuredContent;return sc===void 0||!(typeof sc!="object"||sc===null||Array.isArray(sc))||(result.content?.some(c=>c.type==="text")??!1)?result:{...result,content:[...result.content??[],{type:"text",text:JSON.stringify(sc)}]}}function normalizeContentlessToolResult(value){return value===null||typeof value!="object"||Array.isArray(value)||value.content!==void 0||TOOL_RESULT_FOREIGN_FAMILY_KEYS.some(key=>key in value)?value:{...value,content:[]}}function build$1(){let JSONValueSchema$1=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema$1),array(JSONValueSchema$1)])),JSONObjectSchema$1=record(string2(),JSONValueSchema$1),ProgressTokenSchema$1=union([string2(),number2().int()]),CursorSchema$1=string2(),TaskMetadataSchema$1=object({ttl:number2().optional()}),RelatedTaskMetadataSchema$1=object({taskId:string2()}),RequestMetaSchema$1=looseObject({progressToken:ProgressTokenSchema$1.optional(),"io.modelcontextprotocol/related-task":RelatedTaskMetadataSchema$1.optional()}),BaseRequestParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),TaskAugmentedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({task:TaskMetadataSchema$1.optional()}),RequestSchema$1=object({method:string2(),params:BaseRequestParamsSchema$1.loose().optional()}),NotificationsParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),NotificationSchema$1=object({method:string2(),params:NotificationsParamsSchema$1.loose().optional()}),ResultSchema$1=looseObject({_meta:RequestMetaSchema$1.optional()}),RequestIdSchema$1=union([string2(),number2().int()]),EmptyResultSchema$1=ResultSchema$1.strict(),CancelledNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({requestId:RequestIdSchema$1.optional(),reason:string2().optional()}),CancelledNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema$1}),IconSchema$1=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema$1=object({icons:array(IconSchema$1).optional()}),BaseMetadataSchema$1=object({name:string2(),title:string2().optional()}),ImplementationSchema$1=BaseMetadataSchema$1.extend({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema2=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema$1),ElicitationCapabilitySchema2=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema2.optional(),url:JSONObjectSchema$1.optional()}),JSONObjectSchema$1.optional())),ClientTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema$1.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema$1.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema$1.optional()}).optional()}).optional()}),ClientCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),sampling:object({context:JSONObjectSchema$1.optional(),tools:JSONObjectSchema$1.optional()}).optional(),elicitation:ElicitationCapabilitySchema2.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),InitializeRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema$1,clientInfo:ImplementationSchema$1}),InitializeRequestSchema$1=RequestSchema$1.extend({method:literal("initialize"),params:InitializeRequestParamsSchema$1}),ServerCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),logging:JSONObjectSchema$1.optional(),completions:JSONObjectSchema$1.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),InitializeResultSchema$1=ResultSchema$1.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema$1,serverInfo:ImplementationSchema$1,instructions:string2().optional()}),InitializedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema$1.optional()}),PingRequestSchema$1=RequestSchema$1.extend({method:literal("ping"),params:BaseRequestParamsSchema$1.optional()}),ProgressSchema$1=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema$1=object({...NotificationsParamsSchema$1.shape,...ProgressSchema$1.shape,progressToken:ProgressTokenSchema$1}),ProgressNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema$1}),PaginatedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({cursor:CursorSchema$1.optional()}),PaginatedRequestSchema$1=RequestSchema$1.extend({params:PaginatedRequestParamsSchema$1.optional()}),PaginatedResultSchema$1=ResultSchema$1.extend({nextCursor:CursorSchema$1.optional()}),ResourceContentsSchema$1=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema$1=ResourceContentsSchema$1.extend({text:string2()}),Base64Schema2=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema$1=ResourceContentsSchema$1.extend({blob:Base64Schema2}),RoleSchema$1=_enum(["user","assistant"]),AnnotationsSchema$1=object({audience:array(RoleSchema$1).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("resources/list")}),ListResourcesResultSchema$1=PaginatedResultSchema$1.extend({resources:array(ResourceSchema$1)}),ListResourceTemplatesRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema$1=PaginatedResultSchema$1.extend({resourceTemplates:array(ResourceTemplateSchema$1)}),ResourceRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({uri:string2()}),ReadResourceRequestParamsSchema$1=ResourceRequestParamsSchema$1,ReadResourceRequestSchema$1=RequestSchema$1.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema$1}),ReadResourceResultSchema$1=ResultSchema$1.extend({contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),ResourceListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema$1.optional()}),SubscribeRequestParamsSchema$1=ResourceRequestParamsSchema$1,SubscribeRequestSchema$1=RequestSchema$1.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema$1}),UnsubscribeRequestParamsSchema$1=ResourceRequestParamsSchema$1,UnsubscribeRequestSchema$1=RequestSchema$1.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema$1}),ResourceUpdatedNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({uri:string2()}),ResourceUpdatedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema$1}),PromptArgumentSchema$1=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema$1)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("prompts/list")}),ListPromptsResultSchema$1=PaginatedResultSchema$1.extend({prompts:array(PromptSchema$1)}),GetPromptRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({name:string2(),arguments:record(string2(),string2()).optional()}),GetPromptRequestSchema$1=RequestSchema$1.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema$1}),TextContentSchema$1=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema$1=object({type:literal("image"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema$1=object({type:literal("audio"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema$1=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema$1=object({type:literal("resource"),resource:union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema$1=ResourceSchema$1.extend({type:literal("resource_link")}),ContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ResourceLinkSchema$1,EmbeddedResourceSchema$1]),PromptMessageSchema$1=object({role:RoleSchema$1,content:ContentBlockSchema$1}),GetPromptResultSchema$1=ResultSchema$1.extend({description:string2().optional(),messages:array(PromptMessageSchema$1)}),PromptListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema$1.optional()}),ToolAnnotationsSchema$1=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolExecutionSchema$1=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:string2().optional(),inputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema$1).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema$1).optional(),required:array(string2()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema$1.optional(),execution:ToolExecutionSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ListToolsRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("tools/list")}),ListToolsResultSchema$1=PaginatedResultSchema$1.extend({tools:array(ToolSchema$1)}),CallToolResultSchema$1=ResultSchema$1.extend({content:array(ContentBlockSchema$1),structuredContent:record(string2(),unknown()).optional(),isError:boolean2().optional()}),CallToolRequestParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({name:string2(),arguments:record(string2(),unknown()).optional()}),CallToolRequestSchema$1=RequestSchema$1.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema$1}),ToolListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema$1.optional()}),LoggingLevelSchema$1=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({level:LoggingLevelSchema$1}),SetLevelRequestSchema$1=RequestSchema$1.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema$1}),LoggingMessageNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({level:LoggingLevelSchema$1,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema$1}),ModelHintSchema$1=object({name:string2().optional()}),ModelPreferencesSchema$1=object({hints:array(ModelHintSchema$1).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema$1=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema$1=object({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema$1),structuredContent:object({}).loose().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingContentSchema$1=discriminatedUnion("type",[TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1]),SamplingMessageContentBlockSchema$1=discriminatedUnion("type",[TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ToolUseContentSchema$1,ToolResultContentSchema$1]),SamplingMessageSchema$1=object({role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)]),_meta:record(string2(),unknown()).optional()}),CreateMessageRequestParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({messages:array(SamplingMessageSchema$1),modelPreferences:ModelPreferencesSchema$1.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema$1.optional(),tools:array(ToolSchema$1).optional(),toolChoice:ToolChoiceSchema$1.optional()}),CreateMessageRequestSchema$1=RequestSchema$1.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema$1}),CreateMessageResultSchema$1=ResultSchema$1.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema$1,content:SamplingContentSchema$1}),CreateMessageResultWithToolsSchema$1=ResultSchema$1.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)])}),BooleanSchemaSchema$1=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema$1=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema$1=union([UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema$1]),UntitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema$1=union([UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema$1]),EnumSchemaSchema$1=union([LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema$1]),PrimitiveSchemaDefinitionSchema$1=union([EnumSchemaSchema$1,BooleanSchemaSchema$1,StringSchemaSchema$1,NumberSchemaSchema$1]),ElicitRequestFormParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema$1),required:array(string2()).optional()}).catchall(unknown())}),ElicitRequestURLParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()}),ElicitRequestParamsSchema$1=union([ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema$1]),ElicitRequestSchema$1=RequestSchema$1.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema$1}),ElicitationCompleteNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({elicitationId:string2()}),ElicitationCompleteNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema$1}),ElicitResultSchema$1=ResultSchema$1.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional())}),ResourceTemplateReferenceSchema$1=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema$1=object({type:literal("ref/prompt"),name:string2()}),CompleteRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({ref:union([PromptReferenceSchema$1,ResourceTemplateReferenceSchema$1]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()}),CompleteRequestSchema$1=RequestSchema$1.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema$1}),CompleteResultSchema$1=ResultSchema$1.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})}),RootSchema$1=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),ListRootsRequestSchema$1=RequestSchema$1.extend({method:literal("roots/list"),params:BaseRequestParamsSchema$1.optional()}),ListRootsResultSchema$1=ResultSchema$1.extend({roots:array(RootSchema$1)}),RootsListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema$1.optional()}),TaskCreationParamsSchema$1=looseObject({ttl:number2().optional(),pollInterval:number2().optional()}),TaskStatusSchema$1=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema$1=object({taskId:string2(),status:TaskStatusSchema$1,ttl:union([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())}),CreateTaskResultSchema$1=ResultSchema$1.extend({task:TaskSchema$1}),TaskStatusNotificationParamsSchema$1=NotificationsParamsSchema$1.merge(TaskSchema$1),TaskStatusNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema$1}),GetTaskRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})}),GetTaskResultSchema$1=ResultSchema$1.merge(TaskSchema$1),GetTaskPayloadRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})}),GetTaskPayloadResultSchema$1=ResultSchema$1.loose(),ListTasksRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("tasks/list")}),ListTasksResultSchema$1=PaginatedResultSchema$1.extend({tasks:array(TaskSchema$1)}),CancelTaskRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})});return{JSONValueSchema:JSONValueSchema$1,JSONObjectSchema:JSONObjectSchema$1,ProgressTokenSchema:ProgressTokenSchema$1,CursorSchema:CursorSchema$1,TaskMetadataSchema:TaskMetadataSchema$1,RelatedTaskMetadataSchema:RelatedTaskMetadataSchema$1,RequestMetaSchema:RequestMetaSchema$1,BaseRequestParamsSchema:BaseRequestParamsSchema$1,TaskAugmentedRequestParamsSchema:TaskAugmentedRequestParamsSchema$1,RequestSchema:RequestSchema$1,NotificationsParamsSchema:NotificationsParamsSchema$1,NotificationSchema:NotificationSchema$1,ResultSchema:ResultSchema$1,RequestIdSchema:RequestIdSchema$1,EmptyResultSchema:EmptyResultSchema$1,CancelledNotificationParamsSchema:CancelledNotificationParamsSchema$1,CancelledNotificationSchema:CancelledNotificationSchema$1,IconSchema:IconSchema$1,IconsSchema:IconsSchema$1,BaseMetadataSchema:BaseMetadataSchema$1,ImplementationSchema:ImplementationSchema$1,ClientTasksCapabilitySchema:ClientTasksCapabilitySchema$1,ServerTasksCapabilitySchema:ServerTasksCapabilitySchema$1,ClientCapabilitiesSchema:ClientCapabilitiesSchema$1,InitializeRequestParamsSchema:InitializeRequestParamsSchema$1,InitializeRequestSchema:InitializeRequestSchema$1,ServerCapabilitiesSchema:ServerCapabilitiesSchema$1,InitializeResultSchema:InitializeResultSchema$1,InitializedNotificationSchema:InitializedNotificationSchema$1,PingRequestSchema:PingRequestSchema$1,ProgressSchema:ProgressSchema$1,ProgressNotificationParamsSchema:ProgressNotificationParamsSchema$1,ProgressNotificationSchema:ProgressNotificationSchema$1,PaginatedRequestParamsSchema:PaginatedRequestParamsSchema$1,PaginatedRequestSchema:PaginatedRequestSchema$1,PaginatedResultSchema:PaginatedResultSchema$1,ResourceContentsSchema:ResourceContentsSchema$1,TextResourceContentsSchema:TextResourceContentsSchema$1,BlobResourceContentsSchema:BlobResourceContentsSchema$1,RoleSchema:RoleSchema$1,AnnotationsSchema:AnnotationsSchema$1,ResourceSchema:ResourceSchema$1,ResourceTemplateSchema:ResourceTemplateSchema$1,ListResourcesRequestSchema:ListResourcesRequestSchema$1,ListResourcesResultSchema:ListResourcesResultSchema$1,ListResourceTemplatesRequestSchema:ListResourceTemplatesRequestSchema$1,ListResourceTemplatesResultSchema:ListResourceTemplatesResultSchema$1,ResourceRequestParamsSchema:ResourceRequestParamsSchema$1,ReadResourceRequestParamsSchema:ReadResourceRequestParamsSchema$1,ReadResourceRequestSchema:ReadResourceRequestSchema$1,ReadResourceResultSchema:ReadResourceResultSchema$1,ResourceListChangedNotificationSchema:ResourceListChangedNotificationSchema$1,SubscribeRequestParamsSchema:SubscribeRequestParamsSchema$1,SubscribeRequestSchema:SubscribeRequestSchema$1,UnsubscribeRequestParamsSchema:UnsubscribeRequestParamsSchema$1,UnsubscribeRequestSchema:UnsubscribeRequestSchema$1,ResourceUpdatedNotificationParamsSchema:ResourceUpdatedNotificationParamsSchema$1,ResourceUpdatedNotificationSchema:ResourceUpdatedNotificationSchema$1,PromptArgumentSchema:PromptArgumentSchema$1,PromptSchema:PromptSchema$1,ListPromptsRequestSchema:ListPromptsRequestSchema$1,ListPromptsResultSchema:ListPromptsResultSchema$1,GetPromptRequestParamsSchema:GetPromptRequestParamsSchema$1,GetPromptRequestSchema:GetPromptRequestSchema$1,TextContentSchema:TextContentSchema$1,ImageContentSchema:ImageContentSchema$1,AudioContentSchema:AudioContentSchema$1,ToolUseContentSchema:ToolUseContentSchema$1,EmbeddedResourceSchema:EmbeddedResourceSchema$1,ResourceLinkSchema:ResourceLinkSchema$1,ContentBlockSchema:ContentBlockSchema$1,PromptMessageSchema:PromptMessageSchema$1,GetPromptResultSchema:GetPromptResultSchema$1,PromptListChangedNotificationSchema:PromptListChangedNotificationSchema$1,ToolAnnotationsSchema:ToolAnnotationsSchema$1,ToolExecutionSchema:ToolExecutionSchema$1,ToolSchema:ToolSchema$1,ListToolsRequestSchema:ListToolsRequestSchema$1,ListToolsResultSchema:ListToolsResultSchema$1,CallToolResultSchema:CallToolResultSchema$1,CallToolRequestParamsSchema:CallToolRequestParamsSchema$1,CallToolRequestSchema:CallToolRequestSchema$1,ToolListChangedNotificationSchema:ToolListChangedNotificationSchema$1,LoggingLevelSchema:LoggingLevelSchema$1,SetLevelRequestParamsSchema:SetLevelRequestParamsSchema$1,SetLevelRequestSchema:SetLevelRequestSchema$1,LoggingMessageNotificationParamsSchema:LoggingMessageNotificationParamsSchema$1,LoggingMessageNotificationSchema:LoggingMessageNotificationSchema$1,ModelHintSchema:ModelHintSchema$1,ModelPreferencesSchema:ModelPreferencesSchema$1,ToolChoiceSchema:ToolChoiceSchema$1,ToolResultContentSchema:ToolResultContentSchema$1,SamplingContentSchema:SamplingContentSchema$1,SamplingMessageContentBlockSchema:SamplingMessageContentBlockSchema$1,SamplingMessageSchema:SamplingMessageSchema$1,CreateMessageRequestParamsSchema:CreateMessageRequestParamsSchema$1,CreateMessageRequestSchema:CreateMessageRequestSchema$1,CreateMessageResultSchema:CreateMessageResultSchema$1,CreateMessageResultWithToolsSchema:CreateMessageResultWithToolsSchema$1,BooleanSchemaSchema:BooleanSchemaSchema$1,StringSchemaSchema:StringSchemaSchema$1,NumberSchemaSchema:NumberSchemaSchema$1,UntitledSingleSelectEnumSchemaSchema:UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema:TitledSingleSelectEnumSchemaSchema$1,LegacyTitledEnumSchemaSchema:LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema:SingleSelectEnumSchemaSchema$1,UntitledMultiSelectEnumSchemaSchema:UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema:TitledMultiSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema:MultiSelectEnumSchemaSchema$1,EnumSchemaSchema:EnumSchemaSchema$1,PrimitiveSchemaDefinitionSchema:PrimitiveSchemaDefinitionSchema$1,ElicitRequestFormParamsSchema:ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema:ElicitRequestURLParamsSchema$1,ElicitRequestParamsSchema:ElicitRequestParamsSchema$1,ElicitRequestSchema:ElicitRequestSchema$1,ElicitationCompleteNotificationParamsSchema:ElicitationCompleteNotificationParamsSchema$1,ElicitationCompleteNotificationSchema:ElicitationCompleteNotificationSchema$1,ElicitResultSchema:ElicitResultSchema$1,ResourceTemplateReferenceSchema:ResourceTemplateReferenceSchema$1,PromptReferenceSchema:PromptReferenceSchema$1,CompleteRequestParamsSchema:CompleteRequestParamsSchema$1,CompleteRequestSchema:CompleteRequestSchema$1,CompleteResultSchema:CompleteResultSchema$1,RootSchema:RootSchema$1,ListRootsRequestSchema:ListRootsRequestSchema$1,ListRootsResultSchema:ListRootsResultSchema$1,RootsListChangedNotificationSchema:RootsListChangedNotificationSchema$1,TaskCreationParamsSchema:TaskCreationParamsSchema$1,TaskStatusSchema:TaskStatusSchema$1,TaskSchema:TaskSchema$1,CreateTaskResultSchema:CreateTaskResultSchema$1,TaskStatusNotificationParamsSchema:TaskStatusNotificationParamsSchema$1,TaskStatusNotificationSchema:TaskStatusNotificationSchema$1,GetTaskRequestSchema:GetTaskRequestSchema$1,GetTaskResultSchema:GetTaskResultSchema$1,GetTaskPayloadRequestSchema:GetTaskPayloadRequestSchema$1,GetTaskPayloadResultSchema:GetTaskPayloadResultSchema$1,ListTasksRequestSchema:ListTasksRequestSchema$1,ListTasksResultSchema:ListTasksResultSchema$1,CancelTaskRequestSchema:CancelTaskRequestSchema$1,CancelTaskResultSchema:ResultSchema$1.merge(TaskSchema$1),ClientRequestSchema:union([PingRequestSchema$1,InitializeRequestSchema$1,CompleteRequestSchema$1,SetLevelRequestSchema$1,GetPromptRequestSchema$1,ListPromptsRequestSchema$1,ListResourcesRequestSchema$1,ListResourceTemplatesRequestSchema$1,ReadResourceRequestSchema$1,SubscribeRequestSchema$1,UnsubscribeRequestSchema$1,CallToolRequestSchema$1,ListToolsRequestSchema$1,GetTaskRequestSchema$1,GetTaskPayloadRequestSchema$1,ListTasksRequestSchema$1,CancelTaskRequestSchema$1]),ClientNotificationSchema:union([CancelledNotificationSchema$1,ProgressNotificationSchema$1,InitializedNotificationSchema$1,RootsListChangedNotificationSchema$1,TaskStatusNotificationSchema$1]),ClientResultSchema:union([EmptyResultSchema$1,CreateMessageResultSchema$1,CreateMessageResultWithToolsSchema$1,ElicitResultSchema$1,ListRootsResultSchema$1,GetTaskResultSchema$1,ListTasksResultSchema$1,CreateTaskResultSchema$1]),ServerRequestSchema:union([PingRequestSchema$1,CreateMessageRequestSchema$1,ElicitRequestSchema$1,ListRootsRequestSchema$1,GetTaskRequestSchema$1,GetTaskPayloadRequestSchema$1,ListTasksRequestSchema$1,CancelTaskRequestSchema$1]),ServerNotificationSchema:union([CancelledNotificationSchema$1,ProgressNotificationSchema$1,LoggingMessageNotificationSchema$1,ResourceUpdatedNotificationSchema$1,ResourceListChangedNotificationSchema$1,ToolListChangedNotificationSchema$1,PromptListChangedNotificationSchema$1,TaskStatusNotificationSchema$1,ElicitationCompleteNotificationSchema$1]),ServerResultSchema:union([EmptyResultSchema$1,InitializeResultSchema$1,CompleteResultSchema$1,GetPromptResultSchema$1,ListPromptsResultSchema$1,ListResourcesResultSchema$1,ListResourceTemplatesResultSchema$1,ReadResourceResultSchema$1,CallToolResultSchema$1,ListToolsResultSchema$1,GetTaskResultSchema$1,ListTasksResultSchema$1,CreateTaskResultSchema$1]),CallToolResultWireSchema:unknown().superRefine((value,ctx)=>{if(!(typeof value!="object"||value===null||Array.isArray(value)||value.content!==void 0)){for(let key of TOOL_RESULT_FOREIGN_FAMILY_KEYS)if(key in value){ctx.addIssue({code:"custom",message:`content is required when the body carries '${key}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1)}}function buildSchemas2025(){return memo$1??=build$1()}function isNonObjectJsonSchemaRoot(json){return json.type!=="object"}function establishesNewBase(id){return id!==void 0&&!(typeof id=="string"&&id.startsWith("#"))}function wrapOutputSchemaForLegacy(natural){let $schema=typeof natural.$schema=="string"?natural.$schema:void 0;if(establishesNewBase(natural.$id))return{...$schema!==void 0&&{$schema},type:"object",properties:{result:natural},required:["result"]};let convertRecursiveRefs=declares2019Dialect(natural.$schema)&&natural.$recursiveAnchor!==!0,rewriteRefs=(node2,parentIsNameMap)=>{if(Array.isArray(node2))return node2.map(item=>rewriteRefs(item,!1));if(node2===null||typeof node2!="object"||!parentIsNameMap&&establishesNewBase(node2.$id))return node2;let out={},convertedRecursion=!1;for(let[k,v]of Object.entries(node2))parentIsNameMap?out[k]=rewriteRefs(v,!1):(k==="$ref"||k==="$dynamicRef")&&typeof v=="string"?out[k]=v==="#"?"#/properties/result":v.startsWith("#/")?`#/properties/result${v.slice(1)}`:v:k==="$recursiveRef"&&v==="#"&&convertRecursiveRefs?convertedRecursion=!0:REF_REWRITE_DATA_POSITION_KEYS.has(k)?out[k]=v:REF_REWRITE_NAME_MAP_KEYS.has(k)?out[k]=rewriteRefs(v,!0):out[k]=rewriteRefs(v,!1);return convertedRecursion&&("$ref"in out?out.allOf=[...Array.isArray(out.allOf)?out.allOf:[],{$ref:"#/properties/result"}]:out.$ref="#/properties/result"),out};return{...$schema!==void 0&&{$schema},type:"object",properties:{result:rewriteRefs(natural,!1)},required:["result"]}}function registryMaps(){if(maps$1)return maps$1;let s=buildSchemas2025();return maps$1={requestSchemas:{ping:s.PingRequestSchema,initialize:s.InitializeRequestSchema,"completion/complete":s.CompleteRequestSchema,"logging/setLevel":s.SetLevelRequestSchema,"prompts/get":s.GetPromptRequestSchema,"prompts/list":s.ListPromptsRequestSchema,"resources/list":s.ListResourcesRequestSchema,"resources/templates/list":s.ListResourceTemplatesRequestSchema,"resources/read":s.ReadResourceRequestSchema,"resources/subscribe":s.SubscribeRequestSchema,"resources/unsubscribe":s.UnsubscribeRequestSchema,"tools/call":s.CallToolRequestSchema,"tools/list":s.ListToolsRequestSchema,"tasks/get":s.GetTaskRequestSchema,"tasks/result":s.GetTaskPayloadRequestSchema,"tasks/list":s.ListTasksRequestSchema,"tasks/cancel":s.CancelTaskRequestSchema,"sampling/createMessage":s.CreateMessageRequestSchema,"elicitation/create":s.ElicitRequestSchema,"roots/list":s.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":s.CancelledNotificationSchema,"notifications/progress":s.ProgressNotificationSchema,"notifications/initialized":s.InitializedNotificationSchema,"notifications/roots/list_changed":s.RootsListChangedNotificationSchema,"notifications/tasks/status":s.TaskStatusNotificationSchema,"notifications/message":s.LoggingMessageNotificationSchema,"notifications/resources/updated":s.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":s.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":s.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":s.PromptListChangedNotificationSchema,"notifications/elicitation/complete":s.ElicitationCompleteNotificationSchema},resultSchemas:{ping:s.EmptyResultSchema,initialize:s.InitializeResultSchema,"completion/complete":s.CompleteResultSchema,"logging/setLevel":s.EmptyResultSchema,"prompts/get":s.GetPromptResultSchema,"prompts/list":s.ListPromptsResultSchema,"resources/list":s.ListResourcesResultSchema,"resources/templates/list":s.ListResourceTemplatesResultSchema,"resources/read":s.ReadResourceResultSchema,"resources/subscribe":s.EmptyResultSchema,"resources/unsubscribe":s.EmptyResultSchema,"tools/call":s.CallToolResultWireSchema,"tools/list":s.ListToolsResultSchema,"sampling/createMessage":s.CreateMessageResultWithToolsSchema,"elicitation/create":s.ElicitResultSchema,"roots/list":s.ListRootsResultSchema}},maps$1}function hasRequestMethod2025(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys$1,method)}function hasNotificationMethod2025(method){return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1,method)}function hasResultMethod(method){return Object.prototype.hasOwnProperty.call(resultMethodKeys,method)}function getResultSchema(method){return hasResultMethod(method)?registryMaps().resultSchemas[method]:void 0}function getRequestSchema(method){return hasRequestMethod2025(method)?registryMaps().requestSchemas[method]:void 0}function getNotificationSchema(method){return hasNotificationMethod2025(method)?registryMaps().notificationSchemas[method]:void 0}function isPlainObject$6(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function triState$1(schema2,raw2){if(schema2===void 0)return{ok:!1,reason:"not-in-era"};let parsed=schema2.safeParse(raw2);return parsed.success?{ok:!0,value:parsed.data}:{ok:!1,reason:"invalid",message:String(parsed.error)}}function toolNeedsLegacyWrap(t){return isPlainObject$6(t)&&isPlainObject$6(t.outputSchema)&&isNonObjectJsonSchemaRoot(t.outputSchema)}function build(){let JSONValueSchema$1=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema$1),array(JSONValueSchema$1)])),JSONObjectSchema$1=record(string2(),JSONValueSchema$1),ProgressTokenSchema$1=union([string2(),number2().int()]),CursorSchema$1=string2(),RequestIdSchema$1=union([string2(),number2().int()]),RoleSchema$1=_enum(["user","assistant"]),LoggingLevelSchema$1=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Base64Schema2=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),TaskMetadataSchema$1=object({ttl:number2().optional()}),RelatedTaskMetadataSchema$1=object({taskId:string2()}),RequestMetaSchema$1=looseObject({progressToken:ProgressTokenSchema$1.optional(),"io.modelcontextprotocol/related-task":RelatedTaskMetadataSchema$1.optional()}),BaseRequestParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),TaskAugmentedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({task:TaskMetadataSchema$1.optional()}),NotificationsParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),NotificationSchema$1=object({method:string2(),params:NotificationsParamsSchema$1.loose().optional()}),IconSchema$1=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema$1=object({icons:array(IconSchema$1).optional()}),BaseMetadataSchema$1=object({name:string2(),title:string2().optional()}),ImplementationSchema$1=BaseMetadataSchema$1.extend({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema2=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema$1),ElicitationCapabilitySchema2=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema2.optional(),url:JSONObjectSchema$1.optional()}),JSONObjectSchema$1.optional())),ClientTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema$1.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema$1.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema$1.optional()}).optional()}).optional()}),ClientCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),sampling:object({context:JSONObjectSchema$1.optional(),tools:JSONObjectSchema$1.optional()}).optional(),elicitation:ElicitationCapabilitySchema2.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),ServerCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),logging:JSONObjectSchema$1.optional(),completions:JSONObjectSchema$1.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),ProgressSchema$1=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema$1=object({...NotificationsParamsSchema$1.shape,...ProgressSchema$1.shape,progressToken:ProgressTokenSchema$1}),ProgressNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema$1}),LoggingMessageNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({level:LoggingLevelSchema$1,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema$1}),ResourceContentsSchema$1=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema$1=ResourceContentsSchema$1.extend({text:string2()}),BlobResourceContentsSchema$1=ResourceContentsSchema$1.extend({blob:Base64Schema2}),AnnotationsSchema$1=object({audience:array(RoleSchema$1).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema$1.optional()}),ResourceUpdatedNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({uri:string2()}),ResourceUpdatedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema$1}),PromptArgumentSchema$1=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema$1)),_meta:optional(looseObject({}))}),PromptListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema$1.optional()}),TextContentSchema$1=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema$1=object({type:literal("image"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema$1=object({type:literal("audio"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema$1=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema$1=object({type:literal("resource"),resource:union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema$1=ResourceSchema$1.extend({type:literal("resource_link")}),ContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ResourceLinkSchema$1,EmbeddedResourceSchema$1]),PromptMessageSchema$1=object({role:RoleSchema$1,content:ContentBlockSchema$1}),ToolAnnotationsSchema$1=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema$1.optional()}),ModelHintSchema$1=object({name:string2().optional()}),ModelPreferencesSchema$1=object({hints:array(ModelHintSchema$1).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema$1=object({mode:_enum(["auto","required","none"]).optional()}),BooleanSchemaSchema$1=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema$1=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema$1=union([UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema$1]),UntitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema$1=union([UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema$1]),EnumSchemaSchema$1=union([LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema$1]),PrimitiveSchemaDefinitionSchema$1=union([EnumSchemaSchema$1,BooleanSchemaSchema$1,StringSchemaSchema$1,NumberSchemaSchema$1]),ElicitRequestFormParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema$1),required:array(string2()).optional()}).catchall(unknown())}),ResourceTemplateReferenceSchema$1=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema$1=object({type:literal("ref/prompt"),name:string2()}),RootSchema$1=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),sharedClientCapabilityShape=ClientCapabilitiesSchema$1.shape,ClientCapabilities2026Schema=object({experimental:sharedClientCapabilityShape.experimental,sampling:sharedClientCapabilityShape.sampling,elicitation:sharedClientCapabilityShape.elicitation,roots:sharedClientCapabilityShape.roots,extensions:sharedClientCapabilityShape.extensions}),sharedServerCapabilityShape=ServerCapabilitiesSchema$1.shape,ServerCapabilities2026Schema=object({experimental:sharedServerCapabilityShape.experimental,logging:sharedServerCapabilityShape.logging,completions:sharedServerCapabilityShape.completions,prompts:sharedServerCapabilityShape.prompts,resources:sharedServerCapabilityShape.resources,tools:sharedServerCapabilityShape.tools,extensions:sharedServerCapabilityShape.extensions}),RequestMetaEnvelopeSchema=looseObject({progressToken:ProgressTokenSchema$1.optional(),[PROTOCOL_VERSION_META_KEY]:string2(),[CLIENT_INFO_META_KEY]:ImplementationSchema$1.optional(),[CLIENT_CAPABILITIES_META_KEY]:ClientCapabilities2026Schema,[LOG_LEVEL_META_KEY]:LoggingLevelSchema$1.optional()}),ToolSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:string2().optional(),inputSchema:looseObject({$schema:string2().optional(),type:literal("object")}),outputSchema:looseObject({$schema:string2().optional()}).optional(),annotations:ToolAnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolResultContentSchema$1=object({type:literal("tool_result"),toolUseId:string2(),content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingMessageContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ToolUseContentSchema$1,ToolResultContentSchema$1]),SamplingMessageSchema$1=object({role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)]),_meta:record(string2(),unknown()).optional()}),ResultTypeSchema=string2(),ResultMetaSchema=looseObject({[SERVER_INFO_META_KEY]:ImplementationSchema$1.optional().catch(void 0)}),wireMeta=ResultMetaSchema.optional();function wireResult(shape){return looseObject({_meta:wireMeta,resultType:ResultTypeSchema.default("complete"),...shape})}let ResultSchema$1=wireResult({}),PaginatedResultSchema$1=wireResult({nextCursor:CursorSchema$1.optional()}),CallToolResultSchema$1=wireResult({content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional()}),ListToolsResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),tools:array(ToolSchema$1),nextCursor:CursorSchema$1.optional()}),ListPromptsResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),prompts:array(PromptSchema$1),nextCursor:CursorSchema$1.optional()}),GetPromptResultSchema$1=wireResult({description:string2().optional(),messages:array(PromptMessageSchema$1)}),ListResourcesResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resources:array(ResourceSchema$1),nextCursor:CursorSchema$1.optional()}),ListResourceTemplatesResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resourceTemplates:array(ResourceTemplateSchema$1),nextCursor:CursorSchema$1.optional()}),ReadResourceResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),CompleteResultSchema$1=wireResult({completion:object({values:array(string2()).max(100),total:number2().int().optional(),hasMore:boolean2().optional()}).loose()}),CacheableResultSchema=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"])}),DiscoverResultSchema$1=wireResult({ttlMs:number2().int().min(0).catch(0),cacheScope:_enum(["public","private"]).catch("private"),supportedVersions:array(string2()),capabilities:ServerCapabilities2026Schema,instructions:string2().optional()}),CreateMessageRequestParamsSchema$1=object({messages:array(SamplingMessageSchema$1),modelPreferences:ModelPreferencesSchema$1.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema$1.optional(),tools:array(ToolSchema$1).optional(),toolChoice:ToolChoiceSchema$1.optional()}),CreateMessageRequestSchema$1=object({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema$1}),ListRootsRequestSchema$1=object({method:literal("roots/list"),params:object({_meta:record(string2(),unknown()).optional()}).optional()}),CreateMessageResultSchema$1=object({...SamplingMessageSchema$1.shape,model:string2(),stopReason:string2().optional()}),ListRootsResultSchema$1=object({roots:array(RootSchema$1)}),ElicitResultSchema$1=object({action:_enum(["accept","decline","cancel"]),content:record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional()}),ElicitRequestURLParamsSchema$1=object({mode:literal("url"),message:string2(),url:string2().url()}),ElicitRequestParamsSchema$1=union([ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema$1]),ElicitRequestSchema$1=object({method:literal("elicitation/create"),params:ElicitRequestParamsSchema$1}),InputRequestSchema=union([CreateMessageRequestSchema$1,ListRootsRequestSchema$1,ElicitRequestSchema$1]),InputResponseSchema=union([CreateMessageResultSchema$1,ListRootsResultSchema$1,ElicitResultSchema$1]),InputRequestsSchema=record(string2(),InputRequestSchema),InputResponsesSchema=record(string2(),InputResponseSchema),InputRequiredResultSchema=wireResult({inputRequests:InputRequestsSchema.optional(),requestState:string2().optional()}),retryParamsShape={inputResponses:InputResponsesSchema.optional(),requestState:string2().optional()},InputResponseRequestParamsSchema=object({_meta:RequestMetaEnvelopeSchema,...retryParamsShape}),DispatchRequestMetaSchema=looseObject({progressToken:ProgressTokenSchema$1.optional()});function wireRequest(method,paramsShape){return object({method:literal(method),params:object({_meta:RequestMetaEnvelopeSchema,...paramsShape})})}function dispatchRequest(method,paramsShape){return object({method:literal(method),params:object({_meta:DispatchRequestMetaSchema.optional(),...paramsShape}).optional()})}let callToolParamsShape={name:string2(),arguments:record(string2(),unknown()).optional(),...retryParamsShape},paginatedParamsShape={cursor:CursorSchema$1.optional()},CallToolRequestSchema$1=wireRequest("tools/call",callToolParamsShape),ListToolsRequestSchema$1=wireRequest("tools/list",paginatedParamsShape),ListPromptsRequestSchema$1=wireRequest("prompts/list",paginatedParamsShape),GetPromptRequestSchema$1=wireRequest("prompts/get",{name:string2(),arguments:record(string2(),string2()).optional(),...retryParamsShape}),ListResourcesRequestSchema$1=wireRequest("resources/list",paginatedParamsShape),ListResourceTemplatesRequestSchema$1=wireRequest("resources/templates/list",paginatedParamsShape),ReadResourceRequestSchema$1=wireRequest("resources/read",{uri:string2(),...retryParamsShape}),completeParamsShape={ref:union([PromptReferenceSchema$1,ResourceTemplateReferenceSchema$1]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()},CompleteRequestSchema$1=wireRequest("completion/complete",completeParamsShape),DiscoverRequestSchema$1=wireRequest("server/discover",{}),SubscriptionFilterSchema$1=object({toolsListChanged:boolean2().optional(),promptsListChanged:boolean2().optional(),resourcesListChanged:boolean2().optional(),resourceSubscriptions:array(string2()).optional()}),subscriptionsListenParamsShape={notifications:SubscriptionFilterSchema$1},SubscriptionsListenRequestSchema$1=wireRequest("subscriptions/listen",subscriptionsListenParamsShape),SubscriptionsListenResultMetaSchema$1=ResultMetaSchema.extend({"io.modelcontextprotocol/subscriptionId":RequestIdSchema$1}),SubscriptionsListenResultSchema$1=looseObject({_meta:SubscriptionsListenResultMetaSchema$1,resultType:ResultTypeSchema.default("complete")}),dispatchRequestSchemas={"tools/call":dispatchRequest("tools/call",callToolParamsShape),"tools/list":dispatchRequest("tools/list",paginatedParamsShape),"prompts/get":dispatchRequest("prompts/get",{name:string2(),arguments:record(string2(),string2()).optional()}),"prompts/list":dispatchRequest("prompts/list",paginatedParamsShape),"resources/list":dispatchRequest("resources/list",paginatedParamsShape),"resources/templates/list":dispatchRequest("resources/templates/list",paginatedParamsShape),"resources/read":dispatchRequest("resources/read",{uri:string2()}),"completion/complete":dispatchRequest("completion/complete",completeParamsShape),"server/discover":dispatchRequest("server/discover",{}),"subscriptions/listen":dispatchRequest("subscriptions/listen",subscriptionsListenParamsShape)};function liftedResult(shape){return looseObject({_meta:wireMeta,...shape})}let dispatchResultSchemas={"tools/call":liftedResult({content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional()}),"tools/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),tools:array(ToolSchema$1),nextCursor:CursorSchema$1.optional()}),"prompts/get":liftedResult({description:string2().optional(),messages:array(PromptMessageSchema$1)}),"prompts/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),prompts:array(PromptSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resources:array(ResourceSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/templates/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resourceTemplates:array(ResourceTemplateSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/read":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),"completion/complete":liftedResult({completion:object({values:array(string2()).max(100),total:number2().int().optional(),hasMore:boolean2().optional()}).loose()}),"server/discover":liftedResult({ttlMs:number2().int().min(0).catch(0),cacheScope:_enum(["public","private"]).catch("private"),supportedVersions:array(string2()),capabilities:ServerCapabilities2026Schema,instructions:string2().optional()}),"subscriptions/listen":liftedResult({})},NotificationMetaSchema=looseObject({"io.modelcontextprotocol/subscriptionId":RequestIdSchema$1.optional()}),SubscriptionsAcknowledgedNotificationSchema$1=object({method:literal("notifications/subscriptions/acknowledged"),params:object({_meta:NotificationMetaSchema.optional(),notifications:SubscriptionFilterSchema$1})}),CancelledNotificationParamsSchema$1=object({_meta:NotificationMetaSchema.optional(),requestId:RequestIdSchema$1,reason:string2().optional()}),CancelledNotificationSchema$1=object({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema$1}),notificationSchemas2026={"notifications/cancelled":CancelledNotificationSchema$1,"notifications/progress":ProgressNotificationSchema$1,"notifications/message":LoggingMessageNotificationSchema$1,"notifications/resources/updated":ResourceUpdatedNotificationSchema$1,"notifications/resources/list_changed":ResourceListChangedNotificationSchema$1,"notifications/tools/list_changed":ToolListChangedNotificationSchema$1,"notifications/prompts/list_changed":PromptListChangedNotificationSchema$1,"notifications/subscriptions/acknowledged":SubscriptionsAcknowledgedNotificationSchema$1},wireResultResponse=result=>object({jsonrpc:literal("2.0"),id:union([string2(),number2().int()]),result}).strict();return{JSONValueSchema:JSONValueSchema$1,JSONObjectSchema:JSONObjectSchema$1,ProgressTokenSchema:ProgressTokenSchema$1,CursorSchema:CursorSchema$1,RequestIdSchema:RequestIdSchema$1,RoleSchema:RoleSchema$1,LoggingLevelSchema:LoggingLevelSchema$1,TaskMetadataSchema:TaskMetadataSchema$1,RelatedTaskMetadataSchema:RelatedTaskMetadataSchema$1,RequestMetaSchema:RequestMetaSchema$1,BaseRequestParamsSchema:BaseRequestParamsSchema$1,TaskAugmentedRequestParamsSchema:TaskAugmentedRequestParamsSchema$1,NotificationsParamsSchema:NotificationsParamsSchema$1,NotificationSchema:NotificationSchema$1,IconSchema:IconSchema$1,IconsSchema:IconsSchema$1,BaseMetadataSchema:BaseMetadataSchema$1,ImplementationSchema:ImplementationSchema$1,ClientTasksCapabilitySchema:ClientTasksCapabilitySchema$1,ServerTasksCapabilitySchema:ServerTasksCapabilitySchema$1,ClientCapabilitiesSchema:ClientCapabilitiesSchema$1,ServerCapabilitiesSchema:ServerCapabilitiesSchema$1,ProgressSchema:ProgressSchema$1,ProgressNotificationParamsSchema:ProgressNotificationParamsSchema$1,ProgressNotificationSchema:ProgressNotificationSchema$1,LoggingMessageNotificationParamsSchema:LoggingMessageNotificationParamsSchema$1,LoggingMessageNotificationSchema:LoggingMessageNotificationSchema$1,ResourceContentsSchema:ResourceContentsSchema$1,TextResourceContentsSchema:TextResourceContentsSchema$1,BlobResourceContentsSchema:BlobResourceContentsSchema$1,AnnotationsSchema:AnnotationsSchema$1,ResourceSchema:ResourceSchema$1,ResourceTemplateSchema:ResourceTemplateSchema$1,ResourceListChangedNotificationSchema:ResourceListChangedNotificationSchema$1,ResourceUpdatedNotificationParamsSchema:ResourceUpdatedNotificationParamsSchema$1,ResourceUpdatedNotificationSchema:ResourceUpdatedNotificationSchema$1,PromptArgumentSchema:PromptArgumentSchema$1,PromptSchema:PromptSchema$1,PromptListChangedNotificationSchema:PromptListChangedNotificationSchema$1,TextContentSchema:TextContentSchema$1,ImageContentSchema:ImageContentSchema$1,AudioContentSchema:AudioContentSchema$1,ToolUseContentSchema:ToolUseContentSchema$1,EmbeddedResourceSchema:EmbeddedResourceSchema$1,ResourceLinkSchema:ResourceLinkSchema$1,ContentBlockSchema:ContentBlockSchema$1,PromptMessageSchema:PromptMessageSchema$1,ToolAnnotationsSchema:ToolAnnotationsSchema$1,ToolListChangedNotificationSchema:ToolListChangedNotificationSchema$1,ModelHintSchema:ModelHintSchema$1,ModelPreferencesSchema:ModelPreferencesSchema$1,ToolChoiceSchema:ToolChoiceSchema$1,BooleanSchemaSchema:BooleanSchemaSchema$1,StringSchemaSchema:StringSchemaSchema$1,NumberSchemaSchema:NumberSchemaSchema$1,UntitledSingleSelectEnumSchemaSchema:UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema:TitledSingleSelectEnumSchemaSchema$1,LegacyTitledEnumSchemaSchema:LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema:SingleSelectEnumSchemaSchema$1,UntitledMultiSelectEnumSchemaSchema:UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema:TitledMultiSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema:MultiSelectEnumSchemaSchema$1,EnumSchemaSchema:EnumSchemaSchema$1,PrimitiveSchemaDefinitionSchema:PrimitiveSchemaDefinitionSchema$1,ElicitRequestFormParamsSchema:ElicitRequestFormParamsSchema$1,ResourceTemplateReferenceSchema:ResourceTemplateReferenceSchema$1,PromptReferenceSchema:PromptReferenceSchema$1,RootSchema:RootSchema$1,ClientCapabilities2026Schema,ServerCapabilities2026Schema,RequestMetaEnvelopeSchema,ToolSchema:ToolSchema$1,ToolResultContentSchema:ToolResultContentSchema$1,SamplingMessageContentBlockSchema:SamplingMessageContentBlockSchema$1,SamplingMessageSchema:SamplingMessageSchema$1,ResultTypeSchema,ResultMetaSchema,ResultSchema:ResultSchema$1,PaginatedResultSchema:PaginatedResultSchema$1,CallToolResultSchema:CallToolResultSchema$1,ListToolsResultSchema:ListToolsResultSchema$1,ListPromptsResultSchema:ListPromptsResultSchema$1,GetPromptResultSchema:GetPromptResultSchema$1,ListResourcesResultSchema:ListResourcesResultSchema$1,ListResourceTemplatesResultSchema:ListResourceTemplatesResultSchema$1,ReadResourceResultSchema:ReadResourceResultSchema$1,CompleteResultSchema:CompleteResultSchema$1,CacheableResultSchema,DiscoverResultSchema:DiscoverResultSchema$1,CreateMessageRequestParamsSchema:CreateMessageRequestParamsSchema$1,CreateMessageRequestSchema:CreateMessageRequestSchema$1,ListRootsRequestSchema:ListRootsRequestSchema$1,CreateMessageResultSchema:CreateMessageResultSchema$1,ListRootsResultSchema:ListRootsResultSchema$1,ElicitResultSchema:ElicitResultSchema$1,ElicitRequestURLParamsSchema:ElicitRequestURLParamsSchema$1,ElicitRequestParamsSchema:ElicitRequestParamsSchema$1,ElicitRequestSchema:ElicitRequestSchema$1,InputRequestSchema,InputResponseSchema,InputRequestsSchema,InputResponsesSchema,InputRequiredResultSchema,InputResponseRequestParamsSchema,CallToolRequestSchema:CallToolRequestSchema$1,ListToolsRequestSchema:ListToolsRequestSchema$1,ListPromptsRequestSchema:ListPromptsRequestSchema$1,GetPromptRequestSchema:GetPromptRequestSchema$1,ListResourcesRequestSchema:ListResourcesRequestSchema$1,ListResourceTemplatesRequestSchema:ListResourceTemplatesRequestSchema$1,ReadResourceRequestSchema:ReadResourceRequestSchema$1,CompleteRequestSchema:CompleteRequestSchema$1,DiscoverRequestSchema:DiscoverRequestSchema$1,SubscriptionFilterSchema:SubscriptionFilterSchema$1,SubscriptionsListenRequestSchema:SubscriptionsListenRequestSchema$1,SubscriptionsListenResultMetaSchema:SubscriptionsListenResultMetaSchema$1,SubscriptionsListenResultSchema:SubscriptionsListenResultSchema$1,dispatchRequestSchemas,dispatchResultSchemas,NotificationMetaSchema,SubscriptionsAcknowledgedNotificationSchema:SubscriptionsAcknowledgedNotificationSchema$1,CancelledNotificationParamsSchema:CancelledNotificationParamsSchema$1,CancelledNotificationSchema:CancelledNotificationSchema$1,notificationSchemas2026,JSONRPCResultResponseSchema:wireResultResponse(ResultSchema$1),CallToolResultResponseSchema:wireResultResponse(union([CallToolResultSchema$1,InputRequiredResultSchema])),ListToolsResultResponseSchema:wireResultResponse(ListToolsResultSchema$1),ListPromptsResultResponseSchema:wireResultResponse(ListPromptsResultSchema$1),GetPromptResultResponseSchema:wireResultResponse(union([GetPromptResultSchema$1,InputRequiredResultSchema])),ListResourcesResultResponseSchema:wireResultResponse(ListResourcesResultSchema$1),ListResourceTemplatesResultResponseSchema:wireResultResponse(ListResourceTemplatesResultSchema$1),ReadResourceResultResponseSchema:wireResultResponse(union([ReadResourceResultSchema$1,InputRequiredResultSchema])),CompleteResultResponseSchema:wireResultResponse(CompleteResultSchema$1),DiscoverResultResponseSchema:wireResultResponse(DiscoverResultSchema$1),SubscriptionsListenResultResponseSchema:wireResultResponse(SubscriptionsListenResultSchema$1)}}function buildSchemas2026(){return memo2??=build()}function isCacheableResultMethod(method){return CACHEABLE_RESULT_METHODS.includes(method)}function attachCacheHintFallback(result,hint){if(hint===void 0)return result;let attached=result[RESULT_CACHE_HINT_FALLBACK];if(attached===void 0)return{...result,[RESULT_CACHE_HINT_FALLBACK]:hint};let merged={},ttlMs=attached.ttlMs??hint.ttlMs;ttlMs!==void 0&&(merged.ttlMs=ttlMs);let cacheScope=attached.cacheScope??hint.cacheScope;return cacheScope!==void 0&&(merged.cacheScope=cacheScope),{...result,[RESULT_CACHE_HINT_FALLBACK]:merged}}function cacheHintFallbackOf(result){return result[RESULT_CACHE_HINT_FALLBACK]}function isValidCacheTtlMs(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0}function isValidCacheScope(value){return value==="public"||value==="private"}function assertValidCacheHint(hint,context){if(hint.ttlMs!==void 0&&!isValidCacheTtlMs(hint.ttlMs))throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`);if(hint.cacheScope!==void 0&&!isValidCacheScope(hint.cacheScope))throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`)}function stampResultType(method,result){let provided=result.resultType;if(provided===void 0)return{...result,resultType:"complete"};if(provided==="complete"||EXTENDED_RESULT_TYPE_METHODS.includes(method))return result;throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`)}function fillCacheFields(method,result){let fallback=cacheHintFallbackOf(result);if(result.resultType!=="complete"||!isCacheableResultMethod(method))return fallback===void 0?result:stripCacheHintFallback(result);let provided=result,ttlMs=isValidCacheTtlMs(provided.ttlMs)?provided.ttlMs:resolveTtlMs(fallback),cacheScope=isValidCacheScope(provided.cacheScope)?provided.cacheScope:resolveCacheScope(fallback),filled={...provided,ttlMs,cacheScope};return delete filled[RESULT_CACHE_HINT_FALLBACK],filled}function isPlainObject$5(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function stampServerInfoMeta(result,serverInfo){if(serverInfo===void 0)return result;let meta2=result._meta;return meta2===void 0?{...result,_meta:{[SERVER_INFO_META_KEY]:serverInfo}}:!isPlainObject$5(meta2)||meta2[SERVER_INFO_META_KEY]!==void 0?result:{...result,_meta:{...meta2,[SERVER_INFO_META_KEY]:serverInfo}}}function resolveTtlMs(fallback){return fallback!==void 0&&isValidCacheTtlMs(fallback.ttlMs)?fallback.ttlMs:DEFAULT_CACHE_TTL_MS}function resolveCacheScope(fallback){return fallback!==void 0&&isValidCacheScope(fallback.cacheScope)?fallback.cacheScope:DEFAULT_CACHE_SCOPE}function stripCacheHintFallback(result){let copy={...result};return delete copy[RESULT_CACHE_HINT_FALLBACK],copy}function inputSchemaMaps(){if(maps)return maps;let s=buildSchemas2026();return maps={request:{"elicitation/create":object({method:literal("elicitation/create"),params:s.ElicitRequestParamsSchema}),"sampling/createMessage":object({method:literal("sampling/createMessage"),params:s.CreateMessageRequestParamsSchema}),"roots/list":object({method:literal("roots/list"),params:looseObject({}).optional()})},response:{"elicitation/create":s.ElicitResultSchema,"sampling/createMessage":s.CreateMessageResultSchema,"roots/list":s.ListRootsResultSchema}},maps}function isInputRequestMethod2026(method){return INPUT_REQUEST_METHODS_2026.includes(method)}function getInputRequestSchema2026(method){return isInputRequestMethod2026(method)?inputSchemaMaps().request[method]:void 0}function getInputResponseSchema2026(method){return isInputRequestMethod2026(method)?inputSchemaMaps().response[method]:void 0}function hasRequestMethod2026(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys,method)}function hasNotificationMethod2026(method){return Object.prototype.hasOwnProperty.call(notificationMethodKeys,method)}function hasResultMethod2026(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys,method)}function getRequestSchema2026(method){return hasRequestMethod2026(method)?buildSchemas2026().dispatchRequestSchemas[method]:void 0}function getResultSchema2026(method){return hasResultMethod2026(method)?buildSchemas2026().dispatchResultSchemas[method]:void 0}function getNotificationSchema2026(method){return hasNotificationMethod2026(method)?buildSchemas2026().notificationSchemas2026[method]:void 0}function isPlainObject$4(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function triState(schema2,raw2){if(schema2===void 0)return{ok:!1,reason:"not-in-era"};let parsed=schema2.safeParse(raw2);return parsed.success?{ok:!0,value:parsed.data}:{ok:!1,reason:"invalid",message:String(parsed.error)}}function enforceDeletedFields(method,result){let next=result,copied=!1,copy=()=>(copied||(next={...next},copied=!0),next),tools=result.tools;method==="tools/list"&&Array.isArray(tools)&&tools.some(tool=>isPlainObject$4(tool)&&"execution"in tool)&&(copy().tools=tools.map(tool=>{if(!isPlainObject$4(tool)||!("execution"in tool))return tool;let rest={...tool};return delete rest.execution,rest}));let capabilities=result.capabilities;if(isPlainObject$4(capabilities)&&"tasks"in capabilities){let rest={...capabilities};delete rest.tasks,copy().capabilities=rest}return next}function getWireResultSchemas(){if(wireResultSchemasMemo)return wireResultSchemasMemo;let s=buildSchemas2026();return wireResultSchemasMemo={"tools/call":s.CallToolResultSchema,"tools/list":s.ListToolsResultSchema,"prompts/get":s.GetPromptResultSchema,"prompts/list":s.ListPromptsResultSchema,"resources/list":s.ListResourcesResultSchema,"resources/templates/list":s.ListResourceTemplatesResultSchema,"resources/read":s.ReadResourceResultSchema,"completion/complete":s.CompleteResultSchema,"server/discover":s.DiscoverResultSchema},wireResultSchemasMemo}function codecForVersion(version2){return version2!==void 0&&isModernProtocolVersion(version2)?rev2026Codec:rev2025Codec}function classifiedWireEra(classification){return classification.revision!==void 0?codecForVersion(classification.revision).era:classification.era==="modern"?rev2026Codec.era:rev2025Codec.era}function isSpecRequestMethod(method){return ALL_CODECS.some(codec=>codec.hasRequestMethod(method))}function isSpecNotificationMethod(method){return ALL_CODECS.some(codec=>codec.hasNotificationMethod(method))}function isExtensionReusedRequestMethod(method){return method==="tasks/get"||method==="tasks/cancel"}function isPlainObject$3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function requestMetaOf(params){if(!isPlainObject$3(params))return;let meta2=params._meta;return isPlainObject$3(meta2)?meta2:void 0}function hasEnvelopeClaim(params){let meta2=requestMetaOf(params);return meta2!==void 0&&PROTOCOL_VERSION_META_KEY in meta2}function envelopeClaimVersion(params){let value=requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY];return typeof value=="string"?value:void 0}function validateEnvelopeMeta(meta2){return codecForVersion(MODERN_WIRE_REVISION).validateEnvelopeMeta(meta2)}function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}function scanXMcpHeaderDeclarations(inputSchema2){let declarations=[],seenLower=new Map,visit=(node2,path,reachable)=>{if(node2===null||typeof node2!="object")return;let schema2=node2;if(X_MCP_HEADER_KEY in schema2){if(!reachable||path.length===0)return`${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let raw2=schema2[X_MCP_HEADER_KEY];if(typeof raw2!="string"||raw2.length===0)return`${pathName(path)}: x-mcp-header MUST be a non-empty string`;if(!RFC9110_TOKEN.test(raw2))return`${pathName(path)}: x-mcp-header '${raw2}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let type=typeof schema2.type=="string"?schema2.type:void 0;if(type===void 0||!PERMITTED_X_MCP_HEADER_TYPES.has(type))return`${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type??"<none>"}`;let lower=raw2.toLowerCase(),prior=seenLower.get(lower);if(prior!==void 0)return`x-mcp-header '${raw2}' is not case-insensitively unique (also declared as '${prior}')`;seenLower.set(lower,raw2),declarations.push({path,headerName:raw2,type})}let properties=schema2.properties;if(properties!==null&&typeof properties=="object")for(let[key,child]of Object.entries(properties)){let fault$1=visit(child,[...path,key],reachable);if(fault$1!==void 0)return fault$1}for(let k of NON_REACHABLE_SUBSCHEMA_KEYWORDS){let sub=schema2[k];if(sub===void 0)continue;let branches=Array.isArray(sub)?sub:sub!==null&&typeof sub=="object"&&OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k)?Object.values(sub):[sub];for(let branch of branches){let fault$1=visit(branch,[...path,`<${k}>`],!1);if(fault$1!==void 0)return fault$1}}},fault=visit(inputSchema2,[],!0);return fault===void 0?{valid:!0,declarations}:{valid:!1,reason:fault}}function pathName(path){return path.length===0?"<root>":path.join(".")}function mcpParamPrimitiveToString(value){if(typeof value=="string")return value;if(typeof value=="boolean")return value?"true":"false";if(typeof value=="number")return!Number.isFinite(value)||Number.isInteger(value)&&!Number.isSafeInteger(value)?void 0:String(value)}function base64ToUtf8(b64){let bin=atob(b64),bytes=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)bytes[i]=bin.codePointAt(i);return new TextDecoder("utf-8",{fatal:!0}).decode(bytes)}function decodeMcpParamValue(value){if(!(value.startsWith(BASE64_SENTINEL_PREFIX)&&value.endsWith(BASE64_SENTINEL_SUFFIX)))return value;let b64=value.slice(9,value.length-2);if(BASE64_CANONICAL.test(b64))try{return base64ToUtf8(b64)}catch{return}}function valueAtPath(root,path){let node2=root;for(let key of path){if(node2===null||typeof node2!="object")return;node2=node2[key]}return node2}function validateMcpParamHeaders(declarations,args,headers){for(let decl of declarations){let headerKey=`${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`,headerValue=headers.get(headerKey),bodyRaw=valueAtPath(args,decl.path);if(bodyRaw==null)continue;let bodyString=mcpParamPrimitiveToString(bodyRaw);if(bodyString===void 0)continue;if(headerValue===null)return paramHeaderMismatchRejection("param-header-missing",headerKey,`the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`);let decoded=decodeMcpParamValue(headerValue);if(decoded===void 0)return paramHeaderMismatchRejection("param-header-invalid-encoding",headerKey,`the ${headerKey} header carries an invalid Base64 sentinel value`);if(!((decl.type==="integer"||decl.type==="number")&&CANONICAL_DECIMAL.test(decoded)&&typeof bodyRaw=="number"?Number(decoded)===bodyRaw:decoded===bodyString))return paramHeaderMismatchRejection("param-header-mismatch",headerKey,`the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`)}}function paramHeaderMismatchRejection(cell,header,body){return{kind:"reject",rung:"param-header-validation",cell,httpStatus:400,code:HEADER_MISMATCH_ERROR_CODE,message:`Bad Request: the request headers and body disagree: ${body}`,data:{mismatch:{header,body}},settled:!0}}function httpStatusForErrorCode(code,origin){return origin==="in-band"?code===ProtocolErrorCode.MissingRequiredClientCapability?400:200:LADDER_ERROR_HTTP_STATUS[code]??400}function rejection(rung,cell,httpStatus,error3,settled){return{kind:"reject",rung,cell,httpStatus,code:error3.code,message:error3.message,...error3.data!==void 0&&{data:error3.data},settled}}function crossCheckMismatch(cell,header,body,rung="era-classification"){return rejection(rung,cell,400,new ProtocolError(HEADER_MISMATCH_ERROR_CODE,`Bad Request: the request headers and body disagree: ${body}`,{mismatch:{header,body}}),!0)}function mcpNameSource(method,params){let field=Object.hasOwn(MCP_NAME_HEADER_SOURCE,method)?MCP_NAME_HEADER_SOURCE[method]:void 0;if(field===void 0)return;let raw2=isPlainObject$2(params)?params[field]:void 0;return{field,value:typeof raw2=="string"?raw2:void 0}}function stripHttpOws(value){let start=0;for(;start<value.length;){let code=value.codePointAt(start);if(code!==9&&code!==32)break;start+=1}let end=value.length;for(;end>start;){let code=value.codePointAt(end-1);if(code!==9&&code!==32)break;end-=1}return start===0&&end===value.length?value:value.slice(start,end)}function validateStandardRequestHeaders(request,route){if(route.messageKind!=="request")return;let method=route.message.method;if(request.protocolVersionHeader===void 0){let claimed=route.classification.revision;return crossCheckMismatch("version-header-missing","(missing)",claimed===void 0?"the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent":`the body envelope names protocol version ${claimed} but the required MCP-Protocol-Version header is absent`,"standard-header-validation")}if(request.mcpMethodHeader===void 0)return crossCheckMismatch("method-header-missing","(missing)",`the body names method ${method} but the required Mcp-Method header is absent`,"standard-header-validation");let source=mcpNameSource(method,route.message.params);if(source===void 0)return;let{field:sourceField,value:bodyValue}=source;if(request.mcpNameHeader===void 0)return bodyValue===void 0?void 0:crossCheckMismatch("name-header-missing","(missing)",`the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`,"standard-header-validation");let normalizedNameHeader=stripHttpOws(request.mcpNameHeader),decoded=decodeMcpParamValue(normalizedNameHeader);if(decoded===void 0)return crossCheckMismatch("name-header-invalid-encoding",normalizedNameHeader,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation");if(bodyValue!==void 0&&decoded!==bodyValue)return crossCheckMismatch("name-header-mismatch",normalizedNameHeader,`the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`,"standard-header-validation")}function isPlainObject$2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function classificationForClaim(claimedVersion){return claimedVersion===void 0?{era:"modern"}:{era:isModernProtocolVersion(claimedVersion)?"modern":"legacy",revision:claimedVersion}}function carriesValidModernEnvelopeClaim(params){if(!hasEnvelopeClaim(params))return!1;let claimedVersion=envelopeClaimVersion(params);if(claimedVersion===void 0||!isModernProtocolVersion(claimedVersion))return!1;let meta2=requestMetaOf(params);return meta2!==void 0&&validateEnvelopeMeta(meta2).length===0}function classifyBatch(body){if(body.length===0)return rejection("jsonrpc-shape","empty-batch",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let element of body){if(hasEnvelopeClaim(isPlainObject$2(element)?element.params:void 0))return rejection("jsonrpc-shape","batch-with-modern-element",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(isJSONRPCRequest(element)||isJSONRPCNotification(element)||isJSONRPCResultResponse(element)||isJSONRPCErrorResponse(element)))return rejection("jsonrpc-shape","batch-with-invalid-element",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}function classifyRequestBody(request,body){let params=body.params,method=body.method,headerVersion=request.protocolVersionHeader,headerNamesModern=headerVersion!==void 0&&isModernProtocolVersion(headerVersion);if(method==="initialize"&&!carriesValidModernEnvelopeClaim(params)){if(headerNamesModern)return crossCheckMismatch("initialize-with-modern-header",headerVersion,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let requestedVersion=isPlainObject$2(params)&&typeof params.protocolVersion=="string"?params.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...requestedVersion!==void 0&&{requestedVersion}}}if(hasEnvelopeClaim(params)){let meta2=requestMetaOf(params),firstIssue=(meta2===void 0?[]:validateEnvelopeMeta(meta2))[0];if(firstIssue!==void 0)return rejection("envelope","envelope-invalid",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`,{envelope:firstIssue}),!0);let claimedVersion=envelopeClaimVersion(params);return headerVersion!==void 0&&claimedVersion!==void 0&&headerVersion!==claimedVersion?crossCheckMismatch("header-body-version-mismatch",headerVersion,`the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`):request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("method-header-mismatch",request.mcpMethodHeader,`the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:body,classification:classificationForClaim(claimedVersion)}}if(headerNamesModern){let meta2=requestMetaOf(params),missingFromEnvelope=validateEnvelopeMeta(meta2??{}).filter(issue2=>issue2.problem==="missing").map(issue2=>issue2.key),missing=meta2===void 0?["_meta"]:missingFromEnvelope.length>0?missingFromEnvelope:[PROTOCOL_VERSION_META_KEY];return rejection("envelope","modern-header-without-claim",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`,{envelope:{missing}}),!0)}return{kind:"legacy",reason:"no-claim",...headerVersion!==void 0&&{requestedVersion:headerVersion}}}function classifyNotificationBody(request,body){let params=body.params,method=body.method,headerVersion=request.protocolVersionHeader,headerNamesModern=headerVersion!==void 0&&isModernProtocolVersion(headerVersion);if(hasEnvelopeClaim(params)){let claimedVersion=envelopeClaimVersion(params);if(claimedVersion===void 0){let meta2=requestMetaOf(params),claimIssue=(meta2===void 0?[]:validateEnvelopeMeta(meta2)).find(issue2=>issue2.key===PROTOCOL_VERSION_META_KEY)??{key:PROTOCOL_VERSION_META_KEY,problem:"expected a protocol version string"};return rejection("envelope","notification-envelope-invalid",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`,{envelope:claimIssue}),!0)}if(headerVersion!==void 0&&headerVersion!==claimedVersion)return crossCheckMismatch("notification-header-body-version-mismatch",headerVersion,`the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`);let classification=classificationForClaim(claimedVersion);return classification.era==="modern"&&request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("notification-method-header-mismatch",request.mcpMethodHeader,`the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:body,classification}}return headerNamesModern?request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("notification-method-header-mismatch",request.mcpMethodHeader,`the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:body,classification:{era:"modern",revision:headerVersion}}:{kind:"legacy",reason:"notification",...headerVersion!==void 0&&{requestedVersion:headerVersion}}}function classifyInboundRequest(request){if(request={...request,...request.protocolVersionHeader!==void 0&&{protocolVersionHeader:stripHttpOws(request.protocolVersionHeader)},...request.mcpMethodHeader!==void 0&&{mcpMethodHeader:stripHttpOws(request.mcpMethodHeader)},...request.mcpNameHeader!==void 0&&{mcpNameHeader:stripHttpOws(request.mcpNameHeader)}},request.httpMethod.toUpperCase()!=="POST")return{kind:"legacy",reason:"http-method"};let body=request.body;return Array.isArray(body)?classifyBatch(body):isJSONRPCResultResponse(body)||isJSONRPCErrorResponse(body)?{kind:"legacy",reason:"response"}:isPlainObject$2(body)&&isJSONRPCRequest(body)?classifyRequestBody(request,body):isPlainObject$2(body)&&isJSONRPCNotification(body)?classifyNotificationBody(request,body):rejection("jsonrpc-shape","invalid-json-rpc-body",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}function modernOnlyStrictRejection(route,supportedVersions){switch(route.reason){case"http-method":return rejection("http-method","modern-only-method-not-allowed",405,new ProtocolError(-32e3,"Method not allowed."),!0);case"batch":return rejection("jsonrpc-shape","modern-only-batch-not-supported",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return rejection("jsonrpc-shape","modern-only-response-post",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let requested=route.requestedVersion;return rejection("era-classification","modern-only-missing-envelope",400,requested===void 0?new ProtocolError(ProtocolErrorCode.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...supportedVersions]}):new UnsupportedProtocolVersionError({supported:[...supportedVersions],requested}),!0)}}}function parseSchema(schema2,data){return safeParse(schema2,data)}function shapeKeys(schemas){return new Set(schemas.flatMap(schema2=>Object.keys(schema2.shape)))}function isStandardSchema(schema2){if(schema2==null)return!1;let schemaType=typeof schema2;return schemaType!=="object"&&schemaType!=="function"||!("~standard"in schema2)?!1:typeof schema2["~standard"]?.validate=="function"}function standardSchemaToJsonSchema(schema2,io="input"){let std=schema2["~standard"],result;if(std.jsonSchema)result=std.jsonSchema[io]({target:JSON_SCHEMA_CONVERSION_TARGET});else if(std.vendor==="zod"){if(!("_zod"in schema2))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");warnedZodFallback||(warnedZodFallback=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),result=toJSONSchema(schema2,{target:JSON_SCHEMA_CONVERSION_TARGET,io})}else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(io==="output")return result.type!==void 0?result:isProvablyObjectShapedRoot(result)?{type:"object",...result}:result;if(result.type!==void 0&&result.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...result}}function isProvablyObjectShapedRoot(schema2){if("properties"in schema2||"patternProperties"in schema2||"additionalProperties"in schema2||"required"in schema2)return!0;for(let key of["oneOf","anyOf","allOf"]){let members2=schema2[key];if(Array.isArray(members2)&&members2.length>0)return members2.every(m=>m!==null&&typeof m=="object"&&(m.type==="object"||isProvablyObjectShapedRoot(m)))}return!1}function formatIssue(issue2){return issue2.path?.length?`${issue2.path.map(p=>String(typeof p=="object"?p.key:p)).join(".")}: ${issue2.message}`:issue2.message}async function validateStandardSchema(schema2,data){let result=await schema2["~standard"].validate(data);return result.issues&&result.issues.length>0?{success:!1,error:result.issues.map(i=>formatIssue(i)).join(", ")}:{success:!0,data:result.value}}function zodEmittedPattern(schema2){let jsonSchema=toJSONSchema(schema2,{target:JSON_SCHEMA_CONVERSION_TARGET,io:"input"});return typeof jsonSchema.pattern=="string"?jsonSchema.pattern:void 0}function datetimeReferenceSchemas(pattern){let fractionDigits=DATETIME_FRACTION_DIGITS.exec(pattern),precisions=[void 0,-1,0];return fractionDigits&&precisions.push(Number(fractionDigits[1])),[!1,!0].flatMap(local=>[!1,!0].flatMap(offset=>precisions.map(precision=>iso_exports.datetime({local,offset,precision}))))}function referencePatternsForFormat(format,pattern){let referenceSchemas;switch(format){case"email":referenceSchemas=[email2()];break;case"uri":referenceSchemas=[url()];break;case"date":referenceSchemas=[iso_exports.date()];break;case"date-time":referenceSchemas=datetimeReferenceSchemas(pattern);break}return new Set(referenceSchemas.map(schema2=>zodEmittedPattern(schema2)).filter(emitted=>emitted!==void 0))}function isLibraryFormatPattern(format,pattern,vendor){return vendor!=="zod"?!0:referencePatternsForFormat(format,pattern).has(pattern)}function promptArgumentsFromStandardSchema(schema2){let jsonSchema=standardSchemaToJsonSchema(schema2,"input"),properties=jsonSchema.properties||{},required2=jsonSchema.required||[];return Object.entries(properties).map(([name,prop])=>({name,description:prop?.description,required:required2.includes(name)}))}function isJsonObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function convertStandardElicitationSchema(schema2){try{return standardSchemaToJsonSchema(schema2,"input")}catch(error3){let detail=error3 instanceof Error?error3.message:String(error3);throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`)}}function isAnnotationOnlyJsonSchemaKeyword(key){return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key)||key.startsWith("x-")}function walkProperty(node2,path,vendor,unsupported){if(!isJsonObject(node2))return node2;let allowedKeys=typeof node2.type=="string"&&Object.hasOwn(PROPERTY_KEYS_BY_TYPE,node2.type)?PROPERTY_KEYS_BY_TYPE[node2.type]:void 0;if(allowedKeys===void 0)return node2;let pruned={};for(let[key,value]of Object.entries(node2))allowedKeys.has(key)||isAnnotationOnlyJsonSchemaKeyword(key)?pruned[key]=value:key==="pattern"&&node2.type==="string"&&typeof node2.format=="string"?SUPPORTED_STRING_FORMATS.has(node2.format)?(typeof value!="string"||!isLibraryFormatPattern(node2.format,value,vendor))&&unsupported.push(`${path}.${key}`):pruned[key]=value:unsupported.push(`${path}.${key}`);return pruned}function walkRequestedSchema(converted,vendor){let pruned={},unsupported=[];for(let[key,value]of Object.entries(converted))key==="properties"&&isJsonObject(value)?pruned[key]=Object.fromEntries(Object.entries(value).map(([name,node2])=>[name,walkProperty(node2,`properties.${name}`,vendor,unsupported)])):ROOT_KEYS.has(key)?pruned[key]=value:isAnnotationOnlyJsonSchemaKeyword(key)||unsupported.push(key);if(unsupported.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`);return pruned}function describeUnsupportedProperties(pruned,fallback){if(!isJsonObject(pruned.properties))return fallback;let offenders=Object.entries(pruned.properties).filter(([,node2])=>!parseSchema(PrimitiveSchemaDefinitionSchema,node2).success).map(([name])=>`properties.${name}`);return offenders.length>0?offenders.join(", "):fallback}function findDroppedConstraintPaths(original,parsed,path=""){return Array.isArray(original)&&Array.isArray(parsed)?original.flatMap((item,index)=>findDroppedConstraintPaths(item,parsed[index],`${path}[${index}]`)):!isJsonObject(original)||!isJsonObject(parsed)?[]:Object.entries(original).flatMap(([key,value])=>{let childPath=path?`${path}.${key}`:key;return Object.prototype.hasOwnProperty.call(parsed,key)?findDroppedConstraintPaths(value,parsed[key],childPath):isAnnotationOnlyJsonSchemaKeyword(key)?[]:[childPath]})}function normalizeElicitInputParams(input){if(!isStandardSchema(input.requestedSchema))return{...input,mode:"form",requestedSchema:input.requestedSchema};let vendor=input.requestedSchema["~standard"].vendor,pruned=walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema),vendor),parsed=parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema,pruned);if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned,parsed.error.message)}`);let droppedConstraints=findDroppedConstraintPaths(pruned,parsed.data);if(droppedConstraints.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`);let danglingRequired=(parsed.data.required??[]).filter(key=>!Object.prototype.hasOwnProperty.call(parsed.data.properties,key));if(danglingRequired.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`);return{...input,mode:"form",requestedSchema:parsed.data}}function buildInputRequired(spec){let hasInputRequests=spec.inputRequests!==void 0&&Object.keys(spec.inputRequests).length>0,hasRequestState=typeof spec.requestState=="string";if(!hasInputRequests&&!hasRequestState)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...spec.inputRequests!==void 0&&{inputRequests:spec.inputRequests},...spec.requestState!==void 0&&{requestState:spec.requestState}}}function acceptedContent(responses,key,schema2){let view=inputResponse(responses,key);if(view.kind!=="elicit"||view.action!=="accept"||view.content===void 0)return;if(schema2===void 0)return view.content;let outcome=schema2["~standard"].validate(view.content);if(outcome instanceof Promise)throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema");return outcome.issues===void 0?outcome.value:void 0}function inputResponse(responses,key){if(responses===void 0||typeof responses!="object"||responses===null)return{kind:"missing"};let entry=responses[key];if(entry===null||typeof entry!="object"||Array.isArray(entry))return{kind:"missing"};let candidate=entry;if(candidate.action==="accept"||candidate.action==="decline"||candidate.action==="cancel"){let content=candidate.content;return{kind:"elicit",action:candidate.action,...content!==null&&typeof content=="object"&&!Array.isArray(content)&&{content}}}return Array.isArray(candidate.roots)?{kind:"roots",roots:candidate.roots}:typeof candidate.role=="string"&&candidate.content!==void 0?{kind:"sampling",result:candidate}:{kind:"missing"}}function inputRequiredRoundsExceededMessage(method,maxRounds){return`Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(signal.reason instanceof SdkError?signal.reason:new SdkError(SdkErrorCode.RequestTimeout,String(signal.reason)));return}let timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{clearTimeout(timer),reject(signal?.reason instanceof SdkError?signal.reason:new SdkError(SdkErrorCode.RequestTimeout,String(signal?.reason)))};signal?.addEventListener("abort",onAbort,{once:!0})})}function linkedRoundAbort(outer){let controller=new AbortController,onOuterAbort=()=>controller.abort(outer?.reason);return outer?.addEventListener("abort",onOuterAbort,{once:!0}),outer?.aborted&&controller.abort(outer.reason),{signal:controller.signal,abort:reason=>controller.abort(reason),dispose:()=>outer?.removeEventListener("abort",onOuterAbort)}}function register(key,schema2){let name=key.slice(0,-6);_specTypeSchemas[name]=schema2,_isSpecType[name]=v=>schema2.safeParse(v).success}function bootstrapOutboundCodec(method){switch(method){case"initialize":case"notifications/initialized":return codecForVersion(void 0);case"server/discover":return codecForVersion(MODERN_WIRE_REVISION);default:return}}function liftWireOnlyMaterial(message,kind){let params=message.params;if(!isPlainObject$1(params))return{message,lifted:{}};let meta2=params._meta,envelopeKeys=isPlainObject$1(meta2)?RESERVED_ENVELOPE_META_KEYS.filter(key=>key in meta2):[],retryKeys=kind==="request"?RETRY_PARAMS_KEYS.filter(key=>key in params):[];if(envelopeKeys.length===0&&retryKeys.length===0)return{message,lifted:{}};let lifted={},nextParams={...params};if(envelopeKeys.length>0&&isPlainObject$1(meta2)){let envelope={},nextMeta={...meta2};for(let key of envelopeKeys)envelope[key]=meta2[key],delete nextMeta[key];lifted.envelope=envelope,Object.keys(nextMeta).length>0?nextParams._meta=nextMeta:delete nextParams._meta}for(let key of retryKeys)key==="inputResponses"&&(lifted.inputResponses=nextParams[key]),key==="requestState"&&(lifted.requestState=nextParams[key]),delete nextParams[key];return{message:{...message,params:nextParams},lifted}}function codecResultValidator(codec,method){let probe=codec.validateResult(method,void 0);if(!(!probe.ok&&probe.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(value){let outcome=codec.validateResult(method,value);return outcome.ok?{value:outcome.value}:{issues:[{message:outcome.reason==="invalid"?outcome.message:`not-in-era: ${method}`}]}}}}}function requestStateAccessor(value){return()=>value}function withRequestStateValue(ctx,value){return{...ctx,mcpReq:{...ctx.mcpReq,requestState:requestStateAccessor(value)}}}function setNegotiatedProtocolVersion(instance,version2){writeNegotiatedProtocolVersion(instance,version2)}function isPlainObject$1(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];result[k]=isPlainObject$1(baseValue)&&isPlainObject$1(addValue)?{...baseValue,...addValue}:addValue}return result}function isPlainObject2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function partitionInputResponses(inputResponses){let accepted={},droppedKeys=[];if(!isPlainObject2(inputResponses))return{accepted,droppedKeys};for(let[key,entry]of Object.entries(inputResponses)){if(!isPlainObject2(entry)||"method"in entry||"result"in entry){droppedKeys.push(key);continue}accepted[key]=entry}return{accepted,droppedKeys}}function manualInputRequiredValue(decoded){return{resultType:"input_required",inputRequests:decoded.inputRequests,...decoded.requestState!==void 0&&{requestState:decoded.requestState},...decoded._meta!==void 0&&{_meta:decoded._meta}}}function mediaTypeEssence(header){if(header)try{return import_content_type.parse(header).type}catch{let essence=(header.split(";",1)[0]??"").trim().toLowerCase();return essence===""||header.slice(essence.length).includes(",")?void 0:essence}}function isJsonContentType(header){return header==="application/json"?!0:mediaTypeEssence(header)==="application/json"}function validateToolName(name){let warnings=[];if(name.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(name.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]};if(name.includes(" ")&&warnings.push("Tool name contains spaces, which may cause parsing issues"),name.includes(",")&&warnings.push("Tool name contains commas, which may cause parsing issues"),(name.startsWith("-")||name.endsWith("-"))&&warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(name.startsWith(".")||name.endsWith("."))&&warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!TOOL_NAME_REGEX.test(name)){let invalidChars=[...name].filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index,arr)=>arr.indexOf(char)===index);return warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c=>`"${c}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings}}return{isValid:!0,warnings}}function issueToolNameWarning(name,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name}":`);for(let warning of warnings)console.warn(` - ${warning}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function validateAndWarnToolName(name){let result=validateToolName(name);return issueToolNameWarning(name,result.warnings),result.isValid}function isZodV4Schema(v){return typeof v=="object"&&v!==null&&"_zod"in v}function looksLikeZodV3(v){return typeof v=="object"&&v!==null&&!("_zod"in v)&&"_def"in v&&typeof v._def?.typeName=="string"}function isZodRawShape(obj){if(typeof obj!="object"||obj===null||isStandardSchema(obj))return!1;let proto=Object.getPrototypeOf(obj);return proto!==Object.prototype&&proto!==null?!1:Object.values(obj).every(v=>isZodV4Schema(v))}function normalizeRawShapeSchema(schema2){if(schema2!==void 0){if(isZodRawShape(schema2))return object(schema2);if(typeof schema2=="object"&&schema2!==null&&!isStandardSchema(schema2)&&Object.values(schema2).some(v=>looksLikeZodV3(v)))throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!isStandardSchema(schema2))throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return schema2}}function fromJsonSchema(schema2,validator){let check=validator.getValidator(schema2);return{"~standard":{version:1,vendor:"mcp",jsonSchema:{input:()=>schema2,output:()=>schema2},validate:data=>{let result=check(data);return result.valid?{value:result.data}:{issues:[{message:result.errorMessage}]}}}}}var BRANDS,OAuthErrorCode,OAuthError,SdkErrorCode,SdkError,SdkHttpError,REQUIRED_CLIENT_CAPABILITIES_BY_METHOD,FIRST_MODERN_PROTOCOL_VERSION,SUPPORTED_MODERN_PROTOCOL_VERSIONS,TOOL_RESULT_FOREIGN_FAMILY_KEYS,memo$1,REF_REWRITE_DATA_POSITION_KEYS,REF_REWRITE_NAME_MAP_KEYS,requestMethodKeys$1,notificationMethodKeys$1,resultMethodKeys,maps$1,rev2025RequestMethods,rev2025NotificationMethods,NOT_IN_ERA$1,rev2025Codec,memo2,CACHEABLE_RESULT_METHODS,RESULT_CACHE_HINT_FALLBACK,ProtocolErrorCode,ProtocolError,ResourceNotFoundError,UrlElicitationRequiredError,UnsupportedProtocolVersionError,MissingRequiredClientCapabilityError,DEFAULT_CACHE_TTL_MS,DEFAULT_CACHE_SCOPE,EXTENDED_RESULT_TYPE_METHODS,INPUT_REQUEST_METHODS_2026,maps,requestMethodKeys,notificationMethodKeys,rev2026RequestMethods,rev2026NotificationMethods,NOT_IN_ERA,REQUIRED_ENVELOPE_KEYS,rev2026Codec,wireResultSchemasMemo,MODERN_WIRE_REVISION,ALL_CODECS,schemas_exports2,isJSONRPCRequest,isJSONRPCNotification,isJSONRPCResultResponse,isJSONRPCErrorResponse,isInputRequiredResult,isInitializeRequest,MCP_PARAM_HEADER_PREFIX,X_MCP_HEADER_KEY,RFC9110_TOKEN,PERMITTED_X_MCP_HEADER_TYPES,NON_REACHABLE_SUBSCHEMA_KEYWORDS,OBJECT_VALUED_SUBSCHEMA_KEYWORDS,BASE64_SENTINEL_PREFIX,BASE64_SENTINEL_SUFFIX,BASE64_CANONICAL,CANONICAL_DECIMAL,HEADER_MISMATCH_ERROR_CODE,INBOUND_VALIDATION_LADDER,LADDER_ERROR_HTTP_STATUS,MCP_NAME_HEADER_SOURCE,warnedZodFallback,JSON_SCHEMA_CONVERSION_TARGET,DATETIME_FRACTION_DIGITS,ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS,ROOT_KEYS,PROPERTY_KEYS_BY_TYPE,SUPPORTED_STRING_FORMATS,inputRequired,REQUEST_STATE_ONLY_LEG_PACING_MS,SPEC_SCHEMA_KEYS,authSchemas,_specTypeSchemas,_isSpecType,specTypeSchemas,isSpecType,DEFAULT_REQUEST_TIMEOUT_MSEC,RESERVED_ENVELOPE_META_KEYS,RETRY_PARAMS_KEYS,NO_REQUEST_STATE,writeNegotiatedProtocolVersion,Protocol,require_content_type,import_content_type,STDIO_DEFAULT_MAX_BUFFER_SIZE,TOOL_NAME_REGEX,MAX_TEMPLATE_LENGTH,MAX_VARIABLE_LENGTH,MAX_TEMPLATE_EXPRESSIONS,MAX_REGEX_LENGTH,UriTemplate,init_src_Cqbh3MYc=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/src-Cqbh3MYc.mjs"(){"use strict";init_chunk_Br0eD_fh();init_dialects_DoSzNhcb();init_internal();init_v4();BRANDS=Symbol.for("mcp.sdk.errorBrands");OAuthErrorCode=(function(OAuthErrorCode$1){return OAuthErrorCode$1.InvalidRequest="invalid_request",OAuthErrorCode$1.InvalidClient="invalid_client",OAuthErrorCode$1.InvalidGrant="invalid_grant",OAuthErrorCode$1.UnauthorizedClient="unauthorized_client",OAuthErrorCode$1.UnsupportedGrantType="unsupported_grant_type",OAuthErrorCode$1.InvalidScope="invalid_scope",OAuthErrorCode$1.AccessDenied="access_denied",OAuthErrorCode$1.ServerError="server_error",OAuthErrorCode$1.TemporarilyUnavailable="temporarily_unavailable",OAuthErrorCode$1.UnsupportedResponseType="unsupported_response_type",OAuthErrorCode$1.UnsupportedTokenType="unsupported_token_type",OAuthErrorCode$1.InvalidToken="invalid_token",OAuthErrorCode$1.MethodNotAllowed="method_not_allowed",OAuthErrorCode$1.TooManyRequests="too_many_requests",OAuthErrorCode$1.InvalidClientMetadata="invalid_client_metadata",OAuthErrorCode$1.InvalidRedirectUri="invalid_redirect_uri",OAuthErrorCode$1.InsufficientScope="insufficient_scope",OAuthErrorCode$1.InvalidTarget="invalid_target",OAuthErrorCode$1.InvalidDpopProof="invalid_dpop_proof",OAuthErrorCode$1.UseDpopNonce="use_dpop_nonce",OAuthErrorCode$1})({}),OAuthError=class OAuthError2 extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,errorUri){super(message),this.code=code,this.errorUri=errorUri,this.name="OAuthError",stampErrorBrands(this,new.target)}toResponseObject(){let response={error:this.code,error_description:this.message};return this.errorUri&&(response.error_uri=this.errorUri),response}static fromResponse(response){return new OAuthError2(response.error,response.error_description??response.error,response.error_uri)}},SdkErrorCode=(function(SdkErrorCode$1){return SdkErrorCode$1.NotConnected="NOT_CONNECTED",SdkErrorCode$1.AlreadyConnected="ALREADY_CONNECTED",SdkErrorCode$1.NotInitialized="NOT_INITIALIZED",SdkErrorCode$1.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",SdkErrorCode$1.RequestTimeout="REQUEST_TIMEOUT",SdkErrorCode$1.ConnectionClosed="CONNECTION_CLOSED",SdkErrorCode$1.SendFailed="SEND_FAILED",SdkErrorCode$1.InvalidResult="INVALID_RESULT",SdkErrorCode$1.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",SdkErrorCode$1.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",SdkErrorCode$1.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",SdkErrorCode$1.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",SdkErrorCode$1.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",SdkErrorCode$1.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",SdkErrorCode$1.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",SdkErrorCode$1.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",SdkErrorCode$1.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",SdkErrorCode$1.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",SdkErrorCode$1.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",SdkErrorCode$1})({}),SdkError=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,data,options){super(message,options),this.code=code,this.data=data,this.name="SdkError",stampErrorBrands(this,new.target)}},SdkHttpError=class extends SdkError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(code,message,data,options){super(code,message,data,options),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}},REQUIRED_CLIENT_CAPABILITIES_BY_METHOD={};FIRST_MODERN_PROTOCOL_VERSION="2026-07-28",SUPPORTED_MODERN_PROTOCOL_VERSIONS=[FIRST_MODERN_PROTOCOL_VERSION];TOOL_RESULT_FOREIGN_FAMILY_KEYS=["task","inputRequests","requestState"];REF_REWRITE_DATA_POSITION_KEYS=new Set(["const","enum","default","examples"]),REF_REWRITE_NAME_MAP_KEYS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);requestMethodKeys$1={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},notificationMethodKeys$1={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},resultMethodKeys={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};rev2025RequestMethods=Object.keys(requestMethodKeys$1),rev2025NotificationMethods=Object.keys(notificationMethodKeys$1);NOT_IN_ERA$1={ok:!1,reason:"not-in-era"};rev2025Codec={era:"2025-11-25",hasRequestMethod:hasRequestMethod2025,hasNotificationMethod:hasNotificationMethod2025,validateRequest:(method,raw2)=>triState$1(getRequestSchema(method),raw2),validateResult:(method,raw2)=>triState$1(getResultSchema(method),raw2),validateNotification:(method,raw2)=>triState$1(getNotificationSchema(method),raw2),hasInputRequestMethod:()=>!1,validateInputRequest:()=>NOT_IN_ERA$1,validateInputResponse:()=>NOT_IN_ERA$1,samplingResultVariant:((hasTools,raw2)=>{let s=buildSchemas2025();return triState$1(hasTools?s.CreateMessageResultWithToolsSchema:s.CreateMessageResultSchema,raw2)}),outboundEnvelope:_material=>{},validateEnvelopeMeta:_meta=>[],projectCallToolResult(result,advertisedOutputSchema){let withText=appendTextFallbackForNonObject(result),sc=withText.structuredContent;if(sc===void 0)return withText;let valueIsNonObject=typeof sc!="object"||sc===null||Array.isArray(sc),schemaWrapped=advertisedOutputSchema!==void 0&&isNonObjectJsonSchemaRoot(advertisedOutputSchema);return!valueIsNonObject&&!schemaWrapped?withText:{...withText,structuredContent:{result:sc}}},decodeResult(_method,raw2){if(isPlainObject$6(raw2)&&"resultType"in raw2){let stripped={...raw2};return delete stripped.resultType,{kind:"complete",result:stripped}}return{kind:"complete",result:raw2}},encodeResult(method,result){if(method!=="tools/list")return result;let tools=result.tools;return!Array.isArray(tools)||!tools.some(t=>toolNeedsLegacyWrap(t))?result:{...result,tools:tools.map(t=>toolNeedsLegacyWrap(t)?{...t,outputSchema:wrapOutputSchemaForLegacy(t.outputSchema)}:t)}},encodeErrorCode:code=>code===-32002?-32602:code,checkInboundEnvelope:_material=>{}};CACHEABLE_RESULT_METHODS=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];RESULT_CACHE_HINT_FALLBACK=Symbol("modelcontextprotocol.resultCacheHintFallback");ProtocolErrorCode=(function(ProtocolErrorCode$1){return ProtocolErrorCode$1[ProtocolErrorCode$1.ParseError=-32700]="ParseError",ProtocolErrorCode$1[ProtocolErrorCode$1.InvalidRequest=-32600]="InvalidRequest",ProtocolErrorCode$1[ProtocolErrorCode$1.MethodNotFound=-32601]="MethodNotFound",ProtocolErrorCode$1[ProtocolErrorCode$1.InvalidParams=-32602]="InvalidParams",ProtocolErrorCode$1[ProtocolErrorCode$1.InternalError=-32603]="InternalError",ProtocolErrorCode$1[ProtocolErrorCode$1.ResourceNotFound=-32002]="ResourceNotFound",ProtocolErrorCode$1[ProtocolErrorCode$1.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",ProtocolErrorCode$1[ProtocolErrorCode$1.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",ProtocolErrorCode$1[ProtocolErrorCode$1.UrlElicitationRequired=-32042]="UrlElicitationRequired",ProtocolErrorCode$1})({}),ProtocolError=class ProtocolError2 extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,data){super(message),this.code=code,this.data=data,this.name="ProtocolError",stampErrorBrands(this,new.target)}static fromError(code,message,data){if(code===ProtocolErrorCode.UrlElicitationRequired&&data){let errorData=data;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}if(code===ProtocolErrorCode.UnsupportedProtocolVersion&&data){let errorData=data;if(Array.isArray(errorData.supported)&&typeof errorData.requested=="string")return new UnsupportedProtocolVersionError({supported:errorData.supported,requested:errorData.requested},message)}if(code===ProtocolErrorCode.InvalidParams||code===ProtocolErrorCode.ResourceNotFound){let errorData=data;if(typeof errorData?.uri=="string"&&(code===ProtocolErrorCode.ResourceNotFound||Object.keys(errorData).length===1))return new ResourceNotFoundError(errorData.uri,message)}if(code===ProtocolErrorCode.MissingRequiredClientCapability&&data){let errorData=data;if(errorData.requiredCapabilities!==null&&typeof errorData.requiredCapabilities=="object"&&!Array.isArray(errorData.requiredCapabilities))return new MissingRequiredClientCapabilityError({requiredCapabilities:errorData.requiredCapabilities},message)}return new ProtocolError2(code,message,data)}},ResourceNotFoundError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(uri,message=`Resource not found: ${uri}`){super(ProtocolErrorCode.InvalidParams,message,{uri})}get uri(){return this.data.uri}},UrlElicitationRequiredError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ProtocolErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}},UnsupportedProtocolVersionError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(data,message=`Unsupported protocol version: ${data.requested}`){super(ProtocolErrorCode.UnsupportedProtocolVersion,message,data)}get supported(){return this.data.supported}get requested(){return this.data.requested}},MissingRequiredClientCapabilityError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(data,message=`Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`){super(ProtocolErrorCode.MissingRequiredClientCapability,message,data)}get requiredCapabilities(){return this.data.requiredCapabilities}},DEFAULT_CACHE_TTL_MS=0,DEFAULT_CACHE_SCOPE="private",EXTENDED_RESULT_TYPE_METHODS=["tools/call","prompts/get","resources/read"];INPUT_REQUEST_METHODS_2026=["elicitation/create","sampling/createMessage","roots/list"];requestMethodKeys={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},notificationMethodKeys={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};rev2026RequestMethods=Object.keys(requestMethodKeys),rev2026NotificationMethods=Object.keys(notificationMethodKeys);NOT_IN_ERA={ok:!1,reason:"not-in-era"},REQUIRED_ENVELOPE_KEYS=[PROTOCOL_VERSION_META_KEY,CLIENT_CAPABILITIES_META_KEY];rev2026Codec={era:"2026-07-28",hasRequestMethod:hasRequestMethod2026,hasNotificationMethod:hasNotificationMethod2026,hasInputRequestMethod:method=>getInputRequestSchema2026(method)!==void 0,validateRequest:(method,raw2)=>triState(getRequestSchema2026(method),raw2),validateResult:(method,raw2)=>triState(getResultSchema2026(method),raw2),validateNotification:(method,raw2)=>triState(getNotificationSchema2026(method),raw2),validateInputRequest:(method,raw2)=>triState(getInputRequestSchema2026(method),raw2),validateInputResponse:(method,raw2)=>triState(getInputResponseSchema2026(method),raw2),samplingResultVariant:()=>NOT_IN_ERA,outboundEnvelope(material){return{[PROTOCOL_VERSION_META_KEY]:material.protocolVersion,[CLIENT_INFO_META_KEY]:material.clientInfo,[CLIENT_CAPABILITIES_META_KEY]:material.clientCapabilities,...material.logLevel!==void 0&&{[LOG_LEVEL_META_KEY]:material.logLevel}}},validateEnvelopeMeta(meta2){let issues=[];for(let key of REQUIRED_ENVELOPE_KEYS)key in meta2||issues.push({key,problem:"missing"});let parsed=buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta2);if(!parsed.success)for(let issue2 of parsed.error.issues){let path=issue2.path.map(String),key=path.length>0?path.join("."):"_meta";path.length===1&&issues.some(existing=>existing.key===key&&existing.problem==="missing")||issues.push({key,problem:issue2.message})}return issues},projectCallToolResult:result=>appendTextFallbackForNonObject(result),inputRequestSchema:getInputRequestSchema2026,decodeResult(method,raw2){if(!isPlainObject$4(raw2))return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: not an object`,{method})};let rawResultType=raw2.resultType;if(rawResultType===void 0)return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method,violation:"missing-resultType"})};if(typeof rawResultType!="string")return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: non-string resultType`,{method,resultType:rawResultType})};if(rawResultType==="input_required"){let rawInputRequests=raw2.inputRequests,inputRequests=isPlainObject$4(rawInputRequests)?rawInputRequests:{},requestState=raw2.requestState,metaParse=raw2._meta===void 0?void 0:buildSchemas2026().ResultMetaSchema.safeParse(raw2._meta),meta2=metaParse?.success?metaParse.data:void 0;return Object.keys(inputRequests).length===0&&typeof requestState!="string"?{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests,...typeof requestState=="string"&&{requestState},...meta2!==void 0&&{_meta:meta2}}}if(rawResultType!=="complete")return{kind:"invalid",error:new SdkError(SdkErrorCode.UnsupportedResultType,`Unsupported result type '${rawResultType}' for ${method}`,{resultType:rawResultType,method})};let wireResultSchemas=getWireResultSchemas(),wireSchema=Object.hasOwn(wireResultSchemas,method)?wireResultSchemas[method]:void 0;if(wireSchema!==void 0){let parsed=wireSchema.safeParse(raw2);if(!parsed.success)return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: ${parsed.error}`,{method})}}let lifted={...raw2};return delete lifted.resultType,{kind:"complete",result:lifted}},encodeResult(method,result,serverInfo){return stampServerInfoMeta(fillCacheFields(method,stampResultType(method,enforceDeletedFields(method,result))),serverInfo)},encodeErrorCode:code=>code===-32002?-32602:code,checkInboundEnvelope(material){if(material.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let parsed=buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope);if(!parsed.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map(issue2=>issue2.message).join("; ")}`}};MODERN_WIRE_REVISION="2026-07-28";ALL_CODECS=[rev2025Codec,rev2026Codec];schemas_exports2=__exportAll({AnnotationsSchema:()=>AnnotationsSchema,AudioContentSchema:()=>AudioContentSchema,BaseMetadataSchema:()=>BaseMetadataSchema,BaseRequestParamsSchema:()=>BaseRequestParamsSchema,BlobResourceContentsSchema:()=>BlobResourceContentsSchema,BooleanSchemaSchema:()=>BooleanSchemaSchema,CallToolRequestParamsSchema:()=>CallToolRequestParamsSchema,CallToolRequestSchema:()=>CallToolRequestSchema,CallToolResultSchema:()=>CallToolResultSchema,CancelTaskRequestSchema:()=>CancelTaskRequestSchema,CancelTaskResultSchema:()=>CancelTaskResultSchema,CancelledNotificationParamsSchema:()=>CancelledNotificationParamsSchema,CancelledNotificationSchema:()=>CancelledNotificationSchema,ClientCapabilitiesSchema:()=>ClientCapabilitiesSchema,ClientNotificationSchema:()=>ClientNotificationSchema,ClientRequestSchema:()=>ClientRequestSchema,ClientResultSchema:()=>ClientResultSchema,ClientTasksCapabilitySchema:()=>ClientTasksCapabilitySchema,CompatibilityCallToolResultSchema:()=>CompatibilityCallToolResultSchema,CompleteRequestParamsSchema:()=>CompleteRequestParamsSchema,CompleteRequestSchema:()=>CompleteRequestSchema,CompleteResultSchema:()=>CompleteResultSchema,ContentBlockSchema:()=>ContentBlockSchema,CreateMessageRequestParamsSchema:()=>CreateMessageRequestParamsSchema,CreateMessageRequestSchema:()=>CreateMessageRequestSchema,CreateMessageResultSchema:()=>CreateMessageResultSchema,CreateMessageResultWithToolsSchema:()=>CreateMessageResultWithToolsSchema,CreateTaskResultSchema:()=>CreateTaskResultSchema,CursorSchema:()=>CursorSchema,DiscoverRequestSchema:()=>DiscoverRequestSchema,DiscoverResultSchema:()=>DiscoverResultSchema,ElicitRequestFormParamsSchema:()=>ElicitRequestFormParamsSchema,ElicitRequestParamsSchema:()=>ElicitRequestParamsSchema,ElicitRequestSchema:()=>ElicitRequestSchema,ElicitRequestURLParamsSchema:()=>ElicitRequestURLParamsSchema,ElicitResultSchema:()=>ElicitResultSchema,ElicitationCompleteNotificationParamsSchema:()=>ElicitationCompleteNotificationParamsSchema,ElicitationCompleteNotificationSchema:()=>ElicitationCompleteNotificationSchema,EmbeddedResourceSchema:()=>EmbeddedResourceSchema,EmptyResultSchema:()=>EmptyResultSchema,EnumSchemaSchema:()=>EnumSchemaSchema,GetPromptRequestParamsSchema:()=>GetPromptRequestParamsSchema,GetPromptRequestSchema:()=>GetPromptRequestSchema,GetPromptResultSchema:()=>GetPromptResultSchema,GetTaskPayloadRequestSchema:()=>GetTaskPayloadRequestSchema,GetTaskPayloadResultSchema:()=>GetTaskPayloadResultSchema,GetTaskRequestSchema:()=>GetTaskRequestSchema,GetTaskResultSchema:()=>GetTaskResultSchema,IconSchema:()=>IconSchema,IconsSchema:()=>IconsSchema,ImageContentSchema:()=>ImageContentSchema,ImplementationSchema:()=>ImplementationSchema,InitializeRequestParamsSchema:()=>InitializeRequestParamsSchema,InitializeRequestSchema:()=>InitializeRequestSchema,InitializeResultSchema:()=>InitializeResultSchema,InitializedNotificationSchema:()=>InitializedNotificationSchema,JSONArraySchema:()=>JSONArraySchema,JSONObjectSchema:()=>JSONObjectSchema,JSONRPCErrorResponseSchema:()=>JSONRPCErrorResponseSchema,JSONRPCMessageSchema:()=>JSONRPCMessageSchema,JSONRPCNotificationSchema:()=>JSONRPCNotificationSchema,JSONRPCRequestSchema:()=>JSONRPCRequestSchema,JSONRPCResponseSchema:()=>JSONRPCResponseSchema,JSONRPCResultResponseSchema:()=>JSONRPCResultResponseSchema,JSONValueSchema:()=>JSONValueSchema,LegacyTitledEnumSchemaSchema:()=>LegacyTitledEnumSchemaSchema,ListChangedOptionsBaseSchema:()=>ListChangedOptionsBaseSchema,ListPromptsRequestSchema:()=>ListPromptsRequestSchema,ListPromptsResultSchema:()=>ListPromptsResultSchema,ListResourceTemplatesRequestSchema:()=>ListResourceTemplatesRequestSchema,ListResourceTemplatesResultSchema:()=>ListResourceTemplatesResultSchema,ListResourcesRequestSchema:()=>ListResourcesRequestSchema,ListResourcesResultSchema:()=>ListResourcesResultSchema,ListRootsRequestSchema:()=>ListRootsRequestSchema,ListRootsResultSchema:()=>ListRootsResultSchema,ListTasksRequestSchema:()=>ListTasksRequestSchema,ListTasksResultSchema:()=>ListTasksResultSchema,ListToolsRequestSchema:()=>ListToolsRequestSchema,ListToolsResultSchema:()=>ListToolsResultSchema,LoggingLevelSchema:()=>LoggingLevelSchema,LoggingMessageNotificationParamsSchema:()=>LoggingMessageNotificationParamsSchema,LoggingMessageNotificationSchema:()=>LoggingMessageNotificationSchema,ModelHintSchema:()=>ModelHintSchema,ModelPreferencesSchema:()=>ModelPreferencesSchema,MultiSelectEnumSchemaSchema:()=>MultiSelectEnumSchemaSchema,NotificationSchema:()=>NotificationSchema,NotificationsParamsSchema:()=>NotificationsParamsSchema,NumberSchemaSchema:()=>NumberSchemaSchema,PaginatedRequestParamsSchema:()=>PaginatedRequestParamsSchema,PaginatedRequestSchema:()=>PaginatedRequestSchema,PaginatedResultSchema:()=>PaginatedResultSchema,PingRequestSchema:()=>PingRequestSchema,PrimitiveSchemaDefinitionSchema:()=>PrimitiveSchemaDefinitionSchema,ProgressNotificationParamsSchema:()=>ProgressNotificationParamsSchema,ProgressNotificationSchema:()=>ProgressNotificationSchema,ProgressSchema:()=>ProgressSchema,ProgressTokenSchema:()=>ProgressTokenSchema,PromptArgumentSchema:()=>PromptArgumentSchema,PromptListChangedNotificationSchema:()=>PromptListChangedNotificationSchema,PromptMessageSchema:()=>PromptMessageSchema,PromptReferenceSchema:()=>PromptReferenceSchema,PromptSchema:()=>PromptSchema,ReadResourceRequestParamsSchema:()=>ReadResourceRequestParamsSchema,ReadResourceRequestSchema:()=>ReadResourceRequestSchema,ReadResourceResultSchema:()=>ReadResourceResultSchema,RelatedTaskMetadataSchema:()=>RelatedTaskMetadataSchema,RequestIdSchema:()=>RequestIdSchema,RequestMetaSchema:()=>RequestMetaSchema,RequestSchema:()=>RequestSchema,ResourceContentsSchema:()=>ResourceContentsSchema,ResourceLinkSchema:()=>ResourceLinkSchema,ResourceListChangedNotificationSchema:()=>ResourceListChangedNotificationSchema,ResourceRequestParamsSchema:()=>ResourceRequestParamsSchema,ResourceSchema:()=>ResourceSchema,ResourceTemplateReferenceSchema:()=>ResourceTemplateReferenceSchema,ResourceTemplateSchema:()=>ResourceTemplateSchema,ResourceUpdatedNotificationParamsSchema:()=>ResourceUpdatedNotificationParamsSchema,ResourceUpdatedNotificationSchema:()=>ResourceUpdatedNotificationSchema,ResultMetaObjectSchema:()=>ResultMetaObjectSchema,ResultSchema:()=>ResultSchema,RoleSchema:()=>RoleSchema,RootSchema:()=>RootSchema,RootsListChangedNotificationSchema:()=>RootsListChangedNotificationSchema,SamplingContentSchema:()=>SamplingContentSchema,SamplingMessageContentBlockSchema:()=>SamplingMessageContentBlockSchema,SamplingMessageSchema:()=>SamplingMessageSchema,ServerCapabilitiesSchema:()=>ServerCapabilitiesSchema,ServerNotificationSchema:()=>ServerNotificationSchema,ServerRequestSchema:()=>ServerRequestSchema,ServerResultSchema:()=>ServerResultSchema,ServerTasksCapabilitySchema:()=>ServerTasksCapabilitySchema,SetLevelRequestParamsSchema:()=>SetLevelRequestParamsSchema,SetLevelRequestSchema:()=>SetLevelRequestSchema,SingleSelectEnumSchemaSchema:()=>SingleSelectEnumSchemaSchema,StringSchemaSchema:()=>StringSchemaSchema,SubscribeRequestParamsSchema:()=>SubscribeRequestParamsSchema,SubscribeRequestSchema:()=>SubscribeRequestSchema,SubscriptionFilterSchema:()=>SubscriptionFilterSchema,SubscriptionsAcknowledgedNotificationParamsSchema:()=>SubscriptionsAcknowledgedNotificationParamsSchema,SubscriptionsAcknowledgedNotificationSchema:()=>SubscriptionsAcknowledgedNotificationSchema,SubscriptionsListenRequestParamsSchema:()=>SubscriptionsListenRequestParamsSchema,SubscriptionsListenRequestSchema:()=>SubscriptionsListenRequestSchema,SubscriptionsListenResultMetaSchema:()=>SubscriptionsListenResultMetaSchema,SubscriptionsListenResultSchema:()=>SubscriptionsListenResultSchema,TaskAugmentedRequestParamsSchema:()=>TaskAugmentedRequestParamsSchema,TaskCreationParamsSchema:()=>TaskCreationParamsSchema,TaskMetadataSchema:()=>TaskMetadataSchema,TaskSchema:()=>TaskSchema,TaskStatusNotificationParamsSchema:()=>TaskStatusNotificationParamsSchema,TaskStatusNotificationSchema:()=>TaskStatusNotificationSchema,TaskStatusSchema:()=>TaskStatusSchema,TextContentSchema:()=>TextContentSchema,TextResourceContentsSchema:()=>TextResourceContentsSchema,TitledMultiSelectEnumSchemaSchema:()=>TitledMultiSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema:()=>TitledSingleSelectEnumSchemaSchema,ToolAnnotationsSchema:()=>ToolAnnotationsSchema,ToolChoiceSchema:()=>ToolChoiceSchema,ToolExecutionSchema:()=>ToolExecutionSchema,ToolListChangedNotificationSchema:()=>ToolListChangedNotificationSchema,ToolResultContentSchema:()=>ToolResultContentSchema,ToolSchema:()=>ToolSchema,ToolUseContentSchema:()=>ToolUseContentSchema,UnsubscribeRequestParamsSchema:()=>UnsubscribeRequestParamsSchema,UnsubscribeRequestSchema:()=>UnsubscribeRequestSchema,UntitledMultiSelectEnumSchemaSchema:()=>UntitledMultiSelectEnumSchemaSchema,UntitledSingleSelectEnumSchemaSchema:()=>UntitledSingleSelectEnumSchemaSchema}),isJSONRPCRequest=value=>JSONRPCRequestSchema.safeParse(value).success,isJSONRPCNotification=value=>JSONRPCNotificationSchema.safeParse(value).success,isJSONRPCResultResponse=value=>typeof value=="object"&&value!==null&&Object.hasOwn(value,"result")&&JSONRPCResultResponseSchema.safeParse(value).success,isJSONRPCErrorResponse=value=>typeof value=="object"&&value!==null&&Object.hasOwn(value,"error")&&JSONRPCErrorResponseSchema.safeParse(value).success,isInputRequiredResult=value=>typeof value=="object"&&value!==null&&!Array.isArray(value)&&value.resultType==="input_required",isInitializeRequest=value=>InitializeRequestSchema.safeParse(value).success;MCP_PARAM_HEADER_PREFIX="Mcp-Param-",X_MCP_HEADER_KEY="x-mcp-header",RFC9110_TOKEN=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,PERMITTED_X_MCP_HEADER_TYPES=new Set(["string","integer","boolean","number"]);NON_REACHABLE_SUBSCHEMA_KEYWORDS=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],OBJECT_VALUED_SUBSCHEMA_KEYWORDS=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);BASE64_SENTINEL_PREFIX="=?base64?",BASE64_SENTINEL_SUFFIX="?=",BASE64_CANONICAL=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,CANONICAL_DECIMAL=/^-?\d+(\.\d+)?$/;HEADER_MISMATCH_ERROR_CODE=-32020,INBOUND_VALIDATION_LADDER=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[ProtocolErrorCode.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[HEADER_MISMATCH_ERROR_CODE,ProtocolErrorCode.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[ProtocolErrorCode.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[ProtocolErrorCode.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[ProtocolErrorCode.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[HEADER_MISMATCH_ERROR_CODE],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[ProtocolErrorCode.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[HEADER_MISMATCH_ERROR_CODE],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],LADDER_ERROR_HTTP_STATUS={[ProtocolErrorCode.ParseError]:400,[ProtocolErrorCode.InvalidRequest]:400,[ProtocolErrorCode.MethodNotFound]:404,[ProtocolErrorCode.UnsupportedProtocolVersion]:400,[ProtocolErrorCode.MissingRequiredClientCapability]:400,[HEADER_MISMATCH_ERROR_CODE]:400};MCP_NAME_HEADER_SOURCE={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};warnedZodFallback=!1,JSON_SCHEMA_CONVERSION_TARGET="draft-2020-12";DATETIME_FRACTION_DIGITS=/\\\.\\d\{(\d+)\}/;ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);ROOT_KEYS=new Set(["$schema",...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]),PROPERTY_KEYS_BY_TYPE={string:shapeKeys([StringSchemaSchema,UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema,LegacyTitledEnumSchemaSchema]),number:shapeKeys([NumberSchemaSchema]),integer:shapeKeys([NumberSchemaSchema]),boolean:shapeKeys([BooleanSchemaSchema]),array:shapeKeys([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema])},SUPPORTED_STRING_FORMATS=new Set(StringSchemaSchema.shape.format.unwrap().options);inputRequired=Object.assign(buildInputRequired,{elicit(params){try{return{method:"elicitation/create",params:normalizeElicitInputParams(params)}}catch(error3){throw error3 instanceof ProtocolError?new TypeError(error3.message,{cause:error3}):error3}},elicitUrl(params){return{method:"elicitation/create",params:{...params,mode:"url"}}},createMessage(params){return{method:"sampling/createMessage",params}},listRoots(){return{method:"roots/list"}}});REQUEST_STATE_ONLY_LEG_PACING_MS=250;SPEC_SCHEMA_KEYS=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],authSchemas={IdJagTokenExchangeResponseSchema,OAuthClientInformationFullSchema,OAuthClientInformationSchema,OAuthClientMetadataSchema,OAuthClientRegistrationErrorSchema,OAuthErrorResponseSchema,OAuthMetadataSchema,OAuthProtectedResourceMetadataSchema,OAuthTokenRevocationRequestSchema,OAuthTokensSchema,OpenIdProviderDiscoveryMetadataSchema,OpenIdProviderMetadataSchema},_specTypeSchemas={},_isSpecType={};for(let key of SPEC_SCHEMA_KEYS)register(key,schemas_exports2[key]);for(let[key,schema2]of Object.entries(authSchemas))register(key,schema2);specTypeSchemas=Object.freeze(_specTypeSchemas),isSpecType=Object.freeze(_isSpecType);DEFAULT_REQUEST_TIMEOUT_MSEC=6e4,RESERVED_ENVELOPE_META_KEYS=[PROTOCOL_VERSION_META_KEY,CLIENT_INFO_META_KEY,CLIENT_CAPABILITIES_META_KEY,LOG_LEVEL_META_KEY],RETRY_PARAMS_KEYS=["inputResponses","requestState"];NO_REQUEST_STATE=requestStateAccessor(void 0);Protocol=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{writeNegotiatedProtocolVersion=(instance,version2)=>{instance._negotiatedProtocolVersion=version2}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(_options){this._options=_options,this._supportedProtocolVersions=_options?.supportedProtocolVersions??SUPPORTED_PROTOCOL_VERSIONS,this.setNotificationHandler("notifications/cancelled",notification=>{this._oncancel(notification)}),this.setNotificationHandler("notifications/progress",notification=>{this._onprogress(notification)}),this.setRequestHandler("ping",_request=>({}))}_shouldDropInbound(_message){}_outboundMetaEnvelope(){}_envelopeOutbound(message){let envelope=this._outboundMetaEnvelope();if(envelope===void 0)return message;let params=message.params??{};return{...message,params:{...params,_meta:{...envelope,...params._meta}}}}_resolveNonCompleteResult(decoded,flow){return Promise.reject(new SdkError(SdkErrorCode.UnsupportedResultType,`Unsupported result type '${decoded.kind}' for ${flow.request.method}`,{resultType:decoded.kind,method:flow.request.method}))}_getRequestHandler(method){return this._requestHandlers.get(method)}async _oncancel(notification){notification.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),new SdkError(SdkErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);info&&(clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId))}async connect(transport){this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{try{_onclose?.()}finally{this._onclose()}};let _onerror=this.transport?.onerror;this._transport.onerror=error3=>{_onerror?.(error3),this._onerror(error3)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?this._onresponse(message):isJSONRPCRequest(message)?this._onrequest(message,extra):isJSONRPCNotification(message)?this._onnotification(message,extra):this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))},transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let info of this._timeoutInfo.values())clearTimeout(info.timeoutId);this._timeoutInfo.clear();let requestHandlerAbortControllers=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let error3=new SdkError(SdkErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let handler of responseHandlers.values())handler(error3);for(let controller of requestHandlerAbortControllers.values())controller.abort(error3)}}_onerror(error3){this.onerror?.(error3)}_onnotification(rawNotification,extra){let{message:notification}=liftWireOnlyMaterial(rawNotification,"notification"),codec=this._negotiatedWireCodec();if(extra?.classification===void 0&&this._shouldDropInbound(rawNotification)==="drop")return;if(extra?.classification!==void 0){let classified=classifiedWireEra(extra.classification);if(classified!==codec.era){this._onerror(new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`));return}}if(isSpecNotificationMethod(notification.method)&&!codec.hasNotificationMethod(notification.method))return;let handler=this._notificationHandlers.get(notification.method),fallback=this.fallbackNotificationHandler;handler===void 0&&fallback===void 0||Promise.resolve().then(()=>handler===void 0?fallback(notification):handler(notification,codec)).catch(error3=>this._onerror(new Error(`Uncaught error in notification handler: ${error3}`)))}_onrequest(rawRequest,extra){let{message:request,lifted}=liftWireOnlyMaterial(rawRequest,"request"),codec=this._negotiatedWireCodec();if(extra?.classification===void 0&&this._shouldDropInbound(rawRequest)==="drop"){this._onerror(new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`));return}let capturedTransport=this._transport,sendErrorResponse=(code,message,data)=>{let errorResponse={jsonrpc:"2.0",id:request.id,error:{code,message,...data!==void 0&&{data}}};capturedTransport?.send(errorResponse).catch(error3=>this._onerror(new Error(`Failed to send an error response: ${error3}`)))};if(extra?.classification!==void 0){let classified=classifiedWireEra(extra.classification);if(classified!==codec.era){this._onerror(new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`));let requested=extra.classification.revision??classified;sendErrorResponse(ProtocolErrorCode.UnsupportedProtocolVersion,`Unsupported protocol version: ${requested}`,{supported:this._supportedProtocolVersions,requested});return}}if(isSpecRequestMethod(request.method)&&!codec.hasRequestMethod(request.method)&&!(isExtensionReusedRequestMethod(request.method)&&this._customSchemaRequestMethods.has(request.method))){sendErrorResponse(ProtocolErrorCode.MethodNotFound,"Method not found");return}let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler;if(handler===void 0){sendErrorResponse(ProtocolErrorCode.MethodNotFound,"Method not found");return}let envelopeError=codec.checkInboundEnvelope(lifted);if(envelopeError!==void 0){sendErrorResponse(ProtocolErrorCode.InvalidParams,envelopeError);return}let sendNotification=(notification,options)=>this._notificationViaCodec(this._resolveOutboundCodec(notification.method),notification,{...options,relatedRequestId:request.id}),sendRequest=(r,resultSchema,options)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method),r,resultSchema,{...options,relatedRequestId:request.id}),abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let partitionedInputResponses=lifted.inputResponses===void 0?void 0:partitionInputResponses(lifted.inputResponses),baseCtx={sessionId:capturedTransport?.sessionId,mcpReq:{id:request.id,method:request.method,_meta:request.params?._meta,...lifted.envelope!==void 0&&{envelope:lifted.envelope},...partitionedInputResponses!==void 0&&{inputResponses:partitionedInputResponses.accepted},...partitionedInputResponses!==void 0&&partitionedInputResponses.droppedKeys.length>0&&{droppedInputResponseKeys:partitionedInputResponses.droppedKeys},requestState:lifted.requestState===void 0?NO_REQUEST_STATE:requestStateAccessor(lifted.requestState),signal:abortController.signal,send:((r,schemaOrOptions,maybeOptions)=>{let sendCodec=this._resolveOutboundCodec(r.method);if(this._assertOutboundRequestInEra(sendCodec,r.method),isStandardSchema(schemaOrOptions))return sendRequest(r,schemaOrOptions,maybeOptions);let validate2=codecResultValidator(sendCodec,r.method);if(validate2===void 0)throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return sendRequest(r,validate2,schemaOrOptions)}),notify:sendNotification},http:extra?.authInfo?{authInfo:extra.authInfo}:void 0},ctx=this.buildContext(baseCtx,extra);Promise.resolve().then(()=>handler(request,ctx)).then(async result=>{if(abortController.signal.aborted)return;let encoded;try{encoded=codec.encodeResult(request.method,result,this._outboundServerInfo())}catch(error3){this._onerror(new Error(`Failed to encode result for ${request.method}: ${error3}`)),sendErrorResponse(ProtocolErrorCode.InternalError,"Internal error");return}let response={result:encoded,jsonrpc:"2.0",id:request.id};await capturedTransport?.send(response)},async error3=>{if(abortController.signal.aborted)return;let thrownCode=Number.isSafeInteger(error3.code)?error3.code:ProtocolErrorCode.InternalError,errorResponse={jsonrpc:"2.0",id:request.id,error:{code:codec.encodeErrorCode(thrownCode),message:error3.message??"Internal error",...error3.data!==void 0&&{data:error3.data}}};await capturedTransport?.send(errorResponse)}).catch(error3=>this._onerror(new Error(`Failed to send response: ${error3}`))).finally(()=>{this._requestHandlerAbortControllers.get(request.id)===abortController&&this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error3){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error3);return}handler(params)}_onresponse(response){let messageId=Number(response.id),handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId),this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response)?handler(response):handler(ProtocolError.fromError(response.error.code,response.error.message,response.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(request,schemaOrOptions,maybeOptions){let codec=this._resolveOutboundCodec(request.method);if(isStandardSchema(schemaOrOptions))return isExtensionReusedRequestMethod(request.method)||this._assertOutboundRequestInEra(codec,request.method),this._requestWithSchemaViaCodec(codec,request,schemaOrOptions,maybeOptions);this._assertOutboundRequestInEra(codec,request.method);let validate2=codecResultValidator(codec,request.method);if(validate2===void 0)throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(codec,request,validate2,schemaOrOptions)}_negotiatedWireCodec(){return codecForVersion(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(method){if(this._negotiatedProtocolVersion===void 0){let pinned=bootstrapOutboundCodec(method);if(pinned)return pinned}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(codec,method){if(isSpecRequestMethod(method)&&!codec.hasRequestMethod(method))throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,{method,era:codec.era})}_requestWithSchema(request,resultSchema,options){let codec=this._resolveOutboundCodec(request.method);return this._assertOutboundRequestInEra(codec,request.method),this._requestWithSchemaViaCodec(codec,request,resultSchema,options)}_requestWithSchemaViaCodec(codec,request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,headers}=options??{},flowStartedAt=Date.now(),onAbort,cleanupMessageId;return new Promise((resolve,reject)=>{let earlyReject=error3=>{reject(error3)};if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method)}catch(error3){earlyReject(error3);return}if(options?.signal?.aborted){let reason=options.signal.reason;throw reason instanceof SdkError?reason:new SdkError(SdkErrorCode.RequestTimeout,String(reason))}let requestAbort=codec.era===MODERN_WIRE_REVISION&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,messageId=this._requestMessageId++;cleanupMessageId=messageId;let jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};options?.onprogress&&(this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta,progressToken:messageId}});let outbound=this._envelopeOutbound(jsonrpcRequest),responseReceived=!1,cancel=reason=>{responseReceived||(this._progressHandlers.delete(messageId),requestAbort===void 0?request.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}}),{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error3=>this._onerror(new Error(`Failed to send cancellation: ${error3}`))):requestAbort.abort(),reject(reason instanceof SdkError?reason:new SdkError(SdkErrorCode.RequestTimeout,String(reason))))};this._responseHandlers.set(messageId,response=>{if(options?.signal?.aborted)return;if(responseReceived=!0,response instanceof Error)return reject(response);let decoded;try{decoded=codec.decodeResult(request.method,response.result)}catch(error3){return reject(error3 instanceof Error?error3:new Error(String(error3)))}if(decoded.kind==="invalid")return reject(decoded.error);if(decoded.kind==="input_required"){if(options?.allowInputRequired===!0)return resolve(manualInputRequiredValue(decoded));let flow={codec,request,resultSchema,options,flowStartedAt,retry:(params,legOptions)=>this._requestWithSchemaViaCodec(codec,params===void 0?{method:request.method}:{method:request.method,params},resultSchema,legOptions)};return resolve(this._resolveNonCompleteResult(decoded,flow))}let result=decoded.result;validateStandardSchema(resultSchema,result).then(parseResult=>{parseResult.success?resolve(parseResult.data):reject(new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${request.method}: ${parseResult.error}`))},reject)}),onAbort=()=>cancel(options?.signal?.reason),options?.signal?.addEventListener("abort",onAbort,{once:!0});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=()=>cancel(new SdkError(SdkErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1),this._transport.send(outbound,{relatedRequestId,resumptionToken,onresumptiontoken,headers,requestSignal:requestAbort?.signal}).catch(error3=>{this._progressHandlers.delete(messageId),reject(error3)})}).finally(()=>{onAbort&&options?.signal?.removeEventListener("abort",onAbort),cleanupMessageId!==void 0&&(this._responseHandlers.delete(cleanupMessageId),this._cleanupTimeout(cleanupMessageId))})}async notification(notification,options){return await this._notificationViaCodec(this._resolveOutboundCodec(notification.method),notification,options)}async _notificationViaCodec(codec,notification,options){if(!this._transport)throw new SdkError(SdkErrorCode.NotConnected,"Not connected");if(isSpecNotificationMethod(notification.method)&&!codec.hasNotificationMethod(notification.method))throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,{method:notification.method,era:codec.era});this.assertNotificationCapability(notification.method);let jsonrpcNotification=this._envelopeOutbound({jsonrpc:"2.0",...notification});if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&options?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(notification.method),this._transport&&this._transport?.send(jsonrpcNotification,options).catch(error3=>this._onerror(error3))});return}await this._transport.send(jsonrpcNotification,options)}setRequestHandler(method,schemasOrHandler,maybeHandler){this.assertRequestHandlerCapability(method);let stored;if(typeof schemasOrHandler=="function"){if(!isSpecRequestMethod(method))throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);stored=(request,ctx)=>{let dispatchCodec=this._negotiatedWireCodec(),outcome=dispatchCodec.validateRequest(method,request);if(!outcome.ok&&outcome.reason==="not-in-era"&&(outcome=dispatchCodec.validateInputRequest(method,request)),!outcome.ok)throw outcome.reason==="not-in-era"?new ProtocolError(ProtocolErrorCode.InternalError,`No wire schema for ${method} in the resolved era`):new Error(outcome.message);return Promise.resolve(schemasOrHandler(outcome.value,ctx))}}else if(maybeHandler)stored=async(request,ctx)=>{let parsed=await validateStandardSchema(schemasOrHandler.params,{...request.params});if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params for ${method}: ${parsed.error}`);return maybeHandler(parsed.data,ctx)};else throw new TypeError("setRequestHandler: handler is required");typeof schemasOrHandler=="function"?this._customSchemaRequestMethods.delete(method):this._customSchemaRequestMethods.add(method),this._requestHandlers.set(method,this._wrapHandler(method,stored))}_wrapHandler(_method,handler){return handler}_outboundServerInfo(){}removeRequestHandler(method){this._requestHandlers.delete(method),this._customSchemaRequestMethods.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw new Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(method,schemasOrHandler,maybeHandler){if(typeof schemasOrHandler=="function"){if(!isSpecNotificationMethod(method))throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(method,(notification,codec)=>{let outcome=codec.validateNotification(method,notification);if(!outcome.ok)throw outcome.reason==="not-in-era"?new ProtocolError(ProtocolErrorCode.InternalError,`No wire schema for ${method} in the resolved era`):new Error(outcome.message);return Promise.resolve(schemasOrHandler(outcome.value))});return}if(!maybeHandler)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(method,async notification=>{let parsed=await validateStandardSchema(schemasOrHandler.params,{...notification.params});if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params for notification ${method}: ${parsed.error}`);await maybeHandler(parsed.data,notification)})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}};require_content_type=__commonJSMin((exports=>{var PARAM_REGEXP=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,QESC_REGEXP=/\\([\u000b\u0020-\u00ff])/g,TYPE_REGEXP=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;exports.parse=parse3;function parse3(string4){if(!string4)throw new TypeError("argument string is required");var header=typeof string4=="object"?getcontenttype(string4):string4;if(typeof header!="string")throw new TypeError("argument string is required to be a string");var index=header.indexOf(";"),type=index!==-1?header.slice(0,index).trim():header.trim();if(!TYPE_REGEXP.test(type))throw new TypeError("invalid media type");var obj=new ContentType(type.toLowerCase());if(index!==-1){var key,match2,value;for(PARAM_REGEXP.lastIndex=index;match2=PARAM_REGEXP.exec(header);){if(match2.index!==index)throw new TypeError("invalid parameter format");index+=match2[0].length,key=match2[1].toLowerCase(),value=match2[2],value.charCodeAt(0)===34&&(value=value.slice(1,-1),value.indexOf("\\")!==-1&&(value=value.replace(QESC_REGEXP,"$1"))),obj.parameters[key]=value}if(index!==header.length)throw new TypeError("invalid parameter format")}return obj}function getcontenttype(obj){var header;if(typeof obj.getHeader=="function"?header=obj.getHeader("content-type"):typeof obj.headers=="object"&&(header=obj.headers&&obj.headers["content-type"]),typeof header!="string")throw new TypeError("content-type header is missing from object");return header}function ContentType(type){this.parameters=Object.create(null),this.type=type}})),import_content_type=__toESM(require_content_type(),1);STDIO_DEFAULT_MAX_BUFFER_SIZE=10*1024*1024,TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;MAX_TEMPLATE_LENGTH=1e6,MAX_VARIABLE_LENGTH=1e6,MAX_TEMPLATE_EXPRESSIONS=1e4,MAX_REGEX_LENGTH=1e6,UriTemplate=class UriTemplate2{static isTemplate(str){return/\{[^}\s]+\}/.test(str)}static validateLength(str,max,context){if(str.length>max)throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`)}template;parts;get variableNames(){return this.parts.flatMap(part=>typeof part=="string"?[]:part.names)}constructor(template){UriTemplate2.validateLength(template,MAX_TEMPLATE_LENGTH,"Template"),this.template=template,this.parts=this.parse(template)}toString(){return this.template}parse(template){let parts=[],currentText="",i=0,expressionCount=0;for(;i<template.length;)if(template[i]==="{"){currentText&&(parts.push(currentText),currentText="");let end=template.indexOf("}",i);if(end===-1)throw new Error("Unclosed template expression");if(expressionCount++,expressionCount>MAX_TEMPLATE_EXPRESSIONS)throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);let expr=template.slice(i+1,end),operator=this.getOperator(expr),exploded=expr.includes("*"),names=this.getNames(expr),name=names[0];for(let name$1 of names)UriTemplate2.validateLength(name$1,MAX_VARIABLE_LENGTH,"Variable name");parts.push({name,operator,names,exploded}),i=end+1}else currentText+=template[i],i++;return currentText&&parts.push(currentText),parts}getOperator(expr){return["+","#",".","/","?","&"].find(op=>expr.startsWith(op))||""}getNames(expr){let operator=this.getOperator(expr);return expr.slice(operator.length).split(",").map(name=>name.replace("*","").trim()).filter(name=>name.length>0)}encodeValue(value,operator){return UriTemplate2.validateLength(value,MAX_VARIABLE_LENGTH,"Variable value"),operator==="+"||operator==="#"?encodeURI(value):encodeURIComponent(value)}expandPart(part,variables){if(part.operator==="?"||part.operator==="&"){let pairs=part.names.map(name=>{let value$1=variables[name];return value$1===void 0?"":`${name}=${Array.isArray(value$1)?value$1.map(v=>this.encodeValue(v,part.operator)).join(","):this.encodeValue(value$1.toString(),part.operator)}`}).filter(pair=>pair.length>0);return pairs.length===0?"":(part.operator==="?"?"?":"&")+pairs.join("&")}if(part.names.length>1){let values=part.names.map(name=>variables[name]).filter(v=>v!==void 0);return values.length===0?"":values.map(v=>Array.isArray(v)?v[0]:v).join(",")}let value=variables[part.name];if(value===void 0)return"";let encoded=(Array.isArray(value)?value:[value]).map(v=>this.encodeValue(v,part.operator));switch(part.operator){case"":return encoded.join(",");case"+":return encoded.join(",");case"#":return"#"+encoded.join(",");case".":return"."+encoded.join(".");case"/":return"/"+encoded.join("/");default:return encoded.join(",")}}expand(variables){let result="",hasQueryParam=!1;for(let part of this.parts){if(typeof part=="string"){result+=part;continue}let expanded=this.expandPart(part,variables);expanded&&(result+=(part.operator==="?"||part.operator==="&")&&hasQueryParam?expanded.replace("?","&"):expanded,(part.operator==="?"||part.operator==="&")&&(hasQueryParam=!0))}return result}escapeRegExp(str){return str.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(part){let patterns=[];for(let name$1 of part.names)UriTemplate2.validateLength(name$1,MAX_VARIABLE_LENGTH,"Variable name");if(part.operator==="?"||part.operator==="&"){for(let i=0;i<part.names.length;i++){let name$1=part.names[i],prefix=i===0?"\\"+part.operator:"&";patterns.push({pattern:prefix+this.escapeRegExp(name$1)+"=([^&]+)",name:name$1})}return patterns}let pattern,name=part.name;switch(part.operator){case"":pattern=part.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":pattern="(.+)";break;case".":pattern=String.raw`\.([^/,]+)`;break;case"/":pattern="/"+(part.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:pattern="([^/]+)"}return patterns.push({pattern,name}),patterns}match(uri){UriTemplate2.validateLength(uri,MAX_TEMPLATE_LENGTH,"URI");let pattern="^",names=[];for(let part of this.parts)if(typeof part=="string")pattern+=this.escapeRegExp(part);else{let patterns=this.partToRegExp(part);for(let{pattern:partPattern,name}of patterns)pattern+=partPattern,names.push({name,exploded:part.exploded})}pattern+="$",UriTemplate2.validateLength(pattern,MAX_REGEX_LENGTH,"Generated regex pattern");let regex=new RegExp(pattern),match2=uri.match(regex);if(!match2)return null;let result={};for(let[i,name_]of names.entries()){let{name,exploded}=name_,value=match2[i+1],cleanName=name.replace("*","");result[cleanName]=exploded&&value.includes(",")?value.split(","):value}return result}}}});function createDefaultAjvInstance(engineClass){let ajv=new engineClass({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return addFormats(ajv),ajv}var require_code$1,require_scope,require_codegen,require_util,require_names,require_errors,require_boolSchema,require_rules,require_applicability,require_dataType,require_defaults,require_code,require_keyword,require_subschema,require_fast_deep_equal,require_json_schema_traverse,require_resolve,require_validate,require_validation_error,require_ref_error,require_compile,require_data,require_utils,require_schemes,require_fast_uri,require_uri,require_core$3,require_id,require_ref,require_core$2,require_limitNumber,require_multipleOf,require_ucs2length,require_limitLength,require_pattern,require_limitProperties,require_required,require_limitItems,require_equal,require_uniqueItems,require_const,require_enum,require_validation$2,require_additionalItems,require_items,require_prefixItems,require_items2020,require_contains,require_dependencies,require_propertyNames,require_additionalProperties,require_properties,require_patternProperties,require_not,require_anyOf,require_oneOf,require_allOf,require_if,require_thenElse,require_applicator$2,require_format$2,require_format$1,require_metadata,require_draft7,require_types,require_discriminator,require_json_schema_draft_07,require_ajv,require_dynamicAnchor,require_dynamicRef,require_recursiveAnchor,require_recursiveRef,require_dynamic,require_dependentRequired,require_dependentSchemas,require_limitContains,require_next,require_unevaluatedProperties,require_unevaluatedItems,require_unevaluated$1,require_schema$1,require_applicator$1,require_content$1,require_core$1,require_format,require_meta_data$1,require_validation$1,require_json_schema_2019_09,require__2019,require_draft2020,require_schema,require_applicator,require_unevaluated,require_content,require_core,require_format_annotation,require_meta_data,require_validation,require_json_schema_2020_12,require__2020,require_formats,require_limit,require_dist,import_ajv,import__2019,import__2020,import_dist,addFormats,AjvJsonSchemaValidator,Ajv,init_ajvProvider_CEoC_sr=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs"(){"use strict";init_chunk_Br0eD_fh();init_dialects_DoSzNhcb();require_code$1=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.regexpCode=exports.getEsmExportName=exports.getProperty=exports.safeStringify=exports.stringify=exports.strConcat=exports.addCodeArg=exports.str=exports._=exports.nil=exports._Code=exports.Name=exports.IDENTIFIER=exports._CodeOrName=void 0;var _CodeOrName=class{};exports._CodeOrName=_CodeOrName,exports.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Name=class extends _CodeOrName{constructor(s){if(super(),!exports.IDENTIFIER.test(s))throw new Error("CodeGen: name must be a valid identifier");this.str=s}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};exports.Name=Name;var _Code=class extends _CodeOrName{constructor(code){super(),this._items=typeof code=="string"?[code]:code}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let item=this._items[0];return item===""||item==='""'}get str(){var _a3;return(_a3=this._str)!==null&&_a3!==void 0?_a3:this._str=this._items.reduce((s,c)=>`${s}${c}`,"")}get names(){var _a3;return(_a3=this._names)!==null&&_a3!==void 0?_a3:this._names=this._items.reduce((names,c)=>(c instanceof Name&&(names[c.str]=(names[c.str]||0)+1),names),{})}};exports._Code=_Code,exports.nil=new _Code("");function _(strs,...args){let code=[strs[0]],i=0;for(;i<args.length;)addCodeArg(code,args[i]),code.push(strs[++i]);return new _Code(code)}exports._=_;let plus=new _Code("+");function str(strs,...args){let expr=[safeStringify(strs[0])],i=0;for(;i<args.length;)expr.push(plus),addCodeArg(expr,args[i]),expr.push(plus,safeStringify(strs[++i]));return optimize(expr),new _Code(expr)}exports.str=str;function addCodeArg(code,arg){arg instanceof _Code?code.push(...arg._items):arg instanceof Name?code.push(arg):code.push(interpolate(arg))}exports.addCodeArg=addCodeArg;function optimize(expr){let i=1;for(;i<expr.length-1;){if(expr[i]===plus){let res=mergeExprItems(expr[i-1],expr[i+1]);if(res!==void 0){expr.splice(i-1,3,res);continue}expr[i++]="+"}i++}}function mergeExprItems(a,b){if(b==='""')return a;if(a==='""')return b;if(typeof a=="string")return b instanceof Name||a[a.length-1]!=='"'?void 0:typeof b!="string"?`${a.slice(0,-1)}${b}"`:b[0]==='"'?a.slice(0,-1)+b.slice(1):void 0;if(typeof b=="string"&&b[0]==='"'&&!(a instanceof Name))return`"${a}${b.slice(1)}`}function strConcat(c1,c2){return c2.emptyStr()?c1:c1.emptyStr()?c2:str`${c1}${c2}`}exports.strConcat=strConcat;function interpolate(x){return typeof x=="number"||typeof x=="boolean"||x===null?x:safeStringify(Array.isArray(x)?x.join(","):x)}function stringify(x){return new _Code(safeStringify(x))}exports.stringify=stringify;function safeStringify(x){return JSON.stringify(x).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}exports.safeStringify=safeStringify;function getProperty(key){return typeof key=="string"&&exports.IDENTIFIER.test(key)?new _Code(`.${key}`):_`[${key}]`}exports.getProperty=getProperty;function getEsmExportName(key){if(typeof key=="string"&&exports.IDENTIFIER.test(key))return new _Code(`${key}`);throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)}exports.getEsmExportName=getEsmExportName;function regexpCode(rx){return new _Code(rx.toString())}exports.regexpCode=regexpCode})),require_scope=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.ValueScope=exports.ValueScopeName=exports.Scope=exports.varKinds=exports.UsedValueState=void 0;let code_1=require_code$1();var ValueError=class extends Error{constructor(name){super(`CodeGen: "code" for ${name} not defined`),this.value=name.value}},UsedValueState;(function(UsedValueState2){UsedValueState2[UsedValueState2.Started=0]="Started",UsedValueState2[UsedValueState2.Completed=1]="Completed"})(UsedValueState||(exports.UsedValueState=UsedValueState={})),exports.varKinds={const:new code_1.Name("const"),let:new code_1.Name("let"),var:new code_1.Name("var")};var Scope=class{constructor({prefixes,parent}={}){this._names={},this._prefixes=prefixes,this._parent=parent}toName(nameOrPrefix){return nameOrPrefix instanceof code_1.Name?nameOrPrefix:this.name(nameOrPrefix)}name(prefix){return new code_1.Name(this._newName(prefix))}_newName(prefix){let ng=this._names[prefix]||this._nameGroup(prefix);return`${prefix}${ng.index++}`}_nameGroup(prefix){var _a3,_b;if(!((_b=(_a3=this._parent)===null||_a3===void 0?void 0:_a3._prefixes)===null||_b===void 0)&&_b.has(prefix)||this._prefixes&&!this._prefixes.has(prefix))throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);return this._names[prefix]={prefix,index:0}}};exports.Scope=Scope;var ValueScopeName=class extends code_1.Name{constructor(prefix,nameStr){super(nameStr),this.prefix=prefix}setValue(value,{property,itemIndex}){this.value=value,this.scopePath=(0,code_1._)`.${new code_1.Name(property)}[${itemIndex}]`}};exports.ValueScopeName=ValueScopeName;let line=(0,code_1._)`\n`;var ValueScope=class extends Scope{constructor(opts){super(opts),this._values={},this._scope=opts.scope,this.opts={...opts,_n:opts.lines?line:code_1.nil}}get(){return this._scope}name(prefix){return new ValueScopeName(prefix,this._newName(prefix))}value(nameOrPrefix,value){var _a3;if(value.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let name=this.toName(nameOrPrefix),{prefix}=name,valueKey=(_a3=value.key)!==null&&_a3!==void 0?_a3:value.ref,vs=this._values[prefix];if(vs){let _name=vs.get(valueKey);if(_name)return _name}else vs=this._values[prefix]=new Map;vs.set(valueKey,name);let s=this._scope[prefix]||(this._scope[prefix]=[]),itemIndex=s.length;return s[itemIndex]=value.ref,name.setValue(value,{property:prefix,itemIndex}),name}getValue(prefix,keyOrRef){let vs=this._values[prefix];if(vs)return vs.get(keyOrRef)}scopeRefs(scopeName,values=this._values){return this._reduceValues(values,name=>{if(name.scopePath===void 0)throw new Error(`CodeGen: name "${name}" has no value`);return(0,code_1._)`${scopeName}${name.scopePath}`})}scopeCode(values=this._values,usedValues,getCode){return this._reduceValues(values,name=>{if(name.value===void 0)throw new Error(`CodeGen: name "${name}" has no value`);return name.value.code},usedValues,getCode)}_reduceValues(values,valueCode,usedValues={},getCode){let code=code_1.nil;for(let prefix in values){let vs=values[prefix];if(!vs)continue;let nameSet=usedValues[prefix]=usedValues[prefix]||new Map;vs.forEach(name=>{if(nameSet.has(name))return;nameSet.set(name,UsedValueState.Started);let c=valueCode(name);if(c){let def=this.opts.es5?exports.varKinds.var:exports.varKinds.const;code=(0,code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`}else if(c=getCode?.(name))code=(0,code_1._)`${code}${c}${this.opts._n}`;else throw new ValueError(name);nameSet.set(name,UsedValueState.Completed)})}return code}};exports.ValueScope=ValueScope})),require_codegen=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.or=exports.and=exports.not=exports.CodeGen=exports.operators=exports.varKinds=exports.ValueScopeName=exports.ValueScope=exports.Scope=exports.Name=exports.regexpCode=exports.stringify=exports.getProperty=exports.nil=exports.strConcat=exports.str=exports._=void 0;let code_1=require_code$1(),scope_1=require_scope();var code_2=require_code$1();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return code_2._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return code_2.str}}),Object.defineProperty(exports,"strConcat",{enumerable:!0,get:function(){return code_2.strConcat}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return code_2.nil}}),Object.defineProperty(exports,"getProperty",{enumerable:!0,get:function(){return code_2.getProperty}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return code_2.stringify}}),Object.defineProperty(exports,"regexpCode",{enumerable:!0,get:function(){return code_2.regexpCode}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return code_2.Name}});var scope_2=require_scope();Object.defineProperty(exports,"Scope",{enumerable:!0,get:function(){return scope_2.Scope}}),Object.defineProperty(exports,"ValueScope",{enumerable:!0,get:function(){return scope_2.ValueScope}}),Object.defineProperty(exports,"ValueScopeName",{enumerable:!0,get:function(){return scope_2.ValueScopeName}}),Object.defineProperty(exports,"varKinds",{enumerable:!0,get:function(){return scope_2.varKinds}}),exports.operators={GT:new code_1._Code(">"),GTE:new code_1._Code(">="),LT:new code_1._Code("<"),LTE:new code_1._Code("<="),EQ:new code_1._Code("==="),NEQ:new code_1._Code("!=="),NOT:new code_1._Code("!"),OR:new code_1._Code("||"),AND:new code_1._Code("&&"),ADD:new code_1._Code("+")};var Node5=class{optimizeNodes(){return this}optimizeNames(_names,_constants){return this}},Def=class extends Node5{constructor(varKind,name,rhs){super(),this.varKind=varKind,this.name=name,this.rhs=rhs}render({es5,_n}){let varKind=es5?scope_1.varKinds.var:this.varKind,rhs=this.rhs===void 0?"":` = ${this.rhs}`;return`${varKind} ${this.name}${rhs};`+_n}optimizeNames(names,constants){if(names[this.name.str])return this.rhs&&(this.rhs=optimizeExpr(this.rhs,names,constants)),this}get names(){return this.rhs instanceof code_1._CodeOrName?this.rhs.names:{}}},Assign=class extends Node5{constructor(lhs,rhs,sideEffects){super(),this.lhs=lhs,this.rhs=rhs,this.sideEffects=sideEffects}render({_n}){return`${this.lhs} = ${this.rhs};`+_n}optimizeNames(names,constants){if(!(this.lhs instanceof code_1.Name&&!names[this.lhs.str]&&!this.sideEffects))return this.rhs=optimizeExpr(this.rhs,names,constants),this}get names(){return addExprNames(this.lhs instanceof code_1.Name?{}:{...this.lhs.names},this.rhs)}},AssignOp=class extends Assign{constructor(lhs,op,rhs,sideEffects){super(lhs,rhs,sideEffects),this.op=op}render({_n}){return`${this.lhs} ${this.op}= ${this.rhs};`+_n}},Label=class extends Node5{constructor(label){super(),this.label=label,this.names={}}render({_n}){return`${this.label}:`+_n}},Break=class extends Node5{constructor(label){super(),this.label=label,this.names={}}render({_n}){return`break${this.label?` ${this.label}`:""};`+_n}},Throw=class extends Node5{constructor(error3){super(),this.error=error3}render({_n}){return`throw ${this.error};`+_n}get names(){return this.error.names}},AnyCode=class extends Node5{constructor(code){super(),this.code=code}render({_n}){return`${this.code};`+_n}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(names,constants){return this.code=optimizeExpr(this.code,names,constants),this}get names(){return this.code instanceof code_1._CodeOrName?this.code.names:{}}},ParentNode=class extends Node5{constructor(nodes=[]){super(),this.nodes=nodes}render(opts){return this.nodes.reduce((code,n)=>code+n.render(opts),"")}optimizeNodes(){let{nodes}=this,i=nodes.length;for(;i--;){let n=nodes[i].optimizeNodes();Array.isArray(n)?nodes.splice(i,1,...n):n?nodes[i]=n:nodes.splice(i,1)}return nodes.length>0?this:void 0}optimizeNames(names,constants){let{nodes}=this,i=nodes.length;for(;i--;){let n=nodes[i];n.optimizeNames(names,constants)||(subtractNames(names,n.names),nodes.splice(i,1))}return nodes.length>0?this:void 0}get names(){return this.nodes.reduce((names,n)=>addNames(names,n.names),{})}},BlockNode=class extends ParentNode{render(opts){return"{"+opts._n+super.render(opts)+"}"+opts._n}},Root=class extends ParentNode{},Else=class extends BlockNode{};Else.kind="else";var If=class If2 extends BlockNode{constructor(condition,nodes){super(nodes),this.condition=condition}render(opts){let code=`if(${this.condition})`+super.render(opts);return this.else&&(code+="else "+this.else.render(opts)),code}optimizeNodes(){super.optimizeNodes();let cond=this.condition;if(cond===!0)return this.nodes;let e=this.else;if(e){let ns=e.optimizeNodes();e=this.else=Array.isArray(ns)?new Else(ns):ns}if(e)return cond===!1?e instanceof If2?e:e.nodes:this.nodes.length?this:new If2(not(cond),e instanceof If2?[e]:e.nodes);if(!(cond===!1||!this.nodes.length))return this}optimizeNames(names,constants){var _a3;if(this.else=(_a3=this.else)===null||_a3===void 0?void 0:_a3.optimizeNames(names,constants),!!(super.optimizeNames(names,constants)||this.else))return this.condition=optimizeExpr(this.condition,names,constants),this}get names(){let names=super.names;return addExprNames(names,this.condition),this.else&&addNames(names,this.else.names),names}};If.kind="if";var For=class extends BlockNode{};For.kind="for";var ForLoop=class extends For{constructor(iteration){super(),this.iteration=iteration}render(opts){return`for(${this.iteration})`+super.render(opts)}optimizeNames(names,constants){if(super.optimizeNames(names,constants))return this.iteration=optimizeExpr(this.iteration,names,constants),this}get names(){return addNames(super.names,this.iteration.names)}},ForRange=class extends For{constructor(varKind,name,from,to){super(),this.varKind=varKind,this.name=name,this.from=from,this.to=to}render(opts){let varKind=opts.es5?scope_1.varKinds.var:this.varKind,{name,from,to}=this;return`for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)`+super.render(opts)}get names(){return addExprNames(addExprNames(super.names,this.from),this.to)}},ForIter=class extends For{constructor(loop,varKind,name,iterable){super(),this.loop=loop,this.varKind=varKind,this.name=name,this.iterable=iterable}render(opts){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(opts)}optimizeNames(names,constants){if(super.optimizeNames(names,constants))return this.iterable=optimizeExpr(this.iterable,names,constants),this}get names(){return addNames(super.names,this.iterable.names)}},Func=class extends BlockNode{constructor(name,args,async){super(),this.name=name,this.args=args,this.async=async}render(opts){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(opts)}};Func.kind="func";var Return=class extends ParentNode{render(opts){return"return "+super.render(opts)}};Return.kind="return";var Try=class extends BlockNode{render(opts){let code="try"+super.render(opts);return this.catch&&(code+=this.catch.render(opts)),this.finally&&(code+=this.finally.render(opts)),code}optimizeNodes(){var _a3,_b;return super.optimizeNodes(),(_a3=this.catch)===null||_a3===void 0||_a3.optimizeNodes(),(_b=this.finally)===null||_b===void 0||_b.optimizeNodes(),this}optimizeNames(names,constants){var _a3,_b;return super.optimizeNames(names,constants),(_a3=this.catch)===null||_a3===void 0||_a3.optimizeNames(names,constants),(_b=this.finally)===null||_b===void 0||_b.optimizeNames(names,constants),this}get names(){let names=super.names;return this.catch&&addNames(names,this.catch.names),this.finally&&addNames(names,this.finally.names),names}},Catch=class extends BlockNode{constructor(error3){super(),this.error=error3}render(opts){return`catch(${this.error})`+super.render(opts)}};Catch.kind="catch";var Finally=class extends BlockNode{render(opts){return"finally"+super.render(opts)}};Finally.kind="finally";var CodeGen=class{constructor(extScope,opts={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...opts,_n:opts.lines?`
58
+ `:""},this._extScope=extScope,this._scope=new scope_1.Scope({parent:extScope}),this._nodes=[new Root]}toString(){return this._root.render(this.opts)}name(prefix){return this._scope.name(prefix)}scopeName(prefix){return this._extScope.name(prefix)}scopeValue(prefixOrName,value){let name=this._extScope.value(prefixOrName,value);return(this._values[name.prefix]||(this._values[name.prefix]=new Set)).add(name),name}getScopeValue(prefix,keyOrRef){return this._extScope.getValue(prefix,keyOrRef)}scopeRefs(scopeName){return this._extScope.scopeRefs(scopeName,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(varKind,nameOrPrefix,rhs,constant){let name=this._scope.toName(nameOrPrefix);return rhs!==void 0&&constant&&(this._constants[name.str]=rhs),this._leafNode(new Def(varKind,name,rhs)),name}const(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.const,nameOrPrefix,rhs,_constant)}let(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.let,nameOrPrefix,rhs,_constant)}var(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.var,nameOrPrefix,rhs,_constant)}assign(lhs,rhs,sideEffects){return this._leafNode(new Assign(lhs,rhs,sideEffects))}add(lhs,rhs){return this._leafNode(new AssignOp(lhs,exports.operators.ADD,rhs))}code(c){return typeof c=="function"?c():c!==code_1.nil&&this._leafNode(new AnyCode(c)),this}object(...keyValues){let code=["{"];for(let[key,value]of keyValues)code.length>1&&code.push(","),code.push(key),(key!==value||this.opts.es5)&&(code.push(":"),(0,code_1.addCodeArg)(code,value));return code.push("}"),new code_1._Code(code)}if(condition,thenBody,elseBody){if(this._blockNode(new If(condition)),thenBody&&elseBody)this.code(thenBody).else().code(elseBody).endIf();else if(thenBody)this.code(thenBody).endIf();else if(elseBody)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(condition){return this._elseNode(new If(condition))}else(){return this._elseNode(new Else)}endIf(){return this._endBlockNode(If,Else)}_for(node2,forBody){return this._blockNode(node2),forBody&&this.code(forBody).endFor(),this}for(iteration,forBody){return this._for(new ForLoop(iteration),forBody)}forRange(nameOrPrefix,from,to,forBody,varKind=this.opts.es5?scope_1.varKinds.var:scope_1.varKinds.let){let name=this._scope.toName(nameOrPrefix);return this._for(new ForRange(varKind,name,from,to),()=>forBody(name))}forOf(nameOrPrefix,iterable,forBody,varKind=scope_1.varKinds.const){let name=this._scope.toName(nameOrPrefix);if(this.opts.es5){let arr=iterable instanceof code_1.Name?iterable:this.var("_arr",iterable);return this.forRange("_i",0,(0,code_1._)`${arr}.length`,i=>{this.var(name,(0,code_1._)`${arr}[${i}]`),forBody(name)})}return this._for(new ForIter("of",varKind,name,iterable),()=>forBody(name))}forIn(nameOrPrefix,obj,forBody,varKind=this.opts.es5?scope_1.varKinds.var:scope_1.varKinds.const){if(this.opts.ownProperties)return this.forOf(nameOrPrefix,(0,code_1._)`Object.keys(${obj})`,forBody);let name=this._scope.toName(nameOrPrefix);return this._for(new ForIter("in",varKind,name,obj),()=>forBody(name))}endFor(){return this._endBlockNode(For)}label(label){return this._leafNode(new Label(label))}break(label){return this._leafNode(new Break(label))}return(value){let node2=new Return;if(this._blockNode(node2),this.code(value),node2.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Return)}try(tryBody,catchCode,finallyCode){if(!catchCode&&!finallyCode)throw new Error('CodeGen: "try" without "catch" and "finally"');let node2=new Try;if(this._blockNode(node2),this.code(tryBody),catchCode){let error3=this.name("e");this._currNode=node2.catch=new Catch(error3),catchCode(error3)}return finallyCode&&(this._currNode=node2.finally=new Finally,this.code(finallyCode)),this._endBlockNode(Catch,Finally)}throw(error3){return this._leafNode(new Throw(error3))}block(body,nodeCount){return this._blockStarts.push(this._nodes.length),body&&this.code(body).endBlock(nodeCount),this}endBlock(nodeCount){let len=this._blockStarts.pop();if(len===void 0)throw new Error("CodeGen: not in self-balancing block");let toClose=this._nodes.length-len;if(toClose<0||nodeCount!==void 0&&toClose!==nodeCount)throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);return this._nodes.length=len,this}func(name,args=code_1.nil,async,funcBody){return this._blockNode(new Func(name,args,async)),funcBody&&this.code(funcBody).endFunc(),this}endFunc(){return this._endBlockNode(Func)}optimize(n=1){for(;n-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(node2){return this._currNode.nodes.push(node2),this}_blockNode(node2){this._currNode.nodes.push(node2),this._nodes.push(node2)}_endBlockNode(N1,N2){let n=this._currNode;if(n instanceof N1||N2&&n instanceof N2)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${N2?`${N1.kind}/${N2.kind}`:N1.kind}"`)}_elseNode(node2){let n=this._currNode;if(!(n instanceof If))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=node2,this}get _root(){return this._nodes[0]}get _currNode(){let ns=this._nodes;return ns[ns.length-1]}set _currNode(node2){let ns=this._nodes;ns[ns.length-1]=node2}};exports.CodeGen=CodeGen;function addNames(names,from){for(let n in from)names[n]=(names[n]||0)+(from[n]||0);return names}function addExprNames(names,from){return from instanceof code_1._CodeOrName?addNames(names,from.names):names}function optimizeExpr(expr,names,constants){if(expr instanceof code_1.Name)return replaceName(expr);if(!canOptimize(expr))return expr;return new code_1._Code(expr._items.reduce((items,c)=>(c instanceof code_1.Name&&(c=replaceName(c)),c instanceof code_1._Code?items.push(...c._items):items.push(c),items),[]));function replaceName(n){let c=constants[n.str];return c===void 0||names[n.str]!==1?n:(delete names[n.str],c)}function canOptimize(e){return e instanceof code_1._Code&&e._items.some(c=>c instanceof code_1.Name&&names[c.str]===1&&constants[c.str]!==void 0)}}function subtractNames(names,from){for(let n in from)names[n]=(names[n]||0)-(from[n]||0)}function not(x){return typeof x=="boolean"||typeof x=="number"||x===null?!x:(0,code_1._)`!${par(x)}`}exports.not=not;let andCode=mappend(exports.operators.AND);function and(...args){return args.reduce(andCode)}exports.and=and;let orCode=mappend(exports.operators.OR);function or(...args){return args.reduce(orCode)}exports.or=or;function mappend(op){return(x,y)=>x===code_1.nil?y:y===code_1.nil?x:(0,code_1._)`${par(x)} ${op} ${par(y)}`}function par(x){return x instanceof code_1.Name?x:(0,code_1._)`(${x})`}})),require_util=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkStrictMode=exports.getErrorPath=exports.Type=exports.useFunc=exports.setEvaluated=exports.evaluatedPropsToName=exports.mergeEvaluated=exports.eachItem=exports.unescapeJsonPointer=exports.escapeJsonPointer=exports.escapeFragment=exports.unescapeFragment=exports.schemaRefOrVal=exports.schemaHasRulesButRef=exports.schemaHasRules=exports.checkUnknownRules=exports.alwaysValidSchema=exports.toHash=void 0;let codegen_1=require_codegen(),code_1=require_code$1();function toHash(arr){let hash={};for(let item of arr)hash[item]=!0;return hash}exports.toHash=toHash;function alwaysValidSchema(it,schema2){return typeof schema2=="boolean"?schema2:Object.keys(schema2).length===0?!0:(checkUnknownRules(it,schema2),!schemaHasRules(schema2,it.self.RULES.all))}exports.alwaysValidSchema=alwaysValidSchema;function checkUnknownRules(it,schema2=it.schema){let{opts,self}=it;if(!opts.strictSchema||typeof schema2=="boolean")return;let rules=self.RULES.keywords;for(let key in schema2)rules[key]||checkStrictMode(it,`unknown keyword: "${key}"`)}exports.checkUnknownRules=checkUnknownRules;function schemaHasRules(schema2,rules){if(typeof schema2=="boolean")return!schema2;for(let key in schema2)if(rules[key])return!0;return!1}exports.schemaHasRules=schemaHasRules;function schemaHasRulesButRef(schema2,RULES){if(typeof schema2=="boolean")return!schema2;for(let key in schema2)if(key!=="$ref"&&RULES.all[key])return!0;return!1}exports.schemaHasRulesButRef=schemaHasRulesButRef;function schemaRefOrVal({topSchemaRef,schemaPath},schema2,keyword,$data){if(!$data){if(typeof schema2=="number"||typeof schema2=="boolean")return schema2;if(typeof schema2=="string")return(0,codegen_1._)`${schema2}`}return(0,codegen_1._)`${topSchemaRef}${schemaPath}${(0,codegen_1.getProperty)(keyword)}`}exports.schemaRefOrVal=schemaRefOrVal;function unescapeFragment(str){return unescapeJsonPointer(decodeURIComponent(str))}exports.unescapeFragment=unescapeFragment;function escapeFragment(str){return encodeURIComponent(escapeJsonPointer(str))}exports.escapeFragment=escapeFragment;function escapeJsonPointer(str){return typeof str=="number"?`${str}`:str.replace(/~/g,"~0").replace(/\//g,"~1")}exports.escapeJsonPointer=escapeJsonPointer;function unescapeJsonPointer(str){return str.replace(/~1/g,"/").replace(/~0/g,"~")}exports.unescapeJsonPointer=unescapeJsonPointer;function eachItem(xs,f){if(Array.isArray(xs))for(let x of xs)f(x);else f(xs)}exports.eachItem=eachItem;function makeMergeEvaluated({mergeNames,mergeToName,mergeValues:mergeValues2,resultToName}){return(gen,from,to,toName)=>{let res=to===void 0?from:to instanceof codegen_1.Name?(from instanceof codegen_1.Name?mergeNames(gen,from,to):mergeToName(gen,from,to),to):from instanceof codegen_1.Name?(mergeToName(gen,to,from),from):mergeValues2(from,to);return toName===codegen_1.Name&&!(res instanceof codegen_1.Name)?resultToName(gen,res):res}}exports.mergeEvaluated={props:makeMergeEvaluated({mergeNames:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true && ${from} !== undefined`,()=>{gen.if((0,codegen_1._)`${from} === true`,()=>gen.assign(to,!0),()=>gen.assign(to,(0,codegen_1._)`${to} || {}`).code((0,codegen_1._)`Object.assign(${to}, ${from})`))}),mergeToName:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true`,()=>{from===!0?gen.assign(to,!0):(gen.assign(to,(0,codegen_1._)`${to} || {}`),setEvaluated(gen,to,from))}),mergeValues:(from,to)=>from===!0?!0:{...from,...to},resultToName:evaluatedPropsToName}),items:makeMergeEvaluated({mergeNames:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true && ${from} !== undefined`,()=>gen.assign(to,(0,codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),mergeToName:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true`,()=>gen.assign(to,from===!0?!0:(0,codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),mergeValues:(from,to)=>from===!0?!0:Math.max(from,to),resultToName:(gen,items)=>gen.var("items",items)})};function evaluatedPropsToName(gen,ps){if(ps===!0)return gen.var("props",!0);let props=gen.var("props",(0,codegen_1._)`{}`);return ps!==void 0&&setEvaluated(gen,props,ps),props}exports.evaluatedPropsToName=evaluatedPropsToName;function setEvaluated(gen,props,ps){Object.keys(ps).forEach(p=>gen.assign((0,codegen_1._)`${props}${(0,codegen_1.getProperty)(p)}`,!0))}exports.setEvaluated=setEvaluated;let snippets={};function useFunc(gen,f){return gen.scopeValue("func",{ref:f,code:snippets[f.code]||(snippets[f.code]=new code_1._Code(f.code))})}exports.useFunc=useFunc;var Type;(function(Type2){Type2[Type2.Num=0]="Num",Type2[Type2.Str=1]="Str"})(Type||(exports.Type=Type={}));function getErrorPath(dataProp,dataPropType,jsPropertySyntax){if(dataProp instanceof codegen_1.Name){let isNumber=dataPropType===Type.Num;return jsPropertySyntax?isNumber?(0,codegen_1._)`"[" + ${dataProp} + "]"`:(0,codegen_1._)`"['" + ${dataProp} + "']"`:isNumber?(0,codegen_1._)`"/" + ${dataProp}`:(0,codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return jsPropertySyntax?(0,codegen_1.getProperty)(dataProp).toString():"/"+escapeJsonPointer(dataProp)}exports.getErrorPath=getErrorPath;function checkStrictMode(it,msg,mode=it.opts.strictSchema){if(mode){if(msg=`strict mode: ${msg}`,mode===!0)throw new Error(msg);it.self.logger.warn(msg)}}exports.checkStrictMode=checkStrictMode})),require_names=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),names={data:new codegen_1.Name("data"),valCxt:new codegen_1.Name("valCxt"),instancePath:new codegen_1.Name("instancePath"),parentData:new codegen_1.Name("parentData"),parentDataProperty:new codegen_1.Name("parentDataProperty"),rootData:new codegen_1.Name("rootData"),dynamicAnchors:new codegen_1.Name("dynamicAnchors"),vErrors:new codegen_1.Name("vErrors"),errors:new codegen_1.Name("errors"),this:new codegen_1.Name("this"),self:new codegen_1.Name("self"),scope:new codegen_1.Name("scope"),json:new codegen_1.Name("json"),jsonPos:new codegen_1.Name("jsonPos"),jsonLen:new codegen_1.Name("jsonLen"),jsonPart:new codegen_1.Name("jsonPart")};exports.default=names})),require_errors=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.extendErrors=exports.resetErrorsCount=exports.reportExtraError=exports.reportError=exports.keyword$DataError=exports.keywordError=void 0;let codegen_1=require_codegen(),util_1=require_util(),names_1=require_names();exports.keywordError={message:({keyword})=>(0,codegen_1.str)`must pass "${keyword}" keyword validation`},exports.keyword$DataError={message:({keyword,schemaType})=>schemaType?(0,codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)`:(0,codegen_1.str)`"${keyword}" keyword is invalid ($data)`};function reportError(cxt,error3=exports.keywordError,errorPaths,overrideAllErrors){let{it}=cxt,{gen,compositeRule,allErrors}=it,errObj=errorObjectCode(cxt,error3,errorPaths);overrideAllErrors??(compositeRule||allErrors)?addError(gen,errObj):returnErrors(it,(0,codegen_1._)`[${errObj}]`)}exports.reportError=reportError;function reportExtraError(cxt,error3=exports.keywordError,errorPaths){let{it}=cxt,{gen,compositeRule,allErrors}=it;addError(gen,errorObjectCode(cxt,error3,errorPaths)),compositeRule||allErrors||returnErrors(it,names_1.default.vErrors)}exports.reportExtraError=reportExtraError;function resetErrorsCount(gen,errsCount){gen.assign(names_1.default.errors,errsCount),gen.if((0,codegen_1._)`${names_1.default.vErrors} !== null`,()=>gen.if(errsCount,()=>gen.assign((0,codegen_1._)`${names_1.default.vErrors}.length`,errsCount),()=>gen.assign(names_1.default.vErrors,null)))}exports.resetErrorsCount=resetErrorsCount;function extendErrors({gen,keyword,schemaValue,data,errsCount,it}){if(errsCount===void 0)throw new Error("ajv implementation error");let err=gen.name("err");gen.forRange("i",errsCount,names_1.default.errors,i=>{gen.const(err,(0,codegen_1._)`${names_1.default.vErrors}[${i}]`),gen.if((0,codegen_1._)`${err}.instancePath === undefined`,()=>gen.assign((0,codegen_1._)`${err}.instancePath`,(0,codegen_1.strConcat)(names_1.default.instancePath,it.errorPath))),gen.assign((0,codegen_1._)`${err}.schemaPath`,(0,codegen_1.str)`${it.errSchemaPath}/${keyword}`),it.opts.verbose&&(gen.assign((0,codegen_1._)`${err}.schema`,schemaValue),gen.assign((0,codegen_1._)`${err}.data`,data))})}exports.extendErrors=extendErrors;function addError(gen,errObj){let err=gen.const("err",errObj);gen.if((0,codegen_1._)`${names_1.default.vErrors} === null`,()=>gen.assign(names_1.default.vErrors,(0,codegen_1._)`[${err}]`),(0,codegen_1._)`${names_1.default.vErrors}.push(${err})`),gen.code((0,codegen_1._)`${names_1.default.errors}++`)}function returnErrors(it,errs){let{gen,validateName,schemaEnv}=it;schemaEnv.$async?gen.throw((0,codegen_1._)`new ${it.ValidationError}(${errs})`):(gen.assign((0,codegen_1._)`${validateName}.errors`,errs),gen.return(!1))}let E={keyword:new codegen_1.Name("keyword"),schemaPath:new codegen_1.Name("schemaPath"),params:new codegen_1.Name("params"),propertyName:new codegen_1.Name("propertyName"),message:new codegen_1.Name("message"),schema:new codegen_1.Name("schema"),parentSchema:new codegen_1.Name("parentSchema")};function errorObjectCode(cxt,error3,errorPaths){let{createErrors}=cxt.it;return createErrors===!1?(0,codegen_1._)`{}`:errorObject(cxt,error3,errorPaths)}function errorObject(cxt,error3,errorPaths={}){let{gen,it}=cxt,keyValues=[errorInstancePath(it,errorPaths),errorSchemaPath(cxt,errorPaths)];return extraErrorProps(cxt,error3,keyValues),gen.object(...keyValues)}function errorInstancePath({errorPath},{instancePath}){let instPath=instancePath?(0,codegen_1.str)`${errorPath}${(0,util_1.getErrorPath)(instancePath,util_1.Type.Str)}`:errorPath;return[names_1.default.instancePath,(0,codegen_1.strConcat)(names_1.default.instancePath,instPath)]}function errorSchemaPath({keyword,it:{errSchemaPath}},{schemaPath,parentSchema}){let schPath=parentSchema?errSchemaPath:(0,codegen_1.str)`${errSchemaPath}/${keyword}`;return schemaPath&&(schPath=(0,codegen_1.str)`${schPath}${(0,util_1.getErrorPath)(schemaPath,util_1.Type.Str)}`),[E.schemaPath,schPath]}function extraErrorProps(cxt,{params,message},keyValues){let{keyword,data,schemaValue,it}=cxt,{opts,propertyName,topSchemaRef,schemaPath}=it;keyValues.push([E.keyword,keyword],[E.params,typeof params=="function"?params(cxt):params||(0,codegen_1._)`{}`]),opts.messages&&keyValues.push([E.message,typeof message=="function"?message(cxt):message]),opts.verbose&&keyValues.push([E.schema,schemaValue],[E.parentSchema,(0,codegen_1._)`${topSchemaRef}${schemaPath}`],[names_1.default.data,data]),propertyName&&keyValues.push([E.propertyName,propertyName])}})),require_boolSchema=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.boolOrEmptySchema=exports.topBoolOrEmptySchema=void 0;let errors_1=require_errors(),codegen_1=require_codegen(),names_1=require_names(),boolError={message:"boolean schema is false"};function topBoolOrEmptySchema(it){let{gen,schema:schema2,validateName}=it;schema2===!1?falseSchemaError(it,!1):typeof schema2=="object"&&schema2.$async===!0?gen.return(names_1.default.data):(gen.assign((0,codegen_1._)`${validateName}.errors`,null),gen.return(!0))}exports.topBoolOrEmptySchema=topBoolOrEmptySchema;function boolOrEmptySchema(it,valid){let{gen,schema:schema2}=it;schema2===!1?(gen.var(valid,!1),falseSchemaError(it)):gen.var(valid,!0)}exports.boolOrEmptySchema=boolOrEmptySchema;function falseSchemaError(it,overrideAllErrors){let{gen,data}=it,cxt={gen,keyword:"false schema",data,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it};(0,errors_1.reportError)(cxt,boolError,void 0,overrideAllErrors)}})),require_rules=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.getRules=exports.isJSONType=void 0;let jsonTypes=new Set(["string","number","integer","boolean","null","object","array"]);function isJSONType(x){return typeof x=="string"&&jsonTypes.has(x)}exports.isJSONType=isJSONType;function getRules(){let groups={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...groups,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},groups.number,groups.string,groups.array,groups.object],post:{rules:[]},all:{},keywords:{}}}exports.getRules=getRules})),require_applicability=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.shouldUseRule=exports.shouldUseGroup=exports.schemaHasRulesForType=void 0;function schemaHasRulesForType({schema:schema2,self},type){let group=self.RULES.types[type];return group&&group!==!0&&shouldUseGroup(schema2,group)}exports.schemaHasRulesForType=schemaHasRulesForType;function shouldUseGroup(schema2,group){return group.rules.some(rule=>shouldUseRule(schema2,rule))}exports.shouldUseGroup=shouldUseGroup;function shouldUseRule(schema2,rule){var _a3;return schema2[rule.keyword]!==void 0||((_a3=rule.definition.implements)===null||_a3===void 0?void 0:_a3.some(kwd=>schema2[kwd]!==void 0))}exports.shouldUseRule=shouldUseRule})),require_dataType=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.reportTypeError=exports.checkDataTypes=exports.checkDataType=exports.coerceAndCheckDataType=exports.getJSONTypes=exports.getSchemaTypes=exports.DataType=void 0;let rules_1=require_rules(),applicability_1=require_applicability(),errors_1=require_errors(),codegen_1=require_codegen(),util_1=require_util();var DataType;(function(DataType2){DataType2[DataType2.Correct=0]="Correct",DataType2[DataType2.Wrong=1]="Wrong"})(DataType||(exports.DataType=DataType={}));function getSchemaTypes(schema2){let types=getJSONTypes(schema2.type);if(types.includes("null")){if(schema2.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!types.length&&schema2.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');schema2.nullable===!0&&types.push("null")}return types}exports.getSchemaTypes=getSchemaTypes;function getJSONTypes(ts){let types=Array.isArray(ts)?ts:ts?[ts]:[];if(types.every(rules_1.isJSONType))return types;throw new Error("type must be JSONType or JSONType[]: "+types.join(","))}exports.getJSONTypes=getJSONTypes;function coerceAndCheckDataType(it,types){let{gen,data,opts}=it,coerceTo=coerceToTypes(types,opts.coerceTypes),checkTypes=types.length>0&&!(coerceTo.length===0&&types.length===1&&(0,applicability_1.schemaHasRulesForType)(it,types[0]));if(checkTypes){let wrongType=checkDataTypes(types,data,opts.strictNumbers,DataType.Wrong);gen.if(wrongType,()=>{coerceTo.length?coerceData(it,types,coerceTo):reportTypeError(it)})}return checkTypes}exports.coerceAndCheckDataType=coerceAndCheckDataType;let COERCIBLE=new Set(["string","number","integer","boolean","null"]);function coerceToTypes(types,coerceTypes){return coerceTypes?types.filter(t=>COERCIBLE.has(t)||coerceTypes==="array"&&t==="array"):[]}function coerceData(it,types,coerceTo){let{gen,data,opts}=it,dataType=gen.let("dataType",(0,codegen_1._)`typeof ${data}`),coerced=gen.let("coerced",(0,codegen_1._)`undefined`);opts.coerceTypes==="array"&&gen.if((0,codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`,()=>gen.assign(data,(0,codegen_1._)`${data}[0]`).assign(dataType,(0,codegen_1._)`typeof ${data}`).if(checkDataTypes(types,data,opts.strictNumbers),()=>gen.assign(coerced,data))),gen.if((0,codegen_1._)`${coerced} !== undefined`);for(let t of coerceTo)(COERCIBLE.has(t)||t==="array"&&opts.coerceTypes==="array")&&coerceSpecificType(t);gen.else(),reportTypeError(it),gen.endIf(),gen.if((0,codegen_1._)`${coerced} !== undefined`,()=>{gen.assign(data,coerced),assignParentData(it,coerced)});function coerceSpecificType(t){switch(t){case"string":gen.elseIf((0,codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced,(0,codegen_1._)`"" + ${data}`).elseIf((0,codegen_1._)`${data} === null`).assign(coerced,(0,codegen_1._)`""`);return;case"number":gen.elseIf((0,codegen_1._)`${dataType} == "boolean" || ${data} === null
66
59
  || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced,(0,codegen_1._)`+${data}`);return;case"integer":gen.elseIf((0,codegen_1._)`${dataType} === "boolean" || ${data} === null
67
60
  || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced,(0,codegen_1._)`+${data}`);return;case"boolean":gen.elseIf((0,codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced,!1).elseIf((0,codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced,!0);return;case"null":gen.elseIf((0,codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`),gen.assign(coerced,null);return;case"array":gen.elseIf((0,codegen_1._)`${dataType} === "string" || ${dataType} === "number"
68
- || ${dataType} === "boolean" || ${data} === null`).assign(coerced,(0,codegen_1._)`[${data}]`)}}}function assignParentData({gen,parentData,parentDataProperty},expr){gen.if((0,codegen_1._)`${parentData} !== undefined`,()=>gen.assign((0,codegen_1._)`${parentData}[${parentDataProperty}]`,expr))}function checkDataType(dataType,data,strictNums,correct=DataType.Correct){let EQ=correct===DataType.Correct?codegen_1.operators.EQ:codegen_1.operators.NEQ,cond;switch(dataType){case"null":return(0,codegen_1._)`${data} ${EQ} null`;case"array":cond=(0,codegen_1._)`Array.isArray(${data})`;break;case"object":cond=(0,codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;break;case"integer":cond=numCond((0,codegen_1._)`!(${data} % 1) && !isNaN(${data})`);break;case"number":cond=numCond();break;default:return(0,codegen_1._)`typeof ${data} ${EQ} ${dataType}`}return correct===DataType.Correct?cond:(0,codegen_1.not)(cond);function numCond(_cond=codegen_1.nil){return(0,codegen_1.and)((0,codegen_1._)`typeof ${data} == "number"`,_cond,strictNums?(0,codegen_1._)`isFinite(${data})`:codegen_1.nil)}}exports.checkDataType=checkDataType;function checkDataTypes(dataTypes,data,strictNums,correct){if(dataTypes.length===1)return checkDataType(dataTypes[0],data,strictNums,correct);let cond,types=(0,util_1.toHash)(dataTypes);if(types.array&&types.object){let notObj=(0,codegen_1._)`typeof ${data} != "object"`;cond=types.null?notObj:(0,codegen_1._)`!${data} || ${notObj}`,delete types.null,delete types.array,delete types.object}else cond=codegen_1.nil;types.number&&delete types.integer;for(let t in types)cond=(0,codegen_1.and)(cond,checkDataType(t,data,strictNums,correct));return cond}exports.checkDataTypes=checkDataTypes;let typeError={message:({schema:schema2})=>`must be ${schema2}`,params:({schema:schema2,schemaValue})=>typeof schema2=="string"?(0,codegen_1._)`{type: ${schema2}}`:(0,codegen_1._)`{type: ${schemaValue}}`};function reportTypeError(it){let cxt=getTypeErrorContext(it);(0,errors_1.reportError)(cxt,typeError)}exports.reportTypeError=reportTypeError;function getTypeErrorContext(it){let{gen,data,schema:schema2}=it,schemaCode=(0,util_1.schemaRefOrVal)(it,schema2,"type");return{gen,keyword:"type",data,schema:schema2.type,schemaCode,schemaValue:schemaCode,parentSchema:schema2,params:{},it}}})),require_defaults=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.assignDefaults=void 0;let codegen_1=require_codegen(),util_1=require_util();function assignDefaults(it,ty){let{properties,items}=it.schema;if(ty==="object"&&properties)for(let key in properties)assignDefault(it,key,properties[key].default);else ty==="array"&&Array.isArray(items)&&items.forEach((sch,i)=>assignDefault(it,i,sch.default))}exports.assignDefaults=assignDefaults;function assignDefault(it,prop,defaultValue){let{gen,compositeRule,data,opts}=it;if(defaultValue===void 0)return;let childData=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(prop)}`;if(compositeRule){(0,util_1.checkStrictMode)(it,`default is ignored for: ${childData}`);return}let condition=(0,codegen_1._)`${childData} === undefined`;opts.useDefaults==="empty"&&(condition=(0,codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`),gen.if(condition,(0,codegen_1._)`${childData} = ${(0,codegen_1.stringify)(defaultValue)}`)}})),require_code=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateUnion=exports.validateArray=exports.usePattern=exports.callValidateCode=exports.schemaProperties=exports.allSchemaProperties=exports.noPropertyInData=exports.propertyInData=exports.isOwnProperty=exports.hasPropFunc=exports.reportMissingProp=exports.checkMissingProp=exports.checkReportMissingProp=void 0;let codegen_1=require_codegen(),util_1=require_util(),names_1=require_names(),util_2=require_util();function checkReportMissingProp(cxt,prop){let{gen,data,it}=cxt;gen.if(noPropertyInData(gen,data,prop,it.opts.ownProperties),()=>{cxt.setParams({missingProperty:(0,codegen_1._)`${prop}`},!0),cxt.error()})}exports.checkReportMissingProp=checkReportMissingProp;function checkMissingProp({gen,data,it:{opts}},properties,missing){return(0,codegen_1.or)(...properties.map(prop=>(0,codegen_1.and)(noPropertyInData(gen,data,prop,opts.ownProperties),(0,codegen_1._)`${missing} = ${prop}`)))}exports.checkMissingProp=checkMissingProp;function reportMissingProp(cxt,missing){cxt.setParams({missingProperty:missing},!0),cxt.error()}exports.reportMissingProp=reportMissingProp;function hasPropFunc(gen){return gen.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,codegen_1._)`Object.prototype.hasOwnProperty`})}exports.hasPropFunc=hasPropFunc;function isOwnProperty(gen,data,property){return(0,codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`}exports.isOwnProperty=isOwnProperty;function propertyInData(gen,data,property,ownProperties){let cond=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(property)} !== undefined`;return ownProperties?(0,codegen_1._)`${cond} && ${isOwnProperty(gen,data,property)}`:cond}exports.propertyInData=propertyInData;function noPropertyInData(gen,data,property,ownProperties){let cond=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(property)} === undefined`;return ownProperties?(0,codegen_1.or)(cond,(0,codegen_1.not)(isOwnProperty(gen,data,property))):cond}exports.noPropertyInData=noPropertyInData;function allSchemaProperties(schemaMap){return schemaMap?Object.keys(schemaMap).filter(p=>p!=="__proto__"):[]}exports.allSchemaProperties=allSchemaProperties;function schemaProperties(it,schemaMap){return allSchemaProperties(schemaMap).filter(p=>!(0,util_1.alwaysValidSchema)(it,schemaMap[p]))}exports.schemaProperties=schemaProperties;function callValidateCode({schemaCode,data,it:{gen,topSchemaRef,schemaPath,errorPath},it},func,context,passSchema){let dataAndSchema=passSchema?(0,codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}`:data,valCxt=[[names_1.default.instancePath,(0,codegen_1.strConcat)(names_1.default.instancePath,errorPath)],[names_1.default.parentData,it.parentData],[names_1.default.parentDataProperty,it.parentDataProperty],[names_1.default.rootData,names_1.default.rootData]];it.opts.dynamicRef&&valCxt.push([names_1.default.dynamicAnchors,names_1.default.dynamicAnchors]);let args=(0,codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;return context!==codegen_1.nil?(0,codegen_1._)`${func}.call(${context}, ${args})`:(0,codegen_1._)`${func}(${args})`}exports.callValidateCode=callValidateCode;let newRegExp=(0,codegen_1._)`new RegExp`;function usePattern({gen,it:{opts}},pattern){let u=opts.unicodeRegExp?"u":"",{regExp}=opts.code,rx=regExp(pattern,u);return gen.scopeValue("pattern",{key:rx.toString(),ref:rx,code:(0,codegen_1._)`${regExp.code==="new RegExp"?newRegExp:(0,util_2.useFunc)(gen,regExp)}(${pattern}, ${u})`})}exports.usePattern=usePattern;function validateArray(cxt){let{gen,data,keyword,it}=cxt,valid=gen.name("valid");if(it.allErrors){let validArr=gen.let("valid",!0);return validateItems(()=>gen.assign(validArr,!1)),validArr}return gen.var(valid,!0),validateItems(()=>gen.break()),valid;function validateItems(notValid){let len=gen.const("len",(0,codegen_1._)`${data}.length`);gen.forRange("i",0,len,i=>{cxt.subschema({keyword,dataProp:i,dataPropType:util_1.Type.Num},valid),gen.if((0,codegen_1.not)(valid),notValid)})}}exports.validateArray=validateArray;function validateUnion(cxt){let{gen,schema:schema2,keyword,it}=cxt;if(!Array.isArray(schema2))throw new Error("ajv implementation error");if(schema2.some(sch=>(0,util_1.alwaysValidSchema)(it,sch))&&!it.opts.unevaluated)return;let valid=gen.let("valid",!1),schValid=gen.name("_valid");gen.block(()=>schema2.forEach((_sch,i)=>{let schCxt=cxt.subschema({keyword,schemaProp:i,compositeRule:!0},schValid);gen.assign(valid,(0,codegen_1._)`${valid} || ${schValid}`),cxt.mergeValidEvaluated(schCxt,schValid)||gen.if((0,codegen_1.not)(valid))})),cxt.result(valid,()=>cxt.reset(),()=>cxt.error(!0))}exports.validateUnion=validateUnion})),require_keyword=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateKeywordUsage=exports.validSchemaType=exports.funcKeywordCode=exports.macroKeywordCode=void 0;let codegen_1=require_codegen(),names_1=require_names(),code_1=require_code(),errors_1=require_errors();function macroKeywordCode(cxt,def){let{gen,keyword,schema:schema2,parentSchema,it}=cxt,macroSchema=def.macro.call(it.self,schema2,parentSchema,it),schemaRef=useKeyword(gen,keyword,macroSchema);it.opts.validateSchema!==!1&&it.self.validateSchema(macroSchema,!0);let valid=gen.name("valid");cxt.subschema({schema:macroSchema,schemaPath:codegen_1.nil,errSchemaPath:`${it.errSchemaPath}/${keyword}`,topSchemaRef:schemaRef,compositeRule:!0},valid),cxt.pass(valid,()=>cxt.error(!0))}exports.macroKeywordCode=macroKeywordCode;function funcKeywordCode(cxt,def){var _a3;let{gen,keyword,schema:schema2,parentSchema,$data,it}=cxt;checkAsyncKeyword(it,def);let validateRef=useKeyword(gen,keyword,!$data&&def.compile?def.compile.call(it.self,schema2,parentSchema,it):def.validate),valid=gen.let("valid");cxt.block$data(valid,validateKeyword),cxt.ok((_a3=def.valid)!==null&&_a3!==void 0?_a3:valid);function validateKeyword(){if(def.errors===!1)assignValid(),def.modifying&&modifyData(cxt),reportErrs(()=>cxt.error());else{let ruleErrs=def.async?validateAsync():validateSync();def.modifying&&modifyData(cxt),reportErrs(()=>addErrs(cxt,ruleErrs))}}function validateAsync(){let ruleErrs=gen.let("ruleErrs",null);return gen.try(()=>assignValid((0,codegen_1._)`await `),e=>gen.assign(valid,!1).if((0,codegen_1._)`${e} instanceof ${it.ValidationError}`,()=>gen.assign(ruleErrs,(0,codegen_1._)`${e}.errors`),()=>gen.throw(e))),ruleErrs}function validateSync(){let validateErrs=(0,codegen_1._)`${validateRef}.errors`;return gen.assign(validateErrs,null),assignValid(codegen_1.nil),validateErrs}function assignValid(_await=def.async?(0,codegen_1._)`await `:codegen_1.nil){let passCxt=it.opts.passContext?names_1.default.this:names_1.default.self,passSchema=!("compile"in def&&!$data||def.schema===!1);gen.assign(valid,(0,codegen_1._)`${_await}${(0,code_1.callValidateCode)(cxt,validateRef,passCxt,passSchema)}`,def.modifying)}function reportErrs(errors2){var _a$1;gen.if((0,codegen_1.not)((_a$1=def.valid)!==null&&_a$1!==void 0?_a$1:valid),errors2)}}exports.funcKeywordCode=funcKeywordCode;function modifyData(cxt){let{gen,data,it}=cxt;gen.if(it.parentData,()=>gen.assign(data,(0,codegen_1._)`${it.parentData}[${it.parentDataProperty}]`))}function addErrs(cxt,errs){let{gen}=cxt;gen.if((0,codegen_1._)`Array.isArray(${errs})`,()=>{gen.assign(names_1.default.vErrors,(0,codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors,(0,codegen_1._)`${names_1.default.vErrors}.length`),(0,errors_1.extendErrors)(cxt)},()=>cxt.error())}function checkAsyncKeyword({schemaEnv},def){if(def.async&&!schemaEnv.$async)throw new Error("async keyword in sync schema")}function useKeyword(gen,keyword,result){if(result===void 0)throw new Error(`keyword "${keyword}" failed to compile`);return gen.scopeValue("keyword",typeof result=="function"?{ref:result}:{ref:result,code:(0,codegen_1.stringify)(result)})}function validSchemaType(schema2,schemaType,allowUndefined=!1){return!schemaType.length||schemaType.some(st=>st==="array"?Array.isArray(schema2):st==="object"?schema2&&typeof schema2=="object"&&!Array.isArray(schema2):typeof schema2==st||allowUndefined&&typeof schema2>"u")}exports.validSchemaType=validSchemaType;function validateKeywordUsage({schema:schema2,opts,self,errSchemaPath},def,keyword){if(Array.isArray(def.keyword)?!def.keyword.includes(keyword):def.keyword!==keyword)throw new Error("ajv implementation error");let deps=def.dependencies;if(deps?.some(kwd=>!Object.prototype.hasOwnProperty.call(schema2,kwd)))throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);if(def.validateSchema&&!def.validateSchema(schema2[keyword])){let msg=`keyword "${keyword}" value is invalid at path "${errSchemaPath}": `+self.errorsText(def.validateSchema.errors);if(opts.validateSchema==="log")self.logger.error(msg);else throw new Error(msg)}}exports.validateKeywordUsage=validateKeywordUsage})),require_subschema=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.extendSubschemaMode=exports.extendSubschemaData=exports.getSubschema=void 0;let codegen_1=require_codegen(),util_1=require_util();function getSubschema(it,{keyword,schemaProp,schema:schema2,schemaPath,errSchemaPath,topSchemaRef}){if(keyword!==void 0&&schema2!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(keyword!==void 0){let sch=it.schema[keyword];return schemaProp===void 0?{schema:sch,schemaPath:(0,codegen_1._)`${it.schemaPath}${(0,codegen_1.getProperty)(keyword)}`,errSchemaPath:`${it.errSchemaPath}/${keyword}`}:{schema:sch[schemaProp],schemaPath:(0,codegen_1._)`${it.schemaPath}${(0,codegen_1.getProperty)(keyword)}${(0,codegen_1.getProperty)(schemaProp)}`,errSchemaPath:`${it.errSchemaPath}/${keyword}/${(0,util_1.escapeFragment)(schemaProp)}`}}if(schema2!==void 0){if(schemaPath===void 0||errSchemaPath===void 0||topSchemaRef===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:schema2,schemaPath,topSchemaRef,errSchemaPath}}throw new Error('either "keyword" or "schema" must be passed')}exports.getSubschema=getSubschema;function extendSubschemaData(subschema,it,{dataProp,dataPropType:dpType,data,dataTypes,propertyName}){if(data!==void 0&&dataProp!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen}=it;if(dataProp!==void 0){let{errorPath,dataPathArr,opts}=it;dataContextProps(gen.let("data",(0,codegen_1._)`${it.data}${(0,codegen_1.getProperty)(dataProp)}`,!0)),subschema.errorPath=(0,codegen_1.str)`${errorPath}${(0,util_1.getErrorPath)(dataProp,dpType,opts.jsPropertySyntax)}`,subschema.parentDataProperty=(0,codegen_1._)`${dataProp}`,subschema.dataPathArr=[...dataPathArr,subschema.parentDataProperty]}data!==void 0&&(dataContextProps(data instanceof codegen_1.Name?data:gen.let("data",data,!0)),propertyName!==void 0&&(subschema.propertyName=propertyName)),dataTypes&&(subschema.dataTypes=dataTypes);function dataContextProps(_nextData){subschema.data=_nextData,subschema.dataLevel=it.dataLevel+1,subschema.dataTypes=[],it.definedProperties=new Set,subschema.parentData=it.data,subschema.dataNames=[...it.dataNames,_nextData]}}exports.extendSubschemaData=extendSubschemaData;function extendSubschemaMode(subschema,{jtdDiscriminator,jtdMetadata,compositeRule,createErrors,allErrors}){compositeRule!==void 0&&(subschema.compositeRule=compositeRule),createErrors!==void 0&&(subschema.createErrors=createErrors),allErrors!==void 0&&(subschema.allErrors=allErrors),subschema.jtdDiscriminator=jtdDiscriminator,subschema.jtdMetadata=jtdMetadata}exports.extendSubschemaMode=extendSubschemaMode})),require_fast_deep_equal=__commonJSMin(((exports,module)=>{module.exports=function equal(a,b){if(a===b)return!0;if(a&&b&&typeof a=="object"&&typeof b=="object"){if(a.constructor!==b.constructor)return!1;var length,i,keys2;if(Array.isArray(a)){if(length=a.length,length!=b.length)return!1;for(i=length;i--!==0;)if(!equal(a[i],b[i]))return!1;return!0}if(a.constructor===RegExp)return a.source===b.source&&a.flags===b.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===b.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===b.toString();if(keys2=Object.keys(a),length=keys2.length,length!==Object.keys(b).length)return!1;for(i=length;i--!==0;)if(!Object.prototype.hasOwnProperty.call(b,keys2[i]))return!1;for(i=length;i--!==0;){var key=keys2[i];if(!equal(a[key],b[key]))return!1}return!0}return a!==a&&b!==b}})),require_json_schema_traverse=__commonJSMin(((exports,module)=>{var traverse=module.exports=function(schema2,opts,cb){typeof opts=="function"&&(cb=opts,opts={}),cb=opts.cb||cb;var pre=typeof cb=="function"?cb:cb.pre||function(){},post=cb.post||function(){};_traverse(opts,pre,post,schema2,"",schema2)};traverse.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},traverse.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},traverse.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},traverse.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function _traverse(opts,pre,post,schema2,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex){if(schema2&&typeof schema2=="object"&&!Array.isArray(schema2)){pre(schema2,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex);for(var key in schema2){var sch=schema2[key];if(Array.isArray(sch)){if(key in traverse.arrayKeywords)for(var i=0;i<sch.length;i++)_traverse(opts,pre,post,sch[i],jsonPtr+"/"+key+"/"+i,rootSchema,jsonPtr,key,schema2,i)}else if(key in traverse.propsKeywords){if(sch&&typeof sch=="object")for(var prop in sch)_traverse(opts,pre,post,sch[prop],jsonPtr+"/"+key+"/"+escapeJsonPtr(prop),rootSchema,jsonPtr,key,schema2,prop)}else(key in traverse.keywords||opts.allKeys&&!(key in traverse.skipKeywords))&&_traverse(opts,pre,post,sch,jsonPtr+"/"+key,rootSchema,jsonPtr,key,schema2)}post(schema2,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex)}}function escapeJsonPtr(str){return str.replace(/~/g,"~0").replace(/\//g,"~1")}})),require_resolve=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.getSchemaRefs=exports.resolveUrl=exports.normalizeId=exports._getFullPath=exports.getFullPath=exports.inlineRef=void 0;let util_1=require_util(),equal=require_fast_deep_equal(),traverse=require_json_schema_traverse(),SIMPLE_INLINED=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function inlineRef(schema2,limit=!0){return typeof schema2=="boolean"?!0:limit===!0?!hasRef(schema2):limit?countKeys(schema2)<=limit:!1}exports.inlineRef=inlineRef;let REF_KEYWORDS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function hasRef(schema2){for(let key in schema2){if(REF_KEYWORDS.has(key))return!0;let sch=schema2[key];if(Array.isArray(sch)&&sch.some(hasRef)||typeof sch=="object"&&hasRef(sch))return!0}return!1}function countKeys(schema2){let count=0;for(let key in schema2){if(key==="$ref")return 1/0;if(count++,!SIMPLE_INLINED.has(key)&&(typeof schema2[key]=="object"&&(0,util_1.eachItem)(schema2[key],sch=>count+=countKeys(sch)),count===1/0))return 1/0}return count}function getFullPath(resolver,id="",normalize){return normalize!==!1&&(id=normalizeId(id)),_getFullPath(resolver,resolver.parse(id))}exports.getFullPath=getFullPath;function _getFullPath(resolver,p){return resolver.serialize(p).split("#")[0]+"#"}exports._getFullPath=_getFullPath;let TRAILING_SLASH_HASH=/#\/?$/;function normalizeId(id){return id?id.replace(TRAILING_SLASH_HASH,""):""}exports.normalizeId=normalizeId;function resolveUrl(resolver,baseId,id){return id=normalizeId(id),resolver.resolve(baseId,id)}exports.resolveUrl=resolveUrl;let ANCHOR=/^[a-z_][-a-z0-9._]*$/i;function getSchemaRefs(schema2,baseId){if(typeof schema2=="boolean")return{};let{schemaId,uriResolver}=this.opts,schId=normalizeId(schema2[schemaId]||baseId),baseIds={"":schId},pathPrefix=getFullPath(uriResolver,schId,!1),localRefs={},schemaRefs=new Set;return traverse(schema2,{allKeys:!0},(sch,jsonPtr,_,parentJsonPtr)=>{if(parentJsonPtr===void 0)return;let fullPath=pathPrefix+jsonPtr,innerBaseId=baseIds[parentJsonPtr];typeof sch[schemaId]=="string"&&(innerBaseId=addRef.call(this,sch[schemaId])),addAnchor.call(this,sch.$anchor),addAnchor.call(this,sch.$dynamicAnchor),baseIds[jsonPtr]=innerBaseId;function addRef(ref){let _resolve=this.opts.uriResolver.resolve;if(ref=normalizeId(innerBaseId?_resolve(innerBaseId,ref):ref),schemaRefs.has(ref))throw ambiguos(ref);schemaRefs.add(ref);let schOrRef=this.refs[ref];return typeof schOrRef=="string"&&(schOrRef=this.refs[schOrRef]),typeof schOrRef=="object"?checkAmbiguosRef(sch,schOrRef.schema,ref):ref!==normalizeId(fullPath)&&(ref[0]==="#"?(checkAmbiguosRef(sch,localRefs[ref],ref),localRefs[ref]=sch):this.refs[ref]=fullPath),ref}function addAnchor(anchor){if(typeof anchor=="string"){if(!ANCHOR.test(anchor))throw new Error(`invalid anchor "${anchor}"`);addRef.call(this,`#${anchor}`)}}}),localRefs;function checkAmbiguosRef(sch1,sch2,ref){if(sch2!==void 0&&!equal(sch1,sch2))throw ambiguos(ref)}function ambiguos(ref){return new Error(`reference "${ref}" resolves to more than one schema`)}}exports.getSchemaRefs=getSchemaRefs})),require_validate=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.getData=exports.KeywordCxt=exports.validateFunctionCode=void 0;let boolSchema_1=require_boolSchema(),dataType_1=require_dataType(),applicability_1=require_applicability(),dataType_2=require_dataType(),defaults_1=require_defaults(),keyword_1=require_keyword(),subschema_1=require_subschema(),codegen_1=require_codegen(),names_1=require_names(),resolve_1=require_resolve(),util_1=require_util(),errors_1=require_errors();function validateFunctionCode(it){if(isSchemaObj(it)&&(checkKeywords(it),schemaCxtHasRules(it))){topSchemaObjCode(it);return}validateFunction(it,()=>(0,boolSchema_1.topBoolOrEmptySchema)(it))}exports.validateFunctionCode=validateFunctionCode;function validateFunction({gen,validateName,schema:schema2,schemaEnv,opts},body){opts.code.es5?gen.func(validateName,(0,codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`,schemaEnv.$async,()=>{gen.code((0,codegen_1._)`"use strict"; ${funcSourceUrl(schema2,opts)}`),destructureValCxtES5(gen,opts),gen.code(body)}):gen.func(validateName,(0,codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`,schemaEnv.$async,()=>gen.code(funcSourceUrl(schema2,opts)).code(body))}function destructureValCxt(opts){return(0,codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef?(0,codegen_1._)`, ${names_1.default.dynamicAnchors}={}`:codegen_1.nil}}={}`}function destructureValCxtES5(gen,opts){gen.if(names_1.default.valCxt,()=>{gen.var(names_1.default.instancePath,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`),gen.var(names_1.default.parentData,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`),gen.var(names_1.default.parentDataProperty,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`),gen.var(names_1.default.rootData,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`),opts.dynamicRef&&gen.var(names_1.default.dynamicAnchors,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`)},()=>{gen.var(names_1.default.instancePath,(0,codegen_1._)`""`),gen.var(names_1.default.parentData,(0,codegen_1._)`undefined`),gen.var(names_1.default.parentDataProperty,(0,codegen_1._)`undefined`),gen.var(names_1.default.rootData,names_1.default.data),opts.dynamicRef&&gen.var(names_1.default.dynamicAnchors,(0,codegen_1._)`{}`)})}function topSchemaObjCode(it){let{schema:schema2,opts,gen}=it;validateFunction(it,()=>{opts.$comment&&schema2.$comment&&commentKeyword(it),checkNoDefault(it),gen.let(names_1.default.vErrors,null),gen.let(names_1.default.errors,0),opts.unevaluated&&resetEvaluated(it),typeAndKeywords(it),returnResults(it)})}function resetEvaluated(it){let{gen,validateName}=it;it.evaluated=gen.const("evaluated",(0,codegen_1._)`${validateName}.evaluated`),gen.if((0,codegen_1._)`${it.evaluated}.dynamicProps`,()=>gen.assign((0,codegen_1._)`${it.evaluated}.props`,(0,codegen_1._)`undefined`)),gen.if((0,codegen_1._)`${it.evaluated}.dynamicItems`,()=>gen.assign((0,codegen_1._)`${it.evaluated}.items`,(0,codegen_1._)`undefined`))}function funcSourceUrl(schema2,opts){let schId=typeof schema2=="object"&&schema2[opts.schemaId];return schId&&(opts.code.source||opts.code.process)?(0,codegen_1._)`/*# sourceURL=${schId} */`:codegen_1.nil}function subschemaCode(it,valid){if(isSchemaObj(it)&&(checkKeywords(it),schemaCxtHasRules(it))){subSchemaObjCode(it,valid);return}(0,boolSchema_1.boolOrEmptySchema)(it,valid)}function schemaCxtHasRules({schema:schema2,self}){if(typeof schema2=="boolean")return!schema2;for(let key in schema2)if(self.RULES.all[key])return!0;return!1}function isSchemaObj(it){return typeof it.schema!="boolean"}function subSchemaObjCode(it,valid){let{schema:schema2,gen,opts}=it;opts.$comment&&schema2.$comment&&commentKeyword(it),updateContext(it),checkAsyncSchema(it);let errsCount=gen.const("_errs",names_1.default.errors);typeAndKeywords(it,errsCount),gen.var(valid,(0,codegen_1._)`${errsCount} === ${names_1.default.errors}`)}function checkKeywords(it){(0,util_1.checkUnknownRules)(it),checkRefsAndKeywords(it)}function typeAndKeywords(it,errsCount){if(it.opts.jtd)return schemaKeywords(it,[],!1,errsCount);let types=(0,dataType_1.getSchemaTypes)(it.schema);schemaKeywords(it,types,!(0,dataType_1.coerceAndCheckDataType)(it,types),errsCount)}function checkRefsAndKeywords(it){let{schema:schema2,errSchemaPath,opts,self}=it;schema2.$ref&&opts.ignoreKeywordsWithRef&&(0,util_1.schemaHasRulesButRef)(schema2,self.RULES)&&self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)}function checkNoDefault(it){let{schema:schema2,opts}=it;schema2.default!==void 0&&opts.useDefaults&&opts.strictSchema&&(0,util_1.checkStrictMode)(it,"default is ignored in the schema root")}function updateContext(it){let schId=it.schema[it.opts.schemaId];schId&&(it.baseId=(0,resolve_1.resolveUrl)(it.opts.uriResolver,it.baseId,schId))}function checkAsyncSchema(it){if(it.schema.$async&&!it.schemaEnv.$async)throw new Error("async schema in sync schema")}function commentKeyword({gen,schemaEnv,schema:schema2,errSchemaPath,opts}){let msg=schema2.$comment;if(opts.$comment===!0)gen.code((0,codegen_1._)`${names_1.default.self}.logger.log(${msg})`);else if(typeof opts.$comment=="function"){let schemaPath=(0,codegen_1.str)`${errSchemaPath}/$comment`,rootName=gen.scopeValue("root",{ref:schemaEnv.root});gen.code((0,codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)}}function returnResults(it){let{gen,schemaEnv,validateName,ValidationError,opts}=it;schemaEnv.$async?gen.if((0,codegen_1._)`${names_1.default.errors} === 0`,()=>gen.return(names_1.default.data),()=>gen.throw((0,codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)):(gen.assign((0,codegen_1._)`${validateName}.errors`,names_1.default.vErrors),opts.unevaluated&&assignEvaluated(it),gen.return((0,codegen_1._)`${names_1.default.errors} === 0`))}function assignEvaluated({gen,evaluated,props,items}){props instanceof codegen_1.Name&&gen.assign((0,codegen_1._)`${evaluated}.props`,props),items instanceof codegen_1.Name&&gen.assign((0,codegen_1._)`${evaluated}.items`,items)}function schemaKeywords(it,types,typeErrors,errsCount){let{gen,schema:schema2,data,allErrors,opts,self}=it,{RULES}=self;if(schema2.$ref&&(opts.ignoreKeywordsWithRef||!(0,util_1.schemaHasRulesButRef)(schema2,RULES))){gen.block(()=>keywordCode(it,"$ref",RULES.all.$ref.definition));return}opts.jtd||checkStrictTypes(it,types),gen.block(()=>{for(let group of RULES.rules)groupKeywords(group);groupKeywords(RULES.post)});function groupKeywords(group){(0,applicability_1.shouldUseGroup)(schema2,group)&&(group.type?(gen.if((0,dataType_2.checkDataType)(group.type,data,opts.strictNumbers)),iterateKeywords(it,group),types.length===1&&types[0]===group.type&&typeErrors&&(gen.else(),(0,dataType_2.reportTypeError)(it)),gen.endIf()):iterateKeywords(it,group),allErrors||gen.if((0,codegen_1._)`${names_1.default.errors} === ${errsCount||0}`))}}function iterateKeywords(it,group){let{gen,schema:schema2,opts:{useDefaults}}=it;useDefaults&&(0,defaults_1.assignDefaults)(it,group.type),gen.block(()=>{for(let rule of group.rules)(0,applicability_1.shouldUseRule)(schema2,rule)&&keywordCode(it,rule.keyword,rule.definition,group.type)})}function checkStrictTypes(it,types){it.schemaEnv.meta||!it.opts.strictTypes||(checkContextTypes(it,types),it.opts.allowUnionTypes||checkMultipleTypes(it,types),checkKeywordTypes(it,it.dataTypes))}function checkContextTypes(it,types){if(types.length){if(!it.dataTypes.length){it.dataTypes=types;return}types.forEach(t=>{includesType(it.dataTypes,t)||strictTypesError(it,`type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)}),narrowSchemaTypes(it,types)}}function checkMultipleTypes(it,ts){ts.length>1&&!(ts.length===2&&ts.includes("null"))&&strictTypesError(it,"use allowUnionTypes to allow union type keyword")}function checkKeywordTypes(it,ts){let rules=it.self.RULES.all;for(let keyword in rules){let rule=rules[keyword];if(typeof rule=="object"&&(0,applicability_1.shouldUseRule)(it.schema,rule)){let{type}=rule.definition;type.length&&!type.some(t=>hasApplicableType(ts,t))&&strictTypesError(it,`missing type "${type.join(",")}" for keyword "${keyword}"`)}}}function hasApplicableType(schTs,kwdT){return schTs.includes(kwdT)||kwdT==="number"&&schTs.includes("integer")}function includesType(ts,t){return ts.includes(t)||t==="integer"&&ts.includes("number")}function narrowSchemaTypes(it,withTypes){let ts=[];for(let t of it.dataTypes)includesType(withTypes,t)?ts.push(t):withTypes.includes("integer")&&t==="number"&&ts.push("integer");it.dataTypes=ts}function strictTypesError(it,msg){let schemaPath=it.schemaEnv.baseId+it.errSchemaPath;msg+=` at "${schemaPath}" (strictTypes)`,(0,util_1.checkStrictMode)(it,msg,it.opts.strictTypes)}var KeywordCxt=class{constructor(it,def,keyword){if((0,keyword_1.validateKeywordUsage)(it,def,keyword),this.gen=it.gen,this.allErrors=it.allErrors,this.keyword=keyword,this.data=it.data,this.schema=it.schema[keyword],this.$data=def.$data&&it.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,util_1.schemaRefOrVal)(it,this.schema,keyword,this.$data),this.schemaType=def.schemaType,this.parentSchema=it.schema,this.params={},this.it=it,this.def=def,this.$data)this.schemaCode=it.gen.const("vSchema",getData(this.$data,it));else if(this.schemaCode=this.schemaValue,!(0,keyword_1.validSchemaType)(this.schema,def.schemaType,def.allowUndefined))throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);("code"in def?def.trackErrors:def.errors!==!1)&&(this.errsCount=it.gen.const("_errs",names_1.default.errors))}result(condition,successAction,failAction){this.failResult((0,codegen_1.not)(condition),successAction,failAction)}failResult(condition,successAction,failAction){this.gen.if(condition),failAction?failAction():this.error(),successAction?(this.gen.else(),successAction(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(condition,failAction){this.failResult((0,codegen_1.not)(condition),void 0,failAction)}fail(condition){if(condition===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(condition),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(condition){if(!this.$data)return this.fail(condition);let{schemaCode}=this;this.fail((0,codegen_1._)`${schemaCode} !== undefined && (${(0,codegen_1.or)(this.invalid$data(),condition)})`)}error(append,errorParams,errorPaths){if(errorParams){this.setParams(errorParams),this._error(append,errorPaths),this.setParams({});return}this._error(append,errorPaths)}_error(append,errorPaths){(append?errors_1.reportExtraError:errors_1.reportError)(this,this.def.error,errorPaths)}$dataError(){(0,errors_1.reportError)(this,this.def.$dataError||errors_1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,errors_1.resetErrorsCount)(this.gen,this.errsCount)}ok(cond){this.allErrors||this.gen.if(cond)}setParams(obj,assign){assign?Object.assign(this.params,obj):this.params=obj}block$data(valid,codeBlock,$dataValid=codegen_1.nil){this.gen.block(()=>{this.check$data(valid,$dataValid),codeBlock()})}check$data(valid=codegen_1.nil,$dataValid=codegen_1.nil){if(!this.$data)return;let{gen,schemaCode,schemaType,def}=this;gen.if((0,codegen_1.or)((0,codegen_1._)`${schemaCode} === undefined`,$dataValid)),valid!==codegen_1.nil&&gen.assign(valid,!0),(schemaType.length||def.validateSchema)&&(gen.elseIf(this.invalid$data()),this.$dataError(),valid!==codegen_1.nil&&gen.assign(valid,!1)),gen.else()}invalid$data(){let{gen,schemaCode,schemaType,def,it}=this;return(0,codegen_1.or)(wrong$DataType(),invalid$DataSchema());function wrong$DataType(){if(schemaType.length){if(!(schemaCode instanceof codegen_1.Name))throw new Error("ajv implementation error");let st=Array.isArray(schemaType)?schemaType:[schemaType];return(0,codegen_1._)`${(0,dataType_2.checkDataTypes)(st,schemaCode,it.opts.strictNumbers,dataType_2.DataType.Wrong)}`}return codegen_1.nil}function invalid$DataSchema(){if(def.validateSchema){let validateSchemaRef=gen.scopeValue("validate$data",{ref:def.validateSchema});return(0,codegen_1._)`!${validateSchemaRef}(${schemaCode})`}return codegen_1.nil}}subschema(appl,valid){let subschema=(0,subschema_1.getSubschema)(this.it,appl);(0,subschema_1.extendSubschemaData)(subschema,this.it,appl),(0,subschema_1.extendSubschemaMode)(subschema,appl);let nextContext={...this.it,...subschema,items:void 0,props:void 0};return subschemaCode(nextContext,valid),nextContext}mergeEvaluated(schemaCxt,toName){let{it,gen}=this;it.opts.unevaluated&&(it.props!==!0&&schemaCxt.props!==void 0&&(it.props=util_1.mergeEvaluated.props(gen,schemaCxt.props,it.props,toName)),it.items!==!0&&schemaCxt.items!==void 0&&(it.items=util_1.mergeEvaluated.items(gen,schemaCxt.items,it.items,toName)))}mergeValidEvaluated(schemaCxt,valid){let{it,gen}=this;if(it.opts.unevaluated&&(it.props!==!0||it.items!==!0))return gen.if(valid,()=>this.mergeEvaluated(schemaCxt,codegen_1.Name)),!0}};exports.KeywordCxt=KeywordCxt;function keywordCode(it,keyword,def,ruleType){let cxt=new KeywordCxt(it,def,keyword);"code"in def?def.code(cxt,ruleType):cxt.$data&&def.validate?(0,keyword_1.funcKeywordCode)(cxt,def):"macro"in def?(0,keyword_1.macroKeywordCode)(cxt,def):(def.compile||def.validate)&&(0,keyword_1.funcKeywordCode)(cxt,def)}let JSON_POINTER=/^\/(?:[^~]|~0|~1)*$/,RELATIVE_JSON_POINTER=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData($data,{dataLevel,dataNames,dataPathArr}){let jsonPointer,data;if($data==="")return names_1.default.rootData;if($data[0]==="/"){if(!JSON_POINTER.test($data))throw new Error(`Invalid JSON-pointer: ${$data}`);jsonPointer=$data,data=names_1.default.rootData}else{let matches=RELATIVE_JSON_POINTER.exec($data);if(!matches)throw new Error(`Invalid JSON-pointer: ${$data}`);let up=+matches[1];if(jsonPointer=matches[2],jsonPointer==="#"){if(up>=dataLevel)throw new Error(errorMsg("property/index",up));return dataPathArr[dataLevel-up]}if(up>dataLevel)throw new Error(errorMsg("data",up));if(data=dataNames[dataLevel-up],!jsonPointer)return data}let expr=data,segments=jsonPointer.split("/");for(let segment of segments)segment&&(data=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)((0,util_1.unescapeJsonPointer)(segment))}`,expr=(0,codegen_1._)`${expr} && ${data}`);return expr;function errorMsg(pointerType,up){return`Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`}}exports.getData=getData})),require_validation_error=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});var ValidationError=class extends Error{constructor(errors2){super("validation failed"),this.errors=errors2,this.ajv=this.validation=!0}};exports.default=ValidationError})),require_ref_error=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let resolve_1=require_resolve();var MissingRefError=class extends Error{constructor(resolver,baseId,ref,msg){super(msg||`can't resolve reference ${ref} from id ${baseId}`),this.missingRef=(0,resolve_1.resolveUrl)(resolver,baseId,ref),this.missingSchema=(0,resolve_1.normalizeId)((0,resolve_1.getFullPath)(resolver,this.missingRef))}};exports.default=MissingRefError})),require_compile=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.resolveSchema=exports.getCompilingSchema=exports.resolveRef=exports.compileSchema=exports.SchemaEnv=void 0;let codegen_1=require_codegen(),validation_error_1=require_validation_error(),names_1=require_names(),resolve_1=require_resolve(),util_1=require_util(),validate_1=require_validate();var SchemaEnv=class{constructor(env2){var _a3;this.refs={},this.dynamicAnchors={};let schema2;typeof env2.schema=="object"&&(schema2=env2.schema),this.schema=env2.schema,this.schemaId=env2.schemaId,this.root=env2.root||this,this.baseId=(_a3=env2.baseId)!==null&&_a3!==void 0?_a3:(0,resolve_1.normalizeId)(schema2?.[env2.schemaId||"$id"]),this.schemaPath=env2.schemaPath,this.localRefs=env2.localRefs,this.meta=env2.meta,this.$async=schema2?.$async,this.refs={}}};exports.SchemaEnv=SchemaEnv;function compileSchema(sch){let _sch=getCompilingSchema.call(this,sch);if(_sch)return _sch;let rootId=(0,resolve_1.getFullPath)(this.opts.uriResolver,sch.root.baseId),{es5,lines}=this.opts.code,{ownProperties}=this.opts,gen=new codegen_1.CodeGen(this.scope,{es5,lines,ownProperties}),_ValidationError;sch.$async&&(_ValidationError=gen.scopeValue("Error",{ref:validation_error_1.default,code:(0,codegen_1._)`require("ajv/dist/runtime/validation_error").default`}));let validateName=gen.scopeName("validate");sch.validateName=validateName;let schemaCxt={gen,allErrors:this.opts.allErrors,data:names_1.default.data,parentData:names_1.default.parentData,parentDataProperty:names_1.default.parentDataProperty,dataNames:[names_1.default.data],dataPathArr:[codegen_1.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:gen.scopeValue("schema",this.opts.code.source===!0?{ref:sch.schema,code:(0,codegen_1.stringify)(sch.schema)}:{ref:sch.schema}),validateName,ValidationError:_ValidationError,schema:sch.schema,schemaEnv:sch,rootId,baseId:sch.baseId||rootId,schemaPath:codegen_1.nil,errSchemaPath:sch.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,codegen_1._)`""`,opts:this.opts,self:this},sourceCode;try{this._compilations.add(sch),(0,validate_1.validateFunctionCode)(schemaCxt),gen.optimize(this.opts.code.optimize);let validateCode=gen.toString();sourceCode=`${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`,this.opts.code.process&&(sourceCode=this.opts.code.process(sourceCode,sch));let validate=new Function(`${names_1.default.self}`,`${names_1.default.scope}`,sourceCode)(this,this.scope.get());if(this.scope.value(validateName,{ref:validate}),validate.errors=null,validate.schema=sch.schema,validate.schemaEnv=sch,sch.$async&&(validate.$async=!0),this.opts.code.source===!0&&(validate.source={validateName,validateCode,scopeValues:gen._values}),this.opts.unevaluated){let{props,items}=schemaCxt;validate.evaluated={props:props instanceof codegen_1.Name?void 0:props,items:items instanceof codegen_1.Name?void 0:items,dynamicProps:props instanceof codegen_1.Name,dynamicItems:items instanceof codegen_1.Name},validate.source&&(validate.source.evaluated=(0,codegen_1.stringify)(validate.evaluated))}return sch.validate=validate,sch}catch(e){throw delete sch.validate,delete sch.validateName,sourceCode&&this.logger.error("Error compiling schema, function code:",sourceCode),e}finally{this._compilations.delete(sch)}}exports.compileSchema=compileSchema;function resolveRef2(root,baseId,ref){var _a3;ref=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,ref);let schOrFunc=root.refs[ref];if(schOrFunc)return schOrFunc;let _sch=resolve.call(this,root,ref);if(_sch===void 0){let schema2=(_a3=root.localRefs)===null||_a3===void 0?void 0:_a3[ref],{schemaId}=this.opts;schema2&&(_sch=new SchemaEnv({schema:schema2,schemaId,root,baseId}))}if(_sch!==void 0)return root.refs[ref]=inlineOrCompile.call(this,_sch)}exports.resolveRef=resolveRef2;function inlineOrCompile(sch){return(0,resolve_1.inlineRef)(sch.schema,this.opts.inlineRefs)?sch.schema:sch.validate?sch:compileSchema.call(this,sch)}function getCompilingSchema(schEnv){for(let sch of this._compilations)if(sameSchemaEnv(sch,schEnv))return sch}exports.getCompilingSchema=getCompilingSchema;function sameSchemaEnv(s1,s2){return s1.schema===s2.schema&&s1.root===s2.root&&s1.baseId===s2.baseId}function resolve(root,ref){let sch;for(;typeof(sch=this.refs[ref])=="string";)ref=sch;return sch||this.schemas[ref]||resolveSchema.call(this,root,ref)}function resolveSchema(root,ref){let p=this.opts.uriResolver.parse(ref),refPath=(0,resolve_1._getFullPath)(this.opts.uriResolver,p),baseId=(0,resolve_1.getFullPath)(this.opts.uriResolver,root.baseId,void 0);if(Object.keys(root.schema).length>0&&refPath===baseId)return getJsonPointer.call(this,p,root);let id=(0,resolve_1.normalizeId)(refPath),schOrRef=this.refs[id]||this.schemas[id];if(typeof schOrRef=="string"){let sch=resolveSchema.call(this,root,schOrRef);return typeof sch?.schema!="object"?void 0:getJsonPointer.call(this,p,sch)}if(typeof schOrRef?.schema=="object"){if(schOrRef.validate||compileSchema.call(this,schOrRef),id===(0,resolve_1.normalizeId)(ref)){let{schema:schema2}=schOrRef,{schemaId}=this.opts,schId=schema2[schemaId];return schId&&(baseId=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schId)),new SchemaEnv({schema:schema2,schemaId,root,baseId})}return getJsonPointer.call(this,p,schOrRef)}}exports.resolveSchema=resolveSchema;let PREVENT_SCOPE_CHANGE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(parsedRef,{baseId,schema:schema2,root}){var _a3;if(((_a3=parsedRef.fragment)===null||_a3===void 0?void 0:_a3[0])!=="/")return;for(let part of parsedRef.fragment.slice(1).split("/")){if(typeof schema2=="boolean")return;let partSchema=schema2[(0,util_1.unescapeFragment)(part)];if(partSchema===void 0)return;schema2=partSchema;let schId=typeof schema2=="object"&&schema2[this.opts.schemaId];!PREVENT_SCOPE_CHANGE.has(part)&&schId&&(baseId=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schId))}let env2;if(typeof schema2!="boolean"&&schema2.$ref&&!(0,util_1.schemaHasRulesButRef)(schema2,this.RULES)){let $ref=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schema2.$ref);env2=resolveSchema.call(this,root,$ref)}let{schemaId}=this.opts;if(env2=env2||new SchemaEnv({schema:schema2,schemaId,root,baseId}),env2.schema!==env2.root.schema)return env2}})),require_data=__commonJSMin(((exports,module)=>{module.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}})),require_utils=__commonJSMin(((exports,module)=>{let isUUID=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),isIPv4=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function stringArrayToHexStripped(input){let acc="",code=0,i=0;for(i=0;i<input.length;i++)if(code=input[i].charCodeAt(0),code!==48){if(!(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102))return"";acc+=input[i];break}for(i+=1;i<input.length;i++){if(code=input[i].charCodeAt(0),!(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102))return"";acc+=input[i]}return acc}let nonSimpleDomain=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function consumeIsZone(buffer){return buffer.length=0,!0}function consumeHextets(buffer,address,output){if(buffer.length){let hex=stringArrayToHexStripped(buffer);if(hex!=="")address.push(hex);else return output.error=!0,!1;buffer.length=0}return!0}function getIPV6(input){let tokenCount=0,output={error:!1,address:"",zone:""},address=[],buffer=[],endipv6Encountered=!1,endIpv6=!1,consume=consumeHextets;for(let i=0;i<input.length;i++){let cursor=input[i];if(!(cursor==="["||cursor==="]"))if(cursor===":"){if(endipv6Encountered===!0&&(endIpv6=!0),!consume(buffer,address,output))break;if(++tokenCount>7){output.error=!0;break}i>0&&input[i-1]===":"&&(endipv6Encountered=!0),address.push(":");continue}else if(cursor==="%"){if(!consume(buffer,address,output))break;consume=consumeIsZone}else{buffer.push(cursor);continue}}return buffer.length&&(consume===consumeIsZone?output.zone=buffer.join(""):endIpv6?address.push(buffer.join("")):address.push(stringArrayToHexStripped(buffer))),output.address=address.join(""),output}function normalizeIPv6(host){if(findToken(host,":")<2)return{host,isIPV6:!1};let ipv62=getIPV6(host);if(ipv62.error)return{host,isIPV6:!1};{let newHost=ipv62.address,escapedHost=ipv62.address;return ipv62.zone&&(newHost+="%"+ipv62.zone,escapedHost+="%25"+ipv62.zone),{host:newHost,isIPV6:!0,escapedHost}}}function findToken(str,token){let ind=0;for(let i=0;i<str.length;i++)str[i]===token&&ind++;return ind}function removeDotSegments(path){let input=path,output=[],nextSlash=-1,len=0;for(;len=input.length;){if(len===1){if(input===".")break;if(input==="/"){output.push("/");break}else{output.push(input);break}}else if(len===2){if(input[0]==="."){if(input[1]===".")break;if(input[1]==="/"){input=input.slice(2);continue}}else if(input[0]==="/"&&(input[1]==="."||input[1]==="/")){output.push("/");break}}else if(len===3&&input==="/.."){output.length!==0&&output.pop(),output.push("/");break}if(input[0]==="."){if(input[1]==="."){if(input[2]==="/"){input=input.slice(3);continue}}else if(input[1]==="/"){input=input.slice(2);continue}}else if(input[0]==="/"&&input[1]==="."){if(input[2]==="/"){input=input.slice(2);continue}else if(input[2]==="."&&input[3]==="/"){input=input.slice(3),output.length!==0&&output.pop();continue}}if((nextSlash=input.indexOf("/",1))===-1){output.push(input);break}else output.push(input.slice(0,nextSlash)),input=input.slice(nextSlash)}return output.join("")}function normalizeComponentEncoding(component,esc2){let func=esc2!==!0?escape:unescape;return component.scheme!==void 0&&(component.scheme=func(component.scheme)),component.userinfo!==void 0&&(component.userinfo=func(component.userinfo)),component.host!==void 0&&(component.host=func(component.host)),component.path!==void 0&&(component.path=func(component.path)),component.query!==void 0&&(component.query=func(component.query)),component.fragment!==void 0&&(component.fragment=func(component.fragment)),component}function recomposeAuthority(component){let uriTokens=[];if(component.userinfo!==void 0&&(uriTokens.push(component.userinfo),uriTokens.push("@")),component.host!==void 0){let host=unescape(component.host);if(!isIPv4(host)){let ipV6res=normalizeIPv6(host);ipV6res.isIPV6===!0?host=`[${ipV6res.escapedHost}]`:host=component.host}uriTokens.push(host)}return(typeof component.port=="number"||typeof component.port=="string")&&(uriTokens.push(":"),uriTokens.push(String(component.port))),uriTokens.length?uriTokens.join(""):void 0}module.exports={nonSimpleDomain,recomposeAuthority,normalizeComponentEncoding,removeDotSegments,isIPv4,isUUID,normalizeIPv6,stringArrayToHexStripped}})),require_schemes=__commonJSMin(((exports,module)=>{let{isUUID}=require_utils(),URN_REG=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,supportedSchemeNames=["http","https","ws","wss","urn","urn:uuid"];function isValidSchemeName(name){return supportedSchemeNames.indexOf(name)!==-1}function wsIsSecure(wsComponent){return wsComponent.secure===!0?!0:wsComponent.secure===!1?!1:wsComponent.scheme?wsComponent.scheme.length===3&&(wsComponent.scheme[0]==="w"||wsComponent.scheme[0]==="W")&&(wsComponent.scheme[1]==="s"||wsComponent.scheme[1]==="S")&&(wsComponent.scheme[2]==="s"||wsComponent.scheme[2]==="S"):!1}function httpParse(component){return component.host||(component.error=component.error||"HTTP URIs must have a host."),component}function httpSerialize(component){let secure=String(component.scheme).toLowerCase()==="https";return(component.port===(secure?443:80)||component.port==="")&&(component.port=void 0),component.path||(component.path="/"),component}function wsParse(wsComponent){return wsComponent.secure=wsIsSecure(wsComponent),wsComponent.resourceName=(wsComponent.path||"/")+(wsComponent.query?"?"+wsComponent.query:""),wsComponent.path=void 0,wsComponent.query=void 0,wsComponent}function wsSerialize(wsComponent){if((wsComponent.port===(wsIsSecure(wsComponent)?443:80)||wsComponent.port==="")&&(wsComponent.port=void 0),typeof wsComponent.secure=="boolean"&&(wsComponent.scheme=wsComponent.secure?"wss":"ws",wsComponent.secure=void 0),wsComponent.resourceName){let[path,query]=wsComponent.resourceName.split("?");wsComponent.path=path&&path!=="/"?path:void 0,wsComponent.query=query,wsComponent.resourceName=void 0}return wsComponent.fragment=void 0,wsComponent}function urnParse(urnComponent,options){if(!urnComponent.path)return urnComponent.error="URN can not be parsed",urnComponent;let matches=urnComponent.path.match(URN_REG);if(matches){let scheme=options.scheme||urnComponent.scheme||"urn";urnComponent.nid=matches[1].toLowerCase(),urnComponent.nss=matches[2];let schemeHandler=getSchemeHandler(`${scheme}:${options.nid||urnComponent.nid}`);urnComponent.path=void 0,schemeHandler&&(urnComponent=schemeHandler.parse(urnComponent,options))}else urnComponent.error=urnComponent.error||"URN can not be parsed.";return urnComponent}function urnSerialize(urnComponent,options){if(urnComponent.nid===void 0)throw new Error("URN without nid cannot be serialized");let scheme=options.scheme||urnComponent.scheme||"urn",nid=urnComponent.nid.toLowerCase(),schemeHandler=getSchemeHandler(`${scheme}:${options.nid||nid}`);schemeHandler&&(urnComponent=schemeHandler.serialize(urnComponent,options));let uriComponent=urnComponent,nss=urnComponent.nss;return uriComponent.path=`${nid||options.nid}:${nss}`,options.skipEscape=!0,uriComponent}function urnuuidParse(urnComponent,options){let uuidComponent=urnComponent;return uuidComponent.uuid=uuidComponent.nss,uuidComponent.nss=void 0,!options.tolerant&&(!uuidComponent.uuid||!isUUID(uuidComponent.uuid))&&(uuidComponent.error=uuidComponent.error||"UUID is not valid."),uuidComponent}function urnuuidSerialize(uuidComponent){let urnComponent=uuidComponent;return urnComponent.nss=(uuidComponent.uuid||"").toLowerCase(),urnComponent}let http={scheme:"http",domainHost:!0,parse:httpParse,serialize:httpSerialize},https={scheme:"https",domainHost:http.domainHost,parse:httpParse,serialize:httpSerialize},ws={scheme:"ws",domainHost:!0,parse:wsParse,serialize:wsSerialize},wss={scheme:"wss",domainHost:ws.domainHost,parse:ws.parse,serialize:ws.serialize},SCHEMES={http,https,ws,wss,urn:{scheme:"urn",parse:urnParse,serialize:urnSerialize,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:urnuuidParse,serialize:urnuuidSerialize,skipNormalize:!0}};Object.setPrototypeOf(SCHEMES,null);function getSchemeHandler(scheme){return scheme&&(SCHEMES[scheme]||SCHEMES[scheme.toLowerCase()])||void 0}module.exports={wsIsSecure,SCHEMES,isValidSchemeName,getSchemeHandler}})),require_fast_uri=__commonJSMin(((exports,module)=>{let{normalizeIPv6,removeDotSegments,recomposeAuthority,normalizeComponentEncoding,isIPv4,nonSimpleDomain}=require_utils(),{SCHEMES,getSchemeHandler}=require_schemes();function normalize(uri,options){return typeof uri=="string"?uri=serialize2(parse4(uri,options),options):typeof uri=="object"&&(uri=parse4(serialize2(uri,options),options)),uri}function resolve(baseURI,relativeURI,options){let schemelessOptions=options?Object.assign({scheme:"null"},options):{scheme:"null"},resolved=resolveComponent(parse4(baseURI,schemelessOptions),parse4(relativeURI,schemelessOptions),schemelessOptions,!0);return schemelessOptions.skipEscape=!0,serialize2(resolved,schemelessOptions)}function resolveComponent(base,relative,options,skipNormalization){let target={};return skipNormalization||(base=parse4(serialize2(base,options),options),relative=parse4(serialize2(relative,options),options)),options=options||{},!options.tolerant&&relative.scheme?(target.scheme=relative.scheme,target.userinfo=relative.userinfo,target.host=relative.host,target.port=relative.port,target.path=removeDotSegments(relative.path||""),target.query=relative.query):(relative.userinfo!==void 0||relative.host!==void 0||relative.port!==void 0?(target.userinfo=relative.userinfo,target.host=relative.host,target.port=relative.port,target.path=removeDotSegments(relative.path||""),target.query=relative.query):(relative.path?(relative.path[0]==="/"?target.path=removeDotSegments(relative.path):((base.userinfo!==void 0||base.host!==void 0||base.port!==void 0)&&!base.path?target.path="/"+relative.path:base.path?target.path=base.path.slice(0,base.path.lastIndexOf("/")+1)+relative.path:target.path=relative.path,target.path=removeDotSegments(target.path)),target.query=relative.query):(target.path=base.path,relative.query!==void 0?target.query=relative.query:target.query=base.query),target.userinfo=base.userinfo,target.host=base.host,target.port=base.port),target.scheme=base.scheme),target.fragment=relative.fragment,target}function equal(uriA,uriB,options){return typeof uriA=="string"?(uriA=unescape(uriA),uriA=serialize2(normalizeComponentEncoding(parse4(uriA,options),!0),{...options,skipEscape:!0})):typeof uriA=="object"&&(uriA=serialize2(normalizeComponentEncoding(uriA,!0),{...options,skipEscape:!0})),typeof uriB=="string"?(uriB=unescape(uriB),uriB=serialize2(normalizeComponentEncoding(parse4(uriB,options),!0),{...options,skipEscape:!0})):typeof uriB=="object"&&(uriB=serialize2(normalizeComponentEncoding(uriB,!0),{...options,skipEscape:!0})),uriA.toLowerCase()===uriB.toLowerCase()}function serialize2(cmpts,opts){let component={host:cmpts.host,scheme:cmpts.scheme,userinfo:cmpts.userinfo,port:cmpts.port,path:cmpts.path,query:cmpts.query,nid:cmpts.nid,nss:cmpts.nss,uuid:cmpts.uuid,fragment:cmpts.fragment,reference:cmpts.reference,resourceName:cmpts.resourceName,secure:cmpts.secure,error:""},options=Object.assign({},opts),uriTokens=[],schemeHandler=getSchemeHandler(options.scheme||component.scheme);schemeHandler&&schemeHandler.serialize&&schemeHandler.serialize(component,options),component.path!==void 0&&(options.skipEscape?component.path=unescape(component.path):(component.path=escape(component.path),component.scheme!==void 0&&(component.path=component.path.split("%3A").join(":")))),options.reference!=="suffix"&&component.scheme&&uriTokens.push(component.scheme,":");let authority=recomposeAuthority(component);if(authority!==void 0&&(options.reference!=="suffix"&&uriTokens.push("//"),uriTokens.push(authority),component.path&&component.path[0]!=="/"&&uriTokens.push("/")),component.path!==void 0){let s=component.path;!options.absolutePath&&(!schemeHandler||!schemeHandler.absolutePath)&&(s=removeDotSegments(s)),authority===void 0&&s[0]==="/"&&s[1]==="/"&&(s="/%2F"+s.slice(2)),uriTokens.push(s)}return component.query!==void 0&&uriTokens.push("?",component.query),component.fragment!==void 0&&uriTokens.push("#",component.fragment),uriTokens.join("")}let URI_PARSE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function parse4(uri,opts){let options=Object.assign({},opts),parsed={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},isIP=!1;options.reference==="suffix"&&(options.scheme?uri=options.scheme+":"+uri:uri="//"+uri);let matches=uri.match(URI_PARSE);if(matches){if(parsed.scheme=matches[1],parsed.userinfo=matches[3],parsed.host=matches[4],parsed.port=parseInt(matches[5],10),parsed.path=matches[6]||"",parsed.query=matches[7],parsed.fragment=matches[8],isNaN(parsed.port)&&(parsed.port=matches[5]),parsed.host)if(isIPv4(parsed.host)===!1){let ipv6result=normalizeIPv6(parsed.host);parsed.host=ipv6result.host.toLowerCase(),isIP=ipv6result.isIPV6}else isIP=!0;parsed.scheme===void 0&&parsed.userinfo===void 0&&parsed.host===void 0&&parsed.port===void 0&&parsed.query===void 0&&!parsed.path?parsed.reference="same-document":parsed.scheme===void 0?parsed.reference="relative":parsed.fragment===void 0?parsed.reference="absolute":parsed.reference="uri",options.reference&&options.reference!=="suffix"&&options.reference!==parsed.reference&&(parsed.error=parsed.error||"URI is not a "+options.reference+" reference.");let schemeHandler=getSchemeHandler(options.scheme||parsed.scheme);if(!options.unicodeSupport&&(!schemeHandler||!schemeHandler.unicodeSupport)&&parsed.host&&(options.domainHost||schemeHandler&&schemeHandler.domainHost)&&isIP===!1&&nonSimpleDomain(parsed.host))try{parsed.host=URL.domainToASCII(parsed.host.toLowerCase())}catch(e){parsed.error=parsed.error||"Host's domain name can not be converted to ASCII: "+e}(!schemeHandler||schemeHandler&&!schemeHandler.skipNormalize)&&(uri.indexOf("%")!==-1&&(parsed.scheme!==void 0&&(parsed.scheme=unescape(parsed.scheme)),parsed.host!==void 0&&(parsed.host=unescape(parsed.host))),parsed.path&&(parsed.path=escape(unescape(parsed.path))),parsed.fragment&&(parsed.fragment=encodeURI(decodeURIComponent(parsed.fragment)))),schemeHandler&&schemeHandler.parse&&schemeHandler.parse(parsed,options)}else parsed.error=parsed.error||"URI can not be parsed.";return parsed}let fastUri={SCHEMES,normalize,resolve,resolveComponent,equal,serialize:serialize2,parse:parse4};module.exports=fastUri,module.exports.default=fastUri,module.exports.fastUri=fastUri})),require_uri=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let uri=require_fast_uri();uri.code='require("ajv/dist/runtime/uri").default',exports.default=uri})),require_core$3=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=void 0;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});let validation_error_1=require_validation_error(),ref_error_1=require_ref_error(),rules_1=require_rules(),compile_1=require_compile(),codegen_2=require_codegen(),resolve_1=require_resolve(),dataType_1=require_dataType(),util_1=require_util(),$dataRefSchema=require_data(),uri_1=require_uri(),defaultRegExp=(str,flags)=>new RegExp(str,flags);defaultRegExp.code="new RegExp";let META_IGNORE_OPTIONS=["removeAdditional","useDefaults","coerceTypes"],EXT_SCOPE_NAMES=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),removedOptions={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},deprecatedOptions={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},MAX_EXPRESSION=200;function requiredOptions(o){var _a3,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_0;let s=o.strict,_optz=(_a3=o.code)===null||_a3===void 0?void 0:_a3.optimize,optimize=_optz===!0||_optz===void 0?1:_optz||0,regExp=(_c=(_b=o.code)===null||_b===void 0?void 0:_b.regExp)!==null&&_c!==void 0?_c:defaultRegExp,uriResolver=(_d=o.uriResolver)!==null&&_d!==void 0?_d:uri_1.default;return{strictSchema:(_f=(_e=o.strictSchema)!==null&&_e!==void 0?_e:s)!==null&&_f!==void 0?_f:!0,strictNumbers:(_h=(_g=o.strictNumbers)!==null&&_g!==void 0?_g:s)!==null&&_h!==void 0?_h:!0,strictTypes:(_k=(_j=o.strictTypes)!==null&&_j!==void 0?_j:s)!==null&&_k!==void 0?_k:"log",strictTuples:(_m=(_l=o.strictTuples)!==null&&_l!==void 0?_l:s)!==null&&_m!==void 0?_m:"log",strictRequired:(_p=(_o=o.strictRequired)!==null&&_o!==void 0?_o:s)!==null&&_p!==void 0?_p:!1,code:o.code?{...o.code,optimize,regExp}:{optimize,regExp},loopRequired:(_q=o.loopRequired)!==null&&_q!==void 0?_q:MAX_EXPRESSION,loopEnum:(_r=o.loopEnum)!==null&&_r!==void 0?_r:MAX_EXPRESSION,meta:(_s=o.meta)!==null&&_s!==void 0?_s:!0,messages:(_t=o.messages)!==null&&_t!==void 0?_t:!0,inlineRefs:(_u=o.inlineRefs)!==null&&_u!==void 0?_u:!0,schemaId:(_v=o.schemaId)!==null&&_v!==void 0?_v:"$id",addUsedSchema:(_w=o.addUsedSchema)!==null&&_w!==void 0?_w:!0,validateSchema:(_x=o.validateSchema)!==null&&_x!==void 0?_x:!0,validateFormats:(_y=o.validateFormats)!==null&&_y!==void 0?_y:!0,unicodeRegExp:(_z=o.unicodeRegExp)!==null&&_z!==void 0?_z:!0,int32range:(_0=o.int32range)!==null&&_0!==void 0?_0:!0,uriResolver}}var Ajv2=class{constructor(opts={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,opts=this.opts={...opts,...requiredOptions(opts)};let{es5,lines}=this.opts.code;this.scope=new codegen_2.ValueScope({scope:{},prefixes:EXT_SCOPE_NAMES,es5,lines}),this.logger=getLogger(opts.logger);let formatOpt=opts.validateFormats;opts.validateFormats=!1,this.RULES=(0,rules_1.getRules)(),checkOptions.call(this,removedOptions,opts,"NOT SUPPORTED"),checkOptions.call(this,deprecatedOptions,opts,"DEPRECATED","warn"),this._metaOpts=getMetaSchemaOptions.call(this),opts.formats&&addInitialFormats.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),opts.keywords&&addInitialKeywords.call(this,opts.keywords),typeof opts.meta=="object"&&this.addMetaSchema(opts.meta),addInitialSchemas.call(this),opts.validateFormats=formatOpt}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data,meta:meta2,schemaId}=this.opts,_dataRefSchema=$dataRefSchema;schemaId==="id"&&(_dataRefSchema={...$dataRefSchema},_dataRefSchema.id=_dataRefSchema.$id,delete _dataRefSchema.$id),meta2&&$data&&this.addMetaSchema(_dataRefSchema,_dataRefSchema[schemaId],!1)}defaultMeta(){let{meta:meta2,schemaId}=this.opts;return this.opts.defaultMeta=typeof meta2=="object"?meta2[schemaId]||meta2:void 0}validate(schemaKeyRef,data){let v;if(typeof schemaKeyRef=="string"){if(v=this.getSchema(schemaKeyRef),!v)throw new Error(`no schema with key or ref "${schemaKeyRef}"`)}else v=this.compile(schemaKeyRef);let valid=v(data);return"$async"in v||(this.errors=v.errors),valid}compile(schema2,_meta){let sch=this._addSchema(schema2,_meta);return sch.validate||this._compileSchemaEnv(sch)}compileAsync(schema2,meta2){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema}=this.opts;return runCompileAsync.call(this,schema2,meta2);async function runCompileAsync(_schema,_meta){await loadMetaSchema.call(this,_schema.$schema);let sch=this._addSchema(_schema,_meta);return sch.validate||_compileAsync.call(this,sch)}async function loadMetaSchema($ref){$ref&&!this.getSchema($ref)&&await runCompileAsync.call(this,{$ref},!0)}async function _compileAsync(sch){try{return this._compileSchemaEnv(sch)}catch(e){if(!(e instanceof ref_error_1.default))throw e;return checkLoaded.call(this,e),await loadMissingSchema.call(this,e.missingSchema),_compileAsync.call(this,sch)}}function checkLoaded({missingSchema:ref,missingRef}){if(this.refs[ref])throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)}async function loadMissingSchema(ref){let _schema=await _loadSchema.call(this,ref);this.refs[ref]||await loadMetaSchema.call(this,_schema.$schema),this.refs[ref]||this.addSchema(_schema,ref,meta2)}async function _loadSchema(ref){let p=this._loading[ref];if(p)return p;try{return await(this._loading[ref]=loadSchema(ref))}finally{delete this._loading[ref]}}}addSchema(schema2,key,_meta,_validateSchema=this.opts.validateSchema){if(Array.isArray(schema2)){for(let sch of schema2)this.addSchema(sch,void 0,_meta,_validateSchema);return this}let id;if(typeof schema2=="object"){let{schemaId}=this.opts;if(id=schema2[schemaId],id!==void 0&&typeof id!="string")throw new Error(`schema ${schemaId} must be string`)}return key=(0,resolve_1.normalizeId)(key||id),this._checkUnique(key),this.schemas[key]=this._addSchema(schema2,_meta,key,_validateSchema,!0),this}addMetaSchema(schema2,key,_validateSchema=this.opts.validateSchema){return this.addSchema(schema2,key,!0,_validateSchema),this}validateSchema(schema2,throwOrLogError){if(typeof schema2=="boolean")return!0;let $schema;if($schema=schema2.$schema,$schema!==void 0&&typeof $schema!="string")throw new Error("$schema must be a string");if($schema=$schema||this.opts.defaultMeta||this.defaultMeta(),!$schema)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let valid=this.validate($schema,schema2);if(!valid&&throwOrLogError){let message="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(message);else throw new Error(message)}return valid}getSchema(keyRef){let sch;for(;typeof(sch=getSchEnv.call(this,keyRef))=="string";)keyRef=sch;if(sch===void 0){let{schemaId}=this.opts,root=new compile_1.SchemaEnv({schema:{},schemaId});if(sch=compile_1.resolveSchema.call(this,root,keyRef),!sch)return;this.refs[keyRef]=sch}return sch.validate||this._compileSchemaEnv(sch)}removeSchema(schemaKeyRef){if(schemaKeyRef instanceof RegExp)return this._removeAllSchemas(this.schemas,schemaKeyRef),this._removeAllSchemas(this.refs,schemaKeyRef),this;switch(typeof schemaKeyRef){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let sch=getSchEnv.call(this,schemaKeyRef);return typeof sch=="object"&&this._cache.delete(sch.schema),delete this.schemas[schemaKeyRef],delete this.refs[schemaKeyRef],this}case"object":{let cacheKey=schemaKeyRef;this._cache.delete(cacheKey);let id=schemaKeyRef[this.opts.schemaId];return id&&(id=(0,resolve_1.normalizeId)(id),delete this.schemas[id],delete this.refs[id]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(definitions){for(let def of definitions)this.addKeyword(def);return this}addKeyword(kwdOrDef,def){let keyword;if(typeof kwdOrDef=="string")keyword=kwdOrDef,typeof def=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),def.keyword=keyword);else if(typeof kwdOrDef=="object"&&def===void 0){if(def=kwdOrDef,keyword=def.keyword,Array.isArray(keyword)&&!keyword.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(checkKeyword.call(this,keyword,def),!def)return(0,util_1.eachItem)(keyword,kwd=>addRule.call(this,kwd)),this;keywordMetaschema.call(this,def);let definition={...def,type:(0,dataType_1.getJSONTypes)(def.type),schemaType:(0,dataType_1.getJSONTypes)(def.schemaType)};return(0,util_1.eachItem)(keyword,definition.type.length===0?k=>addRule.call(this,k,definition):k=>definition.type.forEach(t=>addRule.call(this,k,definition,t))),this}getKeyword(keyword){let rule=this.RULES.all[keyword];return typeof rule=="object"?rule.definition:!!rule}removeKeyword(keyword){let{RULES}=this;delete RULES.keywords[keyword],delete RULES.all[keyword];for(let group of RULES.rules){let i=group.rules.findIndex(rule=>rule.keyword===keyword);i>=0&&group.rules.splice(i,1)}return this}addFormat(name,format){return typeof format=="string"&&(format=new RegExp(format)),this.formats[name]=format,this}errorsText(errors2=this.errors,{separator=", ",dataVar="data"}={}){return!errors2||errors2.length===0?"No errors":errors2.map(e=>`${dataVar}${e.instancePath} ${e.message}`).reduce((text2,msg)=>text2+separator+msg)}$dataMetaSchema(metaSchema,keywordsJsonPointers){let rules=this.RULES.all;metaSchema=JSON.parse(JSON.stringify(metaSchema));for(let jsonPointer of keywordsJsonPointers){let segments=jsonPointer.split("/").slice(1),keywords=metaSchema;for(let seg of segments)keywords=keywords[seg];for(let key in rules){let rule=rules[key];if(typeof rule!="object")continue;let{$data}=rule.definition,schema2=keywords[key];$data&&schema2&&(keywords[key]=schemaOrData(schema2))}}return metaSchema}_removeAllSchemas(schemas,regex){for(let keyRef in schemas){let sch=schemas[keyRef];(!regex||regex.test(keyRef))&&(typeof sch=="string"?delete schemas[keyRef]:sch&&!sch.meta&&(this._cache.delete(sch.schema),delete schemas[keyRef]))}}_addSchema(schema2,meta2,baseId,validateSchema=this.opts.validateSchema,addSchema=this.opts.addUsedSchema){let id,{schemaId}=this.opts;if(typeof schema2=="object")id=schema2[schemaId];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof schema2!="boolean")throw new Error("schema must be object or boolean")}let sch=this._cache.get(schema2);if(sch!==void 0)return sch;baseId=(0,resolve_1.normalizeId)(id||baseId);let localRefs=resolve_1.getSchemaRefs.call(this,schema2,baseId);return sch=new compile_1.SchemaEnv({schema:schema2,schemaId,meta:meta2,baseId,localRefs}),this._cache.set(sch.schema,sch),addSchema&&!baseId.startsWith("#")&&(baseId&&this._checkUnique(baseId),this.refs[baseId]=sch),validateSchema&&this.validateSchema(schema2,!0),sch}_checkUnique(id){if(this.schemas[id]||this.refs[id])throw new Error(`schema with key or id "${id}" already exists`)}_compileSchemaEnv(sch){if(sch.meta?this._compileMetaSchema(sch):compile_1.compileSchema.call(this,sch),!sch.validate)throw new Error("ajv implementation error");return sch.validate}_compileMetaSchema(sch){let currentOpts=this.opts;this.opts=this._metaOpts;try{compile_1.compileSchema.call(this,sch)}finally{this.opts=currentOpts}}};Ajv2.ValidationError=validation_error_1.default,Ajv2.MissingRefError=ref_error_1.default,exports.default=Ajv2;function checkOptions(checkOpts,options,msg,log="error"){for(let key in checkOpts){let opt=key;opt in options&&this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)}}function getSchEnv(keyRef){return keyRef=(0,resolve_1.normalizeId)(keyRef),this.schemas[keyRef]||this.refs[keyRef]}function addInitialSchemas(){let optsSchemas=this.opts.schemas;if(optsSchemas)if(Array.isArray(optsSchemas))this.addSchema(optsSchemas);else for(let key in optsSchemas)this.addSchema(optsSchemas[key],key)}function addInitialFormats(){for(let name in this.opts.formats){let format=this.opts.formats[name];format&&this.addFormat(name,format)}}function addInitialKeywords(defs){if(Array.isArray(defs)){this.addVocabulary(defs);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let keyword in defs){let def=defs[keyword];def.keyword||(def.keyword=keyword),this.addKeyword(def)}}function getMetaSchemaOptions(){let metaOpts={...this.opts};for(let opt of META_IGNORE_OPTIONS)delete metaOpts[opt];return metaOpts}let noLogs={log(){},warn(){},error(){}};function getLogger(logger){if(logger===!1)return noLogs;if(logger===void 0)return console;if(logger.log&&logger.warn&&logger.error)return logger;throw new Error("logger must implement log, warn and error methods")}let KEYWORD_NAME=/^[a-z_$][a-z0-9_$:-]*$/i;function checkKeyword(keyword,def){let{RULES}=this;if((0,util_1.eachItem)(keyword,kwd=>{if(RULES.keywords[kwd])throw new Error(`Keyword ${kwd} is already defined`);if(!KEYWORD_NAME.test(kwd))throw new Error(`Keyword ${kwd} has invalid name`)}),!!def&&def.$data&&!("code"in def||"validate"in def))throw new Error('$data keyword must have "code" or "validate" function')}function addRule(keyword,definition,dataType){var _a3;let post=definition?.post;if(dataType&&post)throw new Error('keyword with "post" flag cannot have "type"');let{RULES}=this,ruleGroup=post?RULES.post:RULES.rules.find(({type:t})=>t===dataType);if(ruleGroup||(ruleGroup={type:dataType,rules:[]},RULES.rules.push(ruleGroup)),RULES.keywords[keyword]=!0,!definition)return;let rule={keyword,definition:{...definition,type:(0,dataType_1.getJSONTypes)(definition.type),schemaType:(0,dataType_1.getJSONTypes)(definition.schemaType)}};definition.before?addBeforeRule.call(this,ruleGroup,rule,definition.before):ruleGroup.rules.push(rule),RULES.all[keyword]=rule,(_a3=definition.implements)===null||_a3===void 0||_a3.forEach(kwd=>this.addKeyword(kwd))}function addBeforeRule(ruleGroup,rule,before){let i=ruleGroup.rules.findIndex(_rule=>_rule.keyword===before);i>=0?ruleGroup.rules.splice(i,0,rule):(ruleGroup.rules.push(rule),this.logger.warn(`rule ${before} is not defined`))}function keywordMetaschema(def){let{metaSchema}=def;metaSchema!==void 0&&(def.$data&&this.opts.$data&&(metaSchema=schemaOrData(metaSchema)),def.validateSchema=this.compile(metaSchema,!0))}let $dataRef={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function schemaOrData(schema2){return{anyOf:[schema2,$dataRef]}}})),require_id=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let def={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};exports.default=def})),require_ref=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.callRef=exports.getValidate=void 0;let ref_error_1=require_ref_error(),code_1=require_code(),codegen_1=require_codegen(),names_1=require_names(),compile_1=require_compile(),util_1=require_util(),def={keyword:"$ref",schemaType:"string",code(cxt){let{gen,schema:$ref,it}=cxt,{baseId,schemaEnv:env2,validateName,opts,self}=it,{root}=env2;if(($ref==="#"||$ref==="#/")&&baseId===root.baseId)return callRootRef();let schOrEnv=compile_1.resolveRef.call(self,root,baseId,$ref);if(schOrEnv===void 0)throw new ref_error_1.default(it.opts.uriResolver,baseId,$ref);if(schOrEnv instanceof compile_1.SchemaEnv)return callValidate(schOrEnv);return inlineRefSchema(schOrEnv);function callRootRef(){if(env2===root)return callRef(cxt,validateName,env2,env2.$async);let rootName=gen.scopeValue("root",{ref:root});return callRef(cxt,(0,codegen_1._)`${rootName}.validate`,root,root.$async)}function callValidate(sch){callRef(cxt,getValidate(cxt,sch),sch,sch.$async)}function inlineRefSchema(sch){let schName=gen.scopeValue("schema",opts.code.source===!0?{ref:sch,code:(0,codegen_1.stringify)(sch)}:{ref:sch}),valid=gen.name("valid"),schCxt=cxt.subschema({schema:sch,dataTypes:[],schemaPath:codegen_1.nil,topSchemaRef:schName,errSchemaPath:$ref},valid);cxt.mergeEvaluated(schCxt),cxt.ok(valid)}}};function getValidate(cxt,sch){let{gen}=cxt;return sch.validate?gen.scopeValue("validate",{ref:sch.validate}):(0,codegen_1._)`${gen.scopeValue("wrapper",{ref:sch})}.validate`}exports.getValidate=getValidate;function callRef(cxt,v,sch,$async){let{gen,it}=cxt,{allErrors,schemaEnv:env2,opts}=it,passCxt=opts.passContext?names_1.default.this:codegen_1.nil;$async?callAsyncRef():callSyncRef();function callAsyncRef(){if(!env2.$async)throw new Error("async schema referenced by sync schema");let valid=gen.let("valid");gen.try(()=>{gen.code((0,codegen_1._)`await ${(0,code_1.callValidateCode)(cxt,v,passCxt)}`),addEvaluatedFrom(v),allErrors||gen.assign(valid,!0)},e=>{gen.if((0,codegen_1._)`!(${e} instanceof ${it.ValidationError})`,()=>gen.throw(e)),addErrorsFrom(e),allErrors||gen.assign(valid,!1)}),cxt.ok(valid)}function callSyncRef(){cxt.result((0,code_1.callValidateCode)(cxt,v,passCxt),()=>addEvaluatedFrom(v),()=>addErrorsFrom(v))}function addErrorsFrom(source){let errs=(0,codegen_1._)`${source}.errors`;gen.assign(names_1.default.vErrors,(0,codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`),gen.assign(names_1.default.errors,(0,codegen_1._)`${names_1.default.vErrors}.length`)}function addEvaluatedFrom(source){var _a3;if(!it.opts.unevaluated)return;let schEvaluated=(_a3=sch?.validate)===null||_a3===void 0?void 0:_a3.evaluated;if(it.props!==!0)if(schEvaluated&&!schEvaluated.dynamicProps)schEvaluated.props!==void 0&&(it.props=util_1.mergeEvaluated.props(gen,schEvaluated.props,it.props));else{let props=gen.var("props",(0,codegen_1._)`${source}.evaluated.props`);it.props=util_1.mergeEvaluated.props(gen,props,it.props,codegen_1.Name)}if(it.items!==!0)if(schEvaluated&&!schEvaluated.dynamicItems)schEvaluated.items!==void 0&&(it.items=util_1.mergeEvaluated.items(gen,schEvaluated.items,it.items));else{let items=gen.var("items",(0,codegen_1._)`${source}.evaluated.items`);it.items=util_1.mergeEvaluated.items(gen,items,it.items,codegen_1.Name)}}}exports.callRef=callRef,exports.default=def})),require_core$2=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let id_1=require_id(),ref_1=require_ref(),core=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",id_1.default,ref_1.default];exports.default=core})),require_limitNumber=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),ops=codegen_1.operators,KWDs={maximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},minimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},exclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},exclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}},def={keyword:Object.keys(KWDs),type:"number",schemaType:"number",$data:!0,error:{message:({keyword,schemaCode})=>(0,codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`},code(cxt){let{keyword,data,schemaCode}=cxt;cxt.fail$data((0,codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`)}};exports.default=def})),require_multipleOf=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),def={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode})=>(0,codegen_1.str)`must be multiple of ${schemaCode}`,params:({schemaCode})=>(0,codegen_1._)`{multipleOf: ${schemaCode}}`},code(cxt){let{gen,data,schemaCode,it}=cxt,prec=it.opts.multipleOfPrecision,res=gen.let("res"),invalid=prec?(0,codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`:(0,codegen_1._)`${res} !== parseInt(${res})`;cxt.fail$data((0,codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)}};exports.default=def})),require_ucs2length=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});function ucs2length(str){let len=str.length,length=0,pos=0,value;for(;pos<len;)length++,value=str.charCodeAt(pos++),value>=55296&&value<=56319&&pos<len&&(value=str.charCodeAt(pos),(value&64512)===56320&&pos++);return length}exports.default=ucs2length,ucs2length.code='require("ajv/dist/runtime/ucs2length").default'})),require_limitLength=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),ucs2length_1=require_ucs2length(),def={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword,schemaCode}){let comp=keyword==="maxLength"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`},code(cxt){let{keyword,data,schemaCode,it}=cxt,op=keyword==="maxLength"?codegen_1.operators.GT:codegen_1.operators.LT,len=it.opts.unicode===!1?(0,codegen_1._)`${data}.length`:(0,codegen_1._)`${(0,util_1.useFunc)(cxt.gen,ucs2length_1.default)}(${data})`;cxt.fail$data((0,codegen_1._)`${len} ${op} ${schemaCode}`)}};exports.default=def})),require_pattern=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let code_1=require_code(),util_1=require_util(),codegen_1=require_codegen(),def={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode})=>(0,codegen_1.str)`must match pattern "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{pattern: ${schemaCode}}`},code(cxt){let{gen,data,$data,schema:schema2,schemaCode,it}=cxt,u=it.opts.unicodeRegExp?"u":"";if($data){let{regExp}=it.opts.code,regExpCode=regExp.code==="new RegExp"?(0,codegen_1._)`new RegExp`:(0,util_1.useFunc)(gen,regExp),valid=gen.let("valid");gen.try(()=>gen.assign(valid,(0,codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`),()=>gen.assign(valid,!1)),cxt.fail$data((0,codegen_1._)`!${valid}`)}else{let regExp=(0,code_1.usePattern)(cxt,schema2);cxt.fail$data((0,codegen_1._)`!${regExp}.test(${data})`)}}};exports.default=def})),require_limitProperties=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),def={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword,schemaCode}){let comp=keyword==="maxProperties"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`},code(cxt){let{keyword,data,schemaCode}=cxt,op=keyword==="maxProperties"?codegen_1.operators.GT:codegen_1.operators.LT;cxt.fail$data((0,codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`)}};exports.default=def})),require_required=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let code_1=require_code(),codegen_1=require_codegen(),util_1=require_util(),def={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty}})=>(0,codegen_1.str)`must have required property '${missingProperty}'`,params:({params:{missingProperty}})=>(0,codegen_1._)`{missingProperty: ${missingProperty}}`},code(cxt){let{gen,schema:schema2,schemaCode,data,$data,it}=cxt,{opts}=it;if(!$data&&schema2.length===0)return;let useLoop=schema2.length>=opts.loopRequired;if(it.allErrors?allErrorsMode():exitOnErrorMode(),opts.strictRequired){let props=cxt.parentSchema.properties,{definedProperties}=cxt.it;for(let requiredKey of schema2)if(props?.[requiredKey]===void 0&&!definedProperties.has(requiredKey)){let msg=`required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId+it.errSchemaPath}" (strictRequired)`;(0,util_1.checkStrictMode)(it,msg,it.opts.strictRequired)}}function allErrorsMode(){if(useLoop||$data)cxt.block$data(codegen_1.nil,loopAllRequired);else for(let prop of schema2)(0,code_1.checkReportMissingProp)(cxt,prop)}function exitOnErrorMode(){let missing=gen.let("missing");if(useLoop||$data){let valid=gen.let("valid",!0);cxt.block$data(valid,()=>loopUntilMissing(missing,valid)),cxt.ok(valid)}else gen.if((0,code_1.checkMissingProp)(cxt,schema2,missing)),(0,code_1.reportMissingProp)(cxt,missing),gen.else()}function loopAllRequired(){gen.forOf("prop",schemaCode,prop=>{cxt.setParams({missingProperty:prop}),gen.if((0,code_1.noPropertyInData)(gen,data,prop,opts.ownProperties),()=>cxt.error())})}function loopUntilMissing(missing,valid){cxt.setParams({missingProperty:missing}),gen.forOf(missing,schemaCode,()=>{gen.assign(valid,(0,code_1.propertyInData)(gen,data,missing,opts.ownProperties)),gen.if((0,codegen_1.not)(valid),()=>{cxt.error(),gen.break()})},codegen_1.nil)}}};exports.default=def})),require_limitItems=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),def={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword,schemaCode}){let comp=keyword==="maxItems"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`},code(cxt){let{keyword,data,schemaCode}=cxt,op=keyword==="maxItems"?codegen_1.operators.GT:codegen_1.operators.LT;cxt.fail$data((0,codegen_1._)`${data}.length ${op} ${schemaCode}`)}};exports.default=def})),require_equal=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let equal=require_fast_deep_equal();equal.code='require("ajv/dist/runtime/equal").default',exports.default=equal})),require_uniqueItems=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dataType_1=require_dataType(),codegen_1=require_codegen(),util_1=require_util(),equal_1=require_equal(),def={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i,j}})=>(0,codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,params:({params:{i,j}})=>(0,codegen_1._)`{i: ${i}, j: ${j}}`},code(cxt){let{gen,data,$data,schema:schema2,parentSchema,schemaCode,it}=cxt;if(!$data&&!schema2)return;let valid=gen.let("valid"),itemTypes=parentSchema.items?(0,dataType_1.getSchemaTypes)(parentSchema.items):[];cxt.block$data(valid,validateUniqueItems,(0,codegen_1._)`${schemaCode} === false`),cxt.ok(valid);function validateUniqueItems(){let i=gen.let("i",(0,codegen_1._)`${data}.length`),j=gen.let("j");cxt.setParams({i,j}),gen.assign(valid,!0),gen.if((0,codegen_1._)`${i} > 1`,()=>(canOptimize()?loopN:loopN2)(i,j))}function canOptimize(){return itemTypes.length>0&&!itemTypes.some(t=>t==="object"||t==="array")}function loopN(i,j){let item=gen.name("item"),wrongType=(0,dataType_1.checkDataTypes)(itemTypes,item,it.opts.strictNumbers,dataType_1.DataType.Wrong),indices=gen.const("indices",(0,codegen_1._)`{}`);gen.for((0,codegen_1._)`;${i}--;`,()=>{gen.let(item,(0,codegen_1._)`${data}[${i}]`),gen.if(wrongType,(0,codegen_1._)`continue`),itemTypes.length>1&&gen.if((0,codegen_1._)`typeof ${item} == "string"`,(0,codegen_1._)`${item} += "_"`),gen.if((0,codegen_1._)`typeof ${indices}[${item}] == "number"`,()=>{gen.assign(j,(0,codegen_1._)`${indices}[${item}]`),cxt.error(),gen.assign(valid,!1).break()}).code((0,codegen_1._)`${indices}[${item}] = ${i}`)})}function loopN2(i,j){let eql=(0,util_1.useFunc)(gen,equal_1.default),outer=gen.name("outer");gen.label(outer).for((0,codegen_1._)`;${i}--;`,()=>gen.for((0,codegen_1._)`${j} = ${i}; ${j}--;`,()=>gen.if((0,codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`,()=>{cxt.error(),gen.assign(valid,!1).break(outer)})))}}};exports.default=def})),require_const=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),equal_1=require_equal(),def={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode})=>(0,codegen_1._)`{allowedValue: ${schemaCode}}`},code(cxt){let{gen,data,$data,schemaCode,schema:schema2}=cxt;$data||schema2&&typeof schema2=="object"?cxt.fail$data((0,codegen_1._)`!${(0,util_1.useFunc)(gen,equal_1.default)}(${data}, ${schemaCode})`):cxt.fail((0,codegen_1._)`${schema2} !== ${data}`)}};exports.default=def})),require_enum=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),equal_1=require_equal(),def={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode})=>(0,codegen_1._)`{allowedValues: ${schemaCode}}`},code(cxt){let{gen,data,$data,schema:schema2,schemaCode,it}=cxt;if(!$data&&schema2.length===0)throw new Error("enum must have non-empty array");let useLoop=schema2.length>=it.opts.loopEnum,eql,getEql=()=>eql??(eql=(0,util_1.useFunc)(gen,equal_1.default)),valid;if(useLoop||$data)valid=gen.let("valid"),cxt.block$data(valid,loopEnum);else{if(!Array.isArray(schema2))throw new Error("ajv implementation error");let vSchema=gen.const("vSchema",schemaCode);valid=(0,codegen_1.or)(...schema2.map((_x,i)=>equalCode(vSchema,i)))}cxt.pass(valid);function loopEnum(){gen.assign(valid,!1),gen.forOf("v",schemaCode,v=>gen.if((0,codegen_1._)`${getEql()}(${data}, ${v})`,()=>gen.assign(valid,!0).break()))}function equalCode(vSchema,i){let sch=schema2[i];return typeof sch=="object"&&sch!==null?(0,codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])`:(0,codegen_1._)`${data} === ${sch}`}}};exports.default=def})),require_validation$2=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let limitNumber_1=require_limitNumber(),multipleOf_1=require_multipleOf(),limitLength_1=require_limitLength(),pattern_1=require_pattern(),limitProperties_1=require_limitProperties(),required_1=require_required(),limitItems_1=require_limitItems(),uniqueItems_1=require_uniqueItems(),const_1=require_const(),enum_1=require_enum(),validation=[limitNumber_1.default,multipleOf_1.default,limitLength_1.default,pattern_1.default,limitProperties_1.default,required_1.default,limitItems_1.default,uniqueItems_1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},const_1.default,enum_1.default];exports.default=validation})),require_additionalItems=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateAdditionalItems=void 0;let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},code(cxt){let{parentSchema,it}=cxt,{items}=parentSchema;if(!Array.isArray(items)){(0,util_1.checkStrictMode)(it,'"additionalItems" is ignored when "items" is not an array of schemas');return}validateAdditionalItems(cxt,items)}};function validateAdditionalItems(cxt,items){let{gen,schema:schema2,data,keyword,it}=cxt;it.items=!0;let len=gen.const("len",(0,codegen_1._)`${data}.length`);if(schema2===!1)cxt.setParams({len:items.length}),cxt.pass((0,codegen_1._)`${len} <= ${items.length}`);else if(typeof schema2=="object"&&!(0,util_1.alwaysValidSchema)(it,schema2)){let valid=gen.var("valid",(0,codegen_1._)`${len} <= ${items.length}`);gen.if((0,codegen_1.not)(valid),()=>validateItems(valid)),cxt.ok(valid)}function validateItems(valid){gen.forRange("i",items.length,len,i=>{cxt.subschema({keyword,dataProp:i,dataPropType:util_1.Type.Num},valid),it.allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break())})}}exports.validateAdditionalItems=validateAdditionalItems,exports.default=def})),require_items=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateTuple=void 0;let codegen_1=require_codegen(),util_1=require_util(),code_1=require_code(),def={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(cxt){let{schema:schema2,it}=cxt;if(Array.isArray(schema2))return validateTuple(cxt,"additionalItems",schema2);it.items=!0,!(0,util_1.alwaysValidSchema)(it,schema2)&&cxt.ok((0,code_1.validateArray)(cxt))}};function validateTuple(cxt,extraItems,schArr=cxt.schema){let{gen,parentSchema,data,keyword,it}=cxt;checkStrictTuple(parentSchema),it.opts.unevaluated&&schArr.length&&it.items!==!0&&(it.items=util_1.mergeEvaluated.items(gen,schArr.length,it.items));let valid=gen.name("valid"),len=gen.const("len",(0,codegen_1._)`${data}.length`);schArr.forEach((sch,i)=>{(0,util_1.alwaysValidSchema)(it,sch)||(gen.if((0,codegen_1._)`${len} > ${i}`,()=>cxt.subschema({keyword,schemaProp:i,dataProp:i},valid)),cxt.ok(valid))});function checkStrictTuple(sch){let{opts,errSchemaPath}=it,l=schArr.length,fullTuple=l===sch.minItems&&(l===sch.maxItems||sch[extraItems]===!1);if(opts.strictTuples&&!fullTuple){let msg=`"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;(0,util_1.checkStrictMode)(it,msg,opts.strictTuples)}}}exports.validateTuple=validateTuple,exports.default=def})),require_prefixItems=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let items_1=require_items(),def={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:cxt=>(0,items_1.validateTuple)(cxt,"items")};exports.default=def})),require_items2020=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),code_1=require_code(),additionalItems_1=require_additionalItems(),def={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},code(cxt){let{schema:schema2,parentSchema,it}=cxt,{prefixItems}=parentSchema;it.items=!0,!(0,util_1.alwaysValidSchema)(it,schema2)&&(prefixItems?(0,additionalItems_1.validateAdditionalItems)(cxt,prefixItems):cxt.ok((0,code_1.validateArray)(cxt)))}};exports.default=def})),require_contains=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min,max}})=>max===void 0?(0,codegen_1.str)`must contain at least ${min} valid item(s)`:(0,codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,params:({params:{min,max}})=>max===void 0?(0,codegen_1._)`{minContains: ${min}}`:(0,codegen_1._)`{minContains: ${min}, maxContains: ${max}}`},code(cxt){let{gen,schema:schema2,parentSchema,data,it}=cxt,min,max,{minContains,maxContains}=parentSchema;it.opts.next?(min=minContains===void 0?1:minContains,max=maxContains):min=1;let len=gen.const("len",(0,codegen_1._)`${data}.length`);if(cxt.setParams({min,max}),max===void 0&&min===0){(0,util_1.checkStrictMode)(it,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(max!==void 0&&min>max){(0,util_1.checkStrictMode)(it,'"minContains" > "maxContains" is always invalid'),cxt.fail();return}if((0,util_1.alwaysValidSchema)(it,schema2)){let cond=(0,codegen_1._)`${len} >= ${min}`;max!==void 0&&(cond=(0,codegen_1._)`${cond} && ${len} <= ${max}`),cxt.pass(cond);return}it.items=!0;let valid=gen.name("valid");max===void 0&&min===1?validateItems(valid,()=>gen.if(valid,()=>gen.break())):min===0?(gen.let(valid,!0),max!==void 0&&gen.if((0,codegen_1._)`${data}.length > 0`,validateItemsWithCount)):(gen.let(valid,!1),validateItemsWithCount()),cxt.result(valid,()=>cxt.reset());function validateItemsWithCount(){let schValid=gen.name("_valid"),count=gen.let("count",0);validateItems(schValid,()=>gen.if(schValid,()=>checkLimits(count)))}function validateItems(_valid,block){gen.forRange("i",0,len,i=>{cxt.subschema({keyword:"contains",dataProp:i,dataPropType:util_1.Type.Num,compositeRule:!0},_valid),block()})}function checkLimits(count){gen.code((0,codegen_1._)`${count}++`),max===void 0?gen.if((0,codegen_1._)`${count} >= ${min}`,()=>gen.assign(valid,!0).break()):(gen.if((0,codegen_1._)`${count} > ${max}`,()=>gen.assign(valid,!1).break()),min===1?gen.assign(valid,!0):gen.if((0,codegen_1._)`${count} >= ${min}`,()=>gen.assign(valid,!0)))}}};exports.default=def})),require_dependencies=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateSchemaDeps=exports.validatePropertyDeps=exports.error=void 0;let codegen_1=require_codegen(),util_1=require_util(),code_1=require_code();exports.error={message:({params:{property,depsCount,deps}})=>{let property_ies=depsCount===1?"property":"properties";return(0,codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`},params:({params:{property,depsCount,deps,missingProperty}})=>(0,codegen_1._)`{property: ${property},
61
+ || ${dataType} === "boolean" || ${data} === null`).assign(coerced,(0,codegen_1._)`[${data}]`)}}}function assignParentData({gen,parentData,parentDataProperty},expr){gen.if((0,codegen_1._)`${parentData} !== undefined`,()=>gen.assign((0,codegen_1._)`${parentData}[${parentDataProperty}]`,expr))}function checkDataType(dataType,data,strictNums,correct=DataType.Correct){let EQ=correct===DataType.Correct?codegen_1.operators.EQ:codegen_1.operators.NEQ,cond;switch(dataType){case"null":return(0,codegen_1._)`${data} ${EQ} null`;case"array":cond=(0,codegen_1._)`Array.isArray(${data})`;break;case"object":cond=(0,codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;break;case"integer":cond=numCond((0,codegen_1._)`!(${data} % 1) && !isNaN(${data})`);break;case"number":cond=numCond();break;default:return(0,codegen_1._)`typeof ${data} ${EQ} ${dataType}`}return correct===DataType.Correct?cond:(0,codegen_1.not)(cond);function numCond(_cond=codegen_1.nil){return(0,codegen_1.and)((0,codegen_1._)`typeof ${data} == "number"`,_cond,strictNums?(0,codegen_1._)`isFinite(${data})`:codegen_1.nil)}}exports.checkDataType=checkDataType;function checkDataTypes(dataTypes,data,strictNums,correct){if(dataTypes.length===1)return checkDataType(dataTypes[0],data,strictNums,correct);let cond,types=(0,util_1.toHash)(dataTypes);if(types.array&&types.object){let notObj=(0,codegen_1._)`typeof ${data} != "object"`;cond=types.null?notObj:(0,codegen_1._)`!${data} || ${notObj}`,delete types.null,delete types.array,delete types.object}else cond=codegen_1.nil;types.number&&delete types.integer;for(let t in types)cond=(0,codegen_1.and)(cond,checkDataType(t,data,strictNums,correct));return cond}exports.checkDataTypes=checkDataTypes;let typeError={message:({schema:schema2})=>`must be ${schema2}`,params:({schema:schema2,schemaValue})=>typeof schema2=="string"?(0,codegen_1._)`{type: ${schema2}}`:(0,codegen_1._)`{type: ${schemaValue}}`};function reportTypeError(it){let cxt=getTypeErrorContext(it);(0,errors_1.reportError)(cxt,typeError)}exports.reportTypeError=reportTypeError;function getTypeErrorContext(it){let{gen,data,schema:schema2}=it,schemaCode=(0,util_1.schemaRefOrVal)(it,schema2,"type");return{gen,keyword:"type",data,schema:schema2.type,schemaCode,schemaValue:schemaCode,parentSchema:schema2,params:{},it}}})),require_defaults=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.assignDefaults=void 0;let codegen_1=require_codegen(),util_1=require_util();function assignDefaults(it,ty){let{properties,items}=it.schema;if(ty==="object"&&properties)for(let key in properties)assignDefault(it,key,properties[key].default);else ty==="array"&&Array.isArray(items)&&items.forEach((sch,i)=>assignDefault(it,i,sch.default))}exports.assignDefaults=assignDefaults;function assignDefault(it,prop,defaultValue){let{gen,compositeRule,data,opts}=it;if(defaultValue===void 0)return;let childData=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(prop)}`;if(compositeRule){(0,util_1.checkStrictMode)(it,`default is ignored for: ${childData}`);return}let condition=(0,codegen_1._)`${childData} === undefined`;opts.useDefaults==="empty"&&(condition=(0,codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`),gen.if(condition,(0,codegen_1._)`${childData} = ${(0,codegen_1.stringify)(defaultValue)}`)}})),require_code=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateUnion=exports.validateArray=exports.usePattern=exports.callValidateCode=exports.schemaProperties=exports.allSchemaProperties=exports.noPropertyInData=exports.propertyInData=exports.isOwnProperty=exports.hasPropFunc=exports.reportMissingProp=exports.checkMissingProp=exports.checkReportMissingProp=void 0;let codegen_1=require_codegen(),util_1=require_util(),names_1=require_names(),util_2=require_util();function checkReportMissingProp(cxt,prop){let{gen,data,it}=cxt;gen.if(noPropertyInData(gen,data,prop,it.opts.ownProperties),()=>{cxt.setParams({missingProperty:(0,codegen_1._)`${prop}`},!0),cxt.error()})}exports.checkReportMissingProp=checkReportMissingProp;function checkMissingProp({gen,data,it:{opts}},properties,missing){return(0,codegen_1.or)(...properties.map(prop=>(0,codegen_1.and)(noPropertyInData(gen,data,prop,opts.ownProperties),(0,codegen_1._)`${missing} = ${prop}`)))}exports.checkMissingProp=checkMissingProp;function reportMissingProp(cxt,missing){cxt.setParams({missingProperty:missing},!0),cxt.error()}exports.reportMissingProp=reportMissingProp;function hasPropFunc(gen){return gen.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,codegen_1._)`Object.prototype.hasOwnProperty`})}exports.hasPropFunc=hasPropFunc;function isOwnProperty(gen,data,property){return(0,codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`}exports.isOwnProperty=isOwnProperty;function propertyInData(gen,data,property,ownProperties){let cond=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(property)} !== undefined`;return ownProperties?(0,codegen_1._)`${cond} && ${isOwnProperty(gen,data,property)}`:cond}exports.propertyInData=propertyInData;function noPropertyInData(gen,data,property,ownProperties){let cond=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(property)} === undefined`;return ownProperties?(0,codegen_1.or)(cond,(0,codegen_1.not)(isOwnProperty(gen,data,property))):cond}exports.noPropertyInData=noPropertyInData;function allSchemaProperties(schemaMap){return schemaMap?Object.keys(schemaMap).filter(p=>p!=="__proto__"):[]}exports.allSchemaProperties=allSchemaProperties;function schemaProperties(it,schemaMap){return allSchemaProperties(schemaMap).filter(p=>!(0,util_1.alwaysValidSchema)(it,schemaMap[p]))}exports.schemaProperties=schemaProperties;function callValidateCode({schemaCode,data,it:{gen,topSchemaRef,schemaPath,errorPath},it},func,context,passSchema){let dataAndSchema=passSchema?(0,codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}`:data,valCxt=[[names_1.default.instancePath,(0,codegen_1.strConcat)(names_1.default.instancePath,errorPath)],[names_1.default.parentData,it.parentData],[names_1.default.parentDataProperty,it.parentDataProperty],[names_1.default.rootData,names_1.default.rootData]];it.opts.dynamicRef&&valCxt.push([names_1.default.dynamicAnchors,names_1.default.dynamicAnchors]);let args=(0,codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;return context!==codegen_1.nil?(0,codegen_1._)`${func}.call(${context}, ${args})`:(0,codegen_1._)`${func}(${args})`}exports.callValidateCode=callValidateCode;let newRegExp=(0,codegen_1._)`new RegExp`;function usePattern({gen,it:{opts}},pattern){let u=opts.unicodeRegExp?"u":"",{regExp}=opts.code,rx=regExp(pattern,u);return gen.scopeValue("pattern",{key:rx.toString(),ref:rx,code:(0,codegen_1._)`${regExp.code==="new RegExp"?newRegExp:(0,util_2.useFunc)(gen,regExp)}(${pattern}, ${u})`})}exports.usePattern=usePattern;function validateArray(cxt){let{gen,data,keyword,it}=cxt,valid=gen.name("valid");if(it.allErrors){let validArr=gen.let("valid",!0);return validateItems(()=>gen.assign(validArr,!1)),validArr}return gen.var(valid,!0),validateItems(()=>gen.break()),valid;function validateItems(notValid){let len=gen.const("len",(0,codegen_1._)`${data}.length`);gen.forRange("i",0,len,i=>{cxt.subschema({keyword,dataProp:i,dataPropType:util_1.Type.Num},valid),gen.if((0,codegen_1.not)(valid),notValid)})}}exports.validateArray=validateArray;function validateUnion(cxt){let{gen,schema:schema2,keyword,it}=cxt;if(!Array.isArray(schema2))throw new Error("ajv implementation error");if(schema2.some(sch=>(0,util_1.alwaysValidSchema)(it,sch))&&!it.opts.unevaluated)return;let valid=gen.let("valid",!1),schValid=gen.name("_valid");gen.block(()=>schema2.forEach((_sch,i)=>{let schCxt=cxt.subschema({keyword,schemaProp:i,compositeRule:!0},schValid);gen.assign(valid,(0,codegen_1._)`${valid} || ${schValid}`),cxt.mergeValidEvaluated(schCxt,schValid)||gen.if((0,codegen_1.not)(valid))})),cxt.result(valid,()=>cxt.reset(),()=>cxt.error(!0))}exports.validateUnion=validateUnion})),require_keyword=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateKeywordUsage=exports.validSchemaType=exports.funcKeywordCode=exports.macroKeywordCode=void 0;let codegen_1=require_codegen(),names_1=require_names(),code_1=require_code(),errors_1=require_errors();function macroKeywordCode(cxt,def){let{gen,keyword,schema:schema2,parentSchema,it}=cxt,macroSchema=def.macro.call(it.self,schema2,parentSchema,it),schemaRef=useKeyword(gen,keyword,macroSchema);it.opts.validateSchema!==!1&&it.self.validateSchema(macroSchema,!0);let valid=gen.name("valid");cxt.subschema({schema:macroSchema,schemaPath:codegen_1.nil,errSchemaPath:`${it.errSchemaPath}/${keyword}`,topSchemaRef:schemaRef,compositeRule:!0},valid),cxt.pass(valid,()=>cxt.error(!0))}exports.macroKeywordCode=macroKeywordCode;function funcKeywordCode(cxt,def){var _a3;let{gen,keyword,schema:schema2,parentSchema,$data,it}=cxt;checkAsyncKeyword(it,def);let validateRef=useKeyword(gen,keyword,!$data&&def.compile?def.compile.call(it.self,schema2,parentSchema,it):def.validate),valid=gen.let("valid");cxt.block$data(valid,validateKeyword),cxt.ok((_a3=def.valid)!==null&&_a3!==void 0?_a3:valid);function validateKeyword(){if(def.errors===!1)assignValid(),def.modifying&&modifyData(cxt),reportErrs(()=>cxt.error());else{let ruleErrs=def.async?validateAsync3():validateSync();def.modifying&&modifyData(cxt),reportErrs(()=>addErrs(cxt,ruleErrs))}}function validateAsync3(){let ruleErrs=gen.let("ruleErrs",null);return gen.try(()=>assignValid((0,codegen_1._)`await `),e=>gen.assign(valid,!1).if((0,codegen_1._)`${e} instanceof ${it.ValidationError}`,()=>gen.assign(ruleErrs,(0,codegen_1._)`${e}.errors`),()=>gen.throw(e))),ruleErrs}function validateSync(){let validateErrs=(0,codegen_1._)`${validateRef}.errors`;return gen.assign(validateErrs,null),assignValid(codegen_1.nil),validateErrs}function assignValid(_await=def.async?(0,codegen_1._)`await `:codegen_1.nil){let passCxt=it.opts.passContext?names_1.default.this:names_1.default.self,passSchema=!("compile"in def&&!$data||def.schema===!1);gen.assign(valid,(0,codegen_1._)`${_await}${(0,code_1.callValidateCode)(cxt,validateRef,passCxt,passSchema)}`,def.modifying)}function reportErrs(errors2){var _a$1;gen.if((0,codegen_1.not)((_a$1=def.valid)!==null&&_a$1!==void 0?_a$1:valid),errors2)}}exports.funcKeywordCode=funcKeywordCode;function modifyData(cxt){let{gen,data,it}=cxt;gen.if(it.parentData,()=>gen.assign(data,(0,codegen_1._)`${it.parentData}[${it.parentDataProperty}]`))}function addErrs(cxt,errs){let{gen}=cxt;gen.if((0,codegen_1._)`Array.isArray(${errs})`,()=>{gen.assign(names_1.default.vErrors,(0,codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors,(0,codegen_1._)`${names_1.default.vErrors}.length`),(0,errors_1.extendErrors)(cxt)},()=>cxt.error())}function checkAsyncKeyword({schemaEnv},def){if(def.async&&!schemaEnv.$async)throw new Error("async keyword in sync schema")}function useKeyword(gen,keyword,result){if(result===void 0)throw new Error(`keyword "${keyword}" failed to compile`);return gen.scopeValue("keyword",typeof result=="function"?{ref:result}:{ref:result,code:(0,codegen_1.stringify)(result)})}function validSchemaType(schema2,schemaType,allowUndefined=!1){return!schemaType.length||schemaType.some(st=>st==="array"?Array.isArray(schema2):st==="object"?schema2&&typeof schema2=="object"&&!Array.isArray(schema2):typeof schema2==st||allowUndefined&&typeof schema2>"u")}exports.validSchemaType=validSchemaType;function validateKeywordUsage({schema:schema2,opts,self,errSchemaPath},def,keyword){if(Array.isArray(def.keyword)?!def.keyword.includes(keyword):def.keyword!==keyword)throw new Error("ajv implementation error");let deps=def.dependencies;if(deps?.some(kwd=>!Object.prototype.hasOwnProperty.call(schema2,kwd)))throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);if(def.validateSchema&&!def.validateSchema(schema2[keyword])){let msg=`keyword "${keyword}" value is invalid at path "${errSchemaPath}": `+self.errorsText(def.validateSchema.errors);if(opts.validateSchema==="log")self.logger.error(msg);else throw new Error(msg)}}exports.validateKeywordUsage=validateKeywordUsage})),require_subschema=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.extendSubschemaMode=exports.extendSubschemaData=exports.getSubschema=void 0;let codegen_1=require_codegen(),util_1=require_util();function getSubschema(it,{keyword,schemaProp,schema:schema2,schemaPath,errSchemaPath,topSchemaRef}){if(keyword!==void 0&&schema2!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(keyword!==void 0){let sch=it.schema[keyword];return schemaProp===void 0?{schema:sch,schemaPath:(0,codegen_1._)`${it.schemaPath}${(0,codegen_1.getProperty)(keyword)}`,errSchemaPath:`${it.errSchemaPath}/${keyword}`}:{schema:sch[schemaProp],schemaPath:(0,codegen_1._)`${it.schemaPath}${(0,codegen_1.getProperty)(keyword)}${(0,codegen_1.getProperty)(schemaProp)}`,errSchemaPath:`${it.errSchemaPath}/${keyword}/${(0,util_1.escapeFragment)(schemaProp)}`}}if(schema2!==void 0){if(schemaPath===void 0||errSchemaPath===void 0||topSchemaRef===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:schema2,schemaPath,topSchemaRef,errSchemaPath}}throw new Error('either "keyword" or "schema" must be passed')}exports.getSubschema=getSubschema;function extendSubschemaData(subschema,it,{dataProp,dataPropType:dpType,data,dataTypes,propertyName}){if(data!==void 0&&dataProp!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen}=it;if(dataProp!==void 0){let{errorPath,dataPathArr,opts}=it;dataContextProps(gen.let("data",(0,codegen_1._)`${it.data}${(0,codegen_1.getProperty)(dataProp)}`,!0)),subschema.errorPath=(0,codegen_1.str)`${errorPath}${(0,util_1.getErrorPath)(dataProp,dpType,opts.jsPropertySyntax)}`,subschema.parentDataProperty=(0,codegen_1._)`${dataProp}`,subschema.dataPathArr=[...dataPathArr,subschema.parentDataProperty]}data!==void 0&&(dataContextProps(data instanceof codegen_1.Name?data:gen.let("data",data,!0)),propertyName!==void 0&&(subschema.propertyName=propertyName)),dataTypes&&(subschema.dataTypes=dataTypes);function dataContextProps(_nextData){subschema.data=_nextData,subschema.dataLevel=it.dataLevel+1,subschema.dataTypes=[],it.definedProperties=new Set,subschema.parentData=it.data,subschema.dataNames=[...it.dataNames,_nextData]}}exports.extendSubschemaData=extendSubschemaData;function extendSubschemaMode(subschema,{jtdDiscriminator,jtdMetadata,compositeRule,createErrors,allErrors}){compositeRule!==void 0&&(subschema.compositeRule=compositeRule),createErrors!==void 0&&(subschema.createErrors=createErrors),allErrors!==void 0&&(subschema.allErrors=allErrors),subschema.jtdDiscriminator=jtdDiscriminator,subschema.jtdMetadata=jtdMetadata}exports.extendSubschemaMode=extendSubschemaMode})),require_fast_deep_equal=__commonJSMin(((exports,module)=>{module.exports=function equal(a,b){if(a===b)return!0;if(a&&b&&typeof a=="object"&&typeof b=="object"){if(a.constructor!==b.constructor)return!1;var length,i,keys2;if(Array.isArray(a)){if(length=a.length,length!=b.length)return!1;for(i=length;i--!==0;)if(!equal(a[i],b[i]))return!1;return!0}if(a.constructor===RegExp)return a.source===b.source&&a.flags===b.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===b.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===b.toString();if(keys2=Object.keys(a),length=keys2.length,length!==Object.keys(b).length)return!1;for(i=length;i--!==0;)if(!Object.prototype.hasOwnProperty.call(b,keys2[i]))return!1;for(i=length;i--!==0;){var key=keys2[i];if(!equal(a[key],b[key]))return!1}return!0}return a!==a&&b!==b}})),require_json_schema_traverse=__commonJSMin(((exports,module)=>{var traverse=module.exports=function(schema2,opts,cb){typeof opts=="function"&&(cb=opts,opts={}),cb=opts.cb||cb;var pre=typeof cb=="function"?cb:cb.pre||function(){},post=cb.post||function(){};_traverse(opts,pre,post,schema2,"",schema2)};traverse.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},traverse.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},traverse.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},traverse.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function _traverse(opts,pre,post,schema2,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex){if(schema2&&typeof schema2=="object"&&!Array.isArray(schema2)){pre(schema2,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex);for(var key in schema2){var sch=schema2[key];if(Array.isArray(sch)){if(key in traverse.arrayKeywords)for(var i=0;i<sch.length;i++)_traverse(opts,pre,post,sch[i],jsonPtr+"/"+key+"/"+i,rootSchema,jsonPtr,key,schema2,i)}else if(key in traverse.propsKeywords){if(sch&&typeof sch=="object")for(var prop in sch)_traverse(opts,pre,post,sch[prop],jsonPtr+"/"+key+"/"+escapeJsonPtr(prop),rootSchema,jsonPtr,key,schema2,prop)}else(key in traverse.keywords||opts.allKeys&&!(key in traverse.skipKeywords))&&_traverse(opts,pre,post,sch,jsonPtr+"/"+key,rootSchema,jsonPtr,key,schema2)}post(schema2,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex)}}function escapeJsonPtr(str){return str.replace(/~/g,"~0").replace(/\//g,"~1")}})),require_resolve=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.getSchemaRefs=exports.resolveUrl=exports.normalizeId=exports._getFullPath=exports.getFullPath=exports.inlineRef=void 0;let util_1=require_util(),equal=require_fast_deep_equal(),traverse=require_json_schema_traverse(),SIMPLE_INLINED=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function inlineRef(schema2,limit=!0){return typeof schema2=="boolean"?!0:limit===!0?!hasRef(schema2):limit?countKeys(schema2)<=limit:!1}exports.inlineRef=inlineRef;let REF_KEYWORDS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function hasRef(schema2){for(let key in schema2){if(REF_KEYWORDS.has(key))return!0;let sch=schema2[key];if(Array.isArray(sch)&&sch.some(hasRef)||typeof sch=="object"&&hasRef(sch))return!0}return!1}function countKeys(schema2){let count=0;for(let key in schema2){if(key==="$ref")return 1/0;if(count++,!SIMPLE_INLINED.has(key)&&(typeof schema2[key]=="object"&&(0,util_1.eachItem)(schema2[key],sch=>count+=countKeys(sch)),count===1/0))return 1/0}return count}function getFullPath(resolver,id="",normalize){return normalize!==!1&&(id=normalizeId(id)),_getFullPath(resolver,resolver.parse(id))}exports.getFullPath=getFullPath;function _getFullPath(resolver,p){return resolver.serialize(p).split("#")[0]+"#"}exports._getFullPath=_getFullPath;let TRAILING_SLASH_HASH=/#\/?$/;function normalizeId(id){return id?id.replace(TRAILING_SLASH_HASH,""):""}exports.normalizeId=normalizeId;function resolveUrl(resolver,baseId,id){return id=normalizeId(id),resolver.resolve(baseId,id)}exports.resolveUrl=resolveUrl;let ANCHOR=/^[a-z_][-a-z0-9._]*$/i;function getSchemaRefs(schema2,baseId){if(typeof schema2=="boolean")return{};let{schemaId,uriResolver}=this.opts,schId=normalizeId(schema2[schemaId]||baseId),baseIds={"":schId},pathPrefix=getFullPath(uriResolver,schId,!1),localRefs={},schemaRefs=new Set;return traverse(schema2,{allKeys:!0},(sch,jsonPtr,_,parentJsonPtr)=>{if(parentJsonPtr===void 0)return;let fullPath=pathPrefix+jsonPtr,innerBaseId=baseIds[parentJsonPtr];typeof sch[schemaId]=="string"&&(innerBaseId=addRef.call(this,sch[schemaId])),addAnchor.call(this,sch.$anchor),addAnchor.call(this,sch.$dynamicAnchor),baseIds[jsonPtr]=innerBaseId;function addRef(ref){let _resolve=this.opts.uriResolver.resolve;if(ref=normalizeId(innerBaseId?_resolve(innerBaseId,ref):ref),schemaRefs.has(ref))throw ambiguos(ref);schemaRefs.add(ref);let schOrRef=this.refs[ref];return typeof schOrRef=="string"&&(schOrRef=this.refs[schOrRef]),typeof schOrRef=="object"?checkAmbiguosRef(sch,schOrRef.schema,ref):ref!==normalizeId(fullPath)&&(ref[0]==="#"?(checkAmbiguosRef(sch,localRefs[ref],ref),localRefs[ref]=sch):this.refs[ref]=fullPath),ref}function addAnchor(anchor2){if(typeof anchor2=="string"){if(!ANCHOR.test(anchor2))throw new Error(`invalid anchor "${anchor2}"`);addRef.call(this,`#${anchor2}`)}}}),localRefs;function checkAmbiguosRef(sch1,sch2,ref){if(sch2!==void 0&&!equal(sch1,sch2))throw ambiguos(ref)}function ambiguos(ref){return new Error(`reference "${ref}" resolves to more than one schema`)}}exports.getSchemaRefs=getSchemaRefs})),require_validate=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.getData=exports.KeywordCxt=exports.validateFunctionCode=void 0;let boolSchema_1=require_boolSchema(),dataType_1=require_dataType(),applicability_1=require_applicability(),dataType_2=require_dataType(),defaults_1=require_defaults(),keyword_1=require_keyword(),subschema_1=require_subschema(),codegen_1=require_codegen(),names_1=require_names(),resolve_1=require_resolve(),util_1=require_util(),errors_1=require_errors();function validateFunctionCode(it){if(isSchemaObj(it)&&(checkKeywords(it),schemaCxtHasRules(it))){topSchemaObjCode(it);return}validateFunction(it,()=>(0,boolSchema_1.topBoolOrEmptySchema)(it))}exports.validateFunctionCode=validateFunctionCode;function validateFunction({gen,validateName,schema:schema2,schemaEnv,opts},body){opts.code.es5?gen.func(validateName,(0,codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`,schemaEnv.$async,()=>{gen.code((0,codegen_1._)`"use strict"; ${funcSourceUrl(schema2,opts)}`),destructureValCxtES5(gen,opts),gen.code(body)}):gen.func(validateName,(0,codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`,schemaEnv.$async,()=>gen.code(funcSourceUrl(schema2,opts)).code(body))}function destructureValCxt(opts){return(0,codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef?(0,codegen_1._)`, ${names_1.default.dynamicAnchors}={}`:codegen_1.nil}}={}`}function destructureValCxtES5(gen,opts){gen.if(names_1.default.valCxt,()=>{gen.var(names_1.default.instancePath,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`),gen.var(names_1.default.parentData,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`),gen.var(names_1.default.parentDataProperty,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`),gen.var(names_1.default.rootData,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`),opts.dynamicRef&&gen.var(names_1.default.dynamicAnchors,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`)},()=>{gen.var(names_1.default.instancePath,(0,codegen_1._)`""`),gen.var(names_1.default.parentData,(0,codegen_1._)`undefined`),gen.var(names_1.default.parentDataProperty,(0,codegen_1._)`undefined`),gen.var(names_1.default.rootData,names_1.default.data),opts.dynamicRef&&gen.var(names_1.default.dynamicAnchors,(0,codegen_1._)`{}`)})}function topSchemaObjCode(it){let{schema:schema2,opts,gen}=it;validateFunction(it,()=>{opts.$comment&&schema2.$comment&&commentKeyword(it),checkNoDefault(it),gen.let(names_1.default.vErrors,null),gen.let(names_1.default.errors,0),opts.unevaluated&&resetEvaluated(it),typeAndKeywords(it),returnResults(it)})}function resetEvaluated(it){let{gen,validateName}=it;it.evaluated=gen.const("evaluated",(0,codegen_1._)`${validateName}.evaluated`),gen.if((0,codegen_1._)`${it.evaluated}.dynamicProps`,()=>gen.assign((0,codegen_1._)`${it.evaluated}.props`,(0,codegen_1._)`undefined`)),gen.if((0,codegen_1._)`${it.evaluated}.dynamicItems`,()=>gen.assign((0,codegen_1._)`${it.evaluated}.items`,(0,codegen_1._)`undefined`))}function funcSourceUrl(schema2,opts){let schId=typeof schema2=="object"&&schema2[opts.schemaId];return schId&&(opts.code.source||opts.code.process)?(0,codegen_1._)`/*# sourceURL=${schId} */`:codegen_1.nil}function subschemaCode(it,valid){if(isSchemaObj(it)&&(checkKeywords(it),schemaCxtHasRules(it))){subSchemaObjCode(it,valid);return}(0,boolSchema_1.boolOrEmptySchema)(it,valid)}function schemaCxtHasRules({schema:schema2,self}){if(typeof schema2=="boolean")return!schema2;for(let key in schema2)if(self.RULES.all[key])return!0;return!1}function isSchemaObj(it){return typeof it.schema!="boolean"}function subSchemaObjCode(it,valid){let{schema:schema2,gen,opts}=it;opts.$comment&&schema2.$comment&&commentKeyword(it),updateContext(it),checkAsyncSchema(it);let errsCount=gen.const("_errs",names_1.default.errors);typeAndKeywords(it,errsCount),gen.var(valid,(0,codegen_1._)`${errsCount} === ${names_1.default.errors}`)}function checkKeywords(it){(0,util_1.checkUnknownRules)(it),checkRefsAndKeywords(it)}function typeAndKeywords(it,errsCount){if(it.opts.jtd)return schemaKeywords(it,[],!1,errsCount);let types=(0,dataType_1.getSchemaTypes)(it.schema);schemaKeywords(it,types,!(0,dataType_1.coerceAndCheckDataType)(it,types),errsCount)}function checkRefsAndKeywords(it){let{schema:schema2,errSchemaPath,opts,self}=it;schema2.$ref&&opts.ignoreKeywordsWithRef&&(0,util_1.schemaHasRulesButRef)(schema2,self.RULES)&&self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)}function checkNoDefault(it){let{schema:schema2,opts}=it;schema2.default!==void 0&&opts.useDefaults&&opts.strictSchema&&(0,util_1.checkStrictMode)(it,"default is ignored in the schema root")}function updateContext(it){let schId=it.schema[it.opts.schemaId];schId&&(it.baseId=(0,resolve_1.resolveUrl)(it.opts.uriResolver,it.baseId,schId))}function checkAsyncSchema(it){if(it.schema.$async&&!it.schemaEnv.$async)throw new Error("async schema in sync schema")}function commentKeyword({gen,schemaEnv,schema:schema2,errSchemaPath,opts}){let msg=schema2.$comment;if(opts.$comment===!0)gen.code((0,codegen_1._)`${names_1.default.self}.logger.log(${msg})`);else if(typeof opts.$comment=="function"){let schemaPath=(0,codegen_1.str)`${errSchemaPath}/$comment`,rootName=gen.scopeValue("root",{ref:schemaEnv.root});gen.code((0,codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)}}function returnResults(it){let{gen,schemaEnv,validateName,ValidationError,opts}=it;schemaEnv.$async?gen.if((0,codegen_1._)`${names_1.default.errors} === 0`,()=>gen.return(names_1.default.data),()=>gen.throw((0,codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)):(gen.assign((0,codegen_1._)`${validateName}.errors`,names_1.default.vErrors),opts.unevaluated&&assignEvaluated(it),gen.return((0,codegen_1._)`${names_1.default.errors} === 0`))}function assignEvaluated({gen,evaluated,props,items}){props instanceof codegen_1.Name&&gen.assign((0,codegen_1._)`${evaluated}.props`,props),items instanceof codegen_1.Name&&gen.assign((0,codegen_1._)`${evaluated}.items`,items)}function schemaKeywords(it,types,typeErrors,errsCount){let{gen,schema:schema2,data,allErrors,opts,self}=it,{RULES}=self;if(schema2.$ref&&(opts.ignoreKeywordsWithRef||!(0,util_1.schemaHasRulesButRef)(schema2,RULES))){gen.block(()=>keywordCode(it,"$ref",RULES.all.$ref.definition));return}opts.jtd||checkStrictTypes(it,types),gen.block(()=>{for(let group of RULES.rules)groupKeywords(group);groupKeywords(RULES.post)});function groupKeywords(group){(0,applicability_1.shouldUseGroup)(schema2,group)&&(group.type?(gen.if((0,dataType_2.checkDataType)(group.type,data,opts.strictNumbers)),iterateKeywords(it,group),types.length===1&&types[0]===group.type&&typeErrors&&(gen.else(),(0,dataType_2.reportTypeError)(it)),gen.endIf()):iterateKeywords(it,group),allErrors||gen.if((0,codegen_1._)`${names_1.default.errors} === ${errsCount||0}`))}}function iterateKeywords(it,group){let{gen,schema:schema2,opts:{useDefaults}}=it;useDefaults&&(0,defaults_1.assignDefaults)(it,group.type),gen.block(()=>{for(let rule of group.rules)(0,applicability_1.shouldUseRule)(schema2,rule)&&keywordCode(it,rule.keyword,rule.definition,group.type)})}function checkStrictTypes(it,types){it.schemaEnv.meta||!it.opts.strictTypes||(checkContextTypes(it,types),it.opts.allowUnionTypes||checkMultipleTypes(it,types),checkKeywordTypes(it,it.dataTypes))}function checkContextTypes(it,types){if(types.length){if(!it.dataTypes.length){it.dataTypes=types;return}types.forEach(t=>{includesType(it.dataTypes,t)||strictTypesError(it,`type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)}),narrowSchemaTypes(it,types)}}function checkMultipleTypes(it,ts){ts.length>1&&!(ts.length===2&&ts.includes("null"))&&strictTypesError(it,"use allowUnionTypes to allow union type keyword")}function checkKeywordTypes(it,ts){let rules=it.self.RULES.all;for(let keyword in rules){let rule=rules[keyword];if(typeof rule=="object"&&(0,applicability_1.shouldUseRule)(it.schema,rule)){let{type}=rule.definition;type.length&&!type.some(t=>hasApplicableType(ts,t))&&strictTypesError(it,`missing type "${type.join(",")}" for keyword "${keyword}"`)}}}function hasApplicableType(schTs,kwdT){return schTs.includes(kwdT)||kwdT==="number"&&schTs.includes("integer")}function includesType(ts,t){return ts.includes(t)||t==="integer"&&ts.includes("number")}function narrowSchemaTypes(it,withTypes){let ts=[];for(let t of it.dataTypes)includesType(withTypes,t)?ts.push(t):withTypes.includes("integer")&&t==="number"&&ts.push("integer");it.dataTypes=ts}function strictTypesError(it,msg){let schemaPath=it.schemaEnv.baseId+it.errSchemaPath;msg+=` at "${schemaPath}" (strictTypes)`,(0,util_1.checkStrictMode)(it,msg,it.opts.strictTypes)}var KeywordCxt=class{constructor(it,def,keyword){if((0,keyword_1.validateKeywordUsage)(it,def,keyword),this.gen=it.gen,this.allErrors=it.allErrors,this.keyword=keyword,this.data=it.data,this.schema=it.schema[keyword],this.$data=def.$data&&it.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,util_1.schemaRefOrVal)(it,this.schema,keyword,this.$data),this.schemaType=def.schemaType,this.parentSchema=it.schema,this.params={},this.it=it,this.def=def,this.$data)this.schemaCode=it.gen.const("vSchema",getData(this.$data,it));else if(this.schemaCode=this.schemaValue,!(0,keyword_1.validSchemaType)(this.schema,def.schemaType,def.allowUndefined))throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);("code"in def?def.trackErrors:def.errors!==!1)&&(this.errsCount=it.gen.const("_errs",names_1.default.errors))}result(condition,successAction,failAction){this.failResult((0,codegen_1.not)(condition),successAction,failAction)}failResult(condition,successAction,failAction){this.gen.if(condition),failAction?failAction():this.error(),successAction?(this.gen.else(),successAction(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(condition,failAction){this.failResult((0,codegen_1.not)(condition),void 0,failAction)}fail(condition){if(condition===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(condition),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(condition){if(!this.$data)return this.fail(condition);let{schemaCode}=this;this.fail((0,codegen_1._)`${schemaCode} !== undefined && (${(0,codegen_1.or)(this.invalid$data(),condition)})`)}error(append,errorParams,errorPaths){if(errorParams){this.setParams(errorParams),this._error(append,errorPaths),this.setParams({});return}this._error(append,errorPaths)}_error(append,errorPaths){(append?errors_1.reportExtraError:errors_1.reportError)(this,this.def.error,errorPaths)}$dataError(){(0,errors_1.reportError)(this,this.def.$dataError||errors_1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,errors_1.resetErrorsCount)(this.gen,this.errsCount)}ok(cond){this.allErrors||this.gen.if(cond)}setParams(obj,assign){assign?Object.assign(this.params,obj):this.params=obj}block$data(valid,codeBlock,$dataValid=codegen_1.nil){this.gen.block(()=>{this.check$data(valid,$dataValid),codeBlock()})}check$data(valid=codegen_1.nil,$dataValid=codegen_1.nil){if(!this.$data)return;let{gen,schemaCode,schemaType,def}=this;gen.if((0,codegen_1.or)((0,codegen_1._)`${schemaCode} === undefined`,$dataValid)),valid!==codegen_1.nil&&gen.assign(valid,!0),(schemaType.length||def.validateSchema)&&(gen.elseIf(this.invalid$data()),this.$dataError(),valid!==codegen_1.nil&&gen.assign(valid,!1)),gen.else()}invalid$data(){let{gen,schemaCode,schemaType,def,it}=this;return(0,codegen_1.or)(wrong$DataType(),invalid$DataSchema());function wrong$DataType(){if(schemaType.length){if(!(schemaCode instanceof codegen_1.Name))throw new Error("ajv implementation error");let st=Array.isArray(schemaType)?schemaType:[schemaType];return(0,codegen_1._)`${(0,dataType_2.checkDataTypes)(st,schemaCode,it.opts.strictNumbers,dataType_2.DataType.Wrong)}`}return codegen_1.nil}function invalid$DataSchema(){if(def.validateSchema){let validateSchemaRef=gen.scopeValue("validate$data",{ref:def.validateSchema});return(0,codegen_1._)`!${validateSchemaRef}(${schemaCode})`}return codegen_1.nil}}subschema(appl,valid){let subschema=(0,subschema_1.getSubschema)(this.it,appl);(0,subschema_1.extendSubschemaData)(subschema,this.it,appl),(0,subschema_1.extendSubschemaMode)(subschema,appl);let nextContext={...this.it,...subschema,items:void 0,props:void 0};return subschemaCode(nextContext,valid),nextContext}mergeEvaluated(schemaCxt,toName){let{it,gen}=this;it.opts.unevaluated&&(it.props!==!0&&schemaCxt.props!==void 0&&(it.props=util_1.mergeEvaluated.props(gen,schemaCxt.props,it.props,toName)),it.items!==!0&&schemaCxt.items!==void 0&&(it.items=util_1.mergeEvaluated.items(gen,schemaCxt.items,it.items,toName)))}mergeValidEvaluated(schemaCxt,valid){let{it,gen}=this;if(it.opts.unevaluated&&(it.props!==!0||it.items!==!0))return gen.if(valid,()=>this.mergeEvaluated(schemaCxt,codegen_1.Name)),!0}};exports.KeywordCxt=KeywordCxt;function keywordCode(it,keyword,def,ruleType){let cxt=new KeywordCxt(it,def,keyword);"code"in def?def.code(cxt,ruleType):cxt.$data&&def.validate?(0,keyword_1.funcKeywordCode)(cxt,def):"macro"in def?(0,keyword_1.macroKeywordCode)(cxt,def):(def.compile||def.validate)&&(0,keyword_1.funcKeywordCode)(cxt,def)}let JSON_POINTER=/^\/(?:[^~]|~0|~1)*$/,RELATIVE_JSON_POINTER=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData($data,{dataLevel,dataNames,dataPathArr}){let jsonPointer,data;if($data==="")return names_1.default.rootData;if($data[0]==="/"){if(!JSON_POINTER.test($data))throw new Error(`Invalid JSON-pointer: ${$data}`);jsonPointer=$data,data=names_1.default.rootData}else{let matches=RELATIVE_JSON_POINTER.exec($data);if(!matches)throw new Error(`Invalid JSON-pointer: ${$data}`);let up=+matches[1];if(jsonPointer=matches[2],jsonPointer==="#"){if(up>=dataLevel)throw new Error(errorMsg("property/index",up));return dataPathArr[dataLevel-up]}if(up>dataLevel)throw new Error(errorMsg("data",up));if(data=dataNames[dataLevel-up],!jsonPointer)return data}let expr=data,segments=jsonPointer.split("/");for(let segment of segments)segment&&(data=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)((0,util_1.unescapeJsonPointer)(segment))}`,expr=(0,codegen_1._)`${expr} && ${data}`);return expr;function errorMsg(pointerType,up){return`Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`}}exports.getData=getData})),require_validation_error=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});var ValidationError=class extends Error{constructor(errors2){super("validation failed"),this.errors=errors2,this.ajv=this.validation=!0}};exports.default=ValidationError})),require_ref_error=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let resolve_1=require_resolve();var MissingRefError=class extends Error{constructor(resolver,baseId,ref,msg){super(msg||`can't resolve reference ${ref} from id ${baseId}`),this.missingRef=(0,resolve_1.resolveUrl)(resolver,baseId,ref),this.missingSchema=(0,resolve_1.normalizeId)((0,resolve_1.getFullPath)(resolver,this.missingRef))}};exports.default=MissingRefError})),require_compile=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.resolveSchema=exports.getCompilingSchema=exports.resolveRef=exports.compileSchema=exports.SchemaEnv=void 0;let codegen_1=require_codegen(),validation_error_1=require_validation_error(),names_1=require_names(),resolve_1=require_resolve(),util_1=require_util(),validate_1=require_validate();var SchemaEnv=class{constructor(env2){var _a3;this.refs={},this.dynamicAnchors={};let schema2;typeof env2.schema=="object"&&(schema2=env2.schema),this.schema=env2.schema,this.schemaId=env2.schemaId,this.root=env2.root||this,this.baseId=(_a3=env2.baseId)!==null&&_a3!==void 0?_a3:(0,resolve_1.normalizeId)(schema2?.[env2.schemaId||"$id"]),this.schemaPath=env2.schemaPath,this.localRefs=env2.localRefs,this.meta=env2.meta,this.$async=schema2?.$async,this.refs={}}};exports.SchemaEnv=SchemaEnv;function compileSchema(sch){let _sch=getCompilingSchema.call(this,sch);if(_sch)return _sch;let rootId=(0,resolve_1.getFullPath)(this.opts.uriResolver,sch.root.baseId),{es5,lines}=this.opts.code,{ownProperties}=this.opts,gen=new codegen_1.CodeGen(this.scope,{es5,lines,ownProperties}),_ValidationError;sch.$async&&(_ValidationError=gen.scopeValue("Error",{ref:validation_error_1.default,code:(0,codegen_1._)`require("ajv/dist/runtime/validation_error").default`}));let validateName=gen.scopeName("validate");sch.validateName=validateName;let schemaCxt={gen,allErrors:this.opts.allErrors,data:names_1.default.data,parentData:names_1.default.parentData,parentDataProperty:names_1.default.parentDataProperty,dataNames:[names_1.default.data],dataPathArr:[codegen_1.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:gen.scopeValue("schema",this.opts.code.source===!0?{ref:sch.schema,code:(0,codegen_1.stringify)(sch.schema)}:{ref:sch.schema}),validateName,ValidationError:_ValidationError,schema:sch.schema,schemaEnv:sch,rootId,baseId:sch.baseId||rootId,schemaPath:codegen_1.nil,errSchemaPath:sch.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,codegen_1._)`""`,opts:this.opts,self:this},sourceCode;try{this._compilations.add(sch),(0,validate_1.validateFunctionCode)(schemaCxt),gen.optimize(this.opts.code.optimize);let validateCode=gen.toString();sourceCode=`${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`,this.opts.code.process&&(sourceCode=this.opts.code.process(sourceCode,sch));let validate2=new Function(`${names_1.default.self}`,`${names_1.default.scope}`,sourceCode)(this,this.scope.get());if(this.scope.value(validateName,{ref:validate2}),validate2.errors=null,validate2.schema=sch.schema,validate2.schemaEnv=sch,sch.$async&&(validate2.$async=!0),this.opts.code.source===!0&&(validate2.source={validateName,validateCode,scopeValues:gen._values}),this.opts.unevaluated){let{props,items}=schemaCxt;validate2.evaluated={props:props instanceof codegen_1.Name?void 0:props,items:items instanceof codegen_1.Name?void 0:items,dynamicProps:props instanceof codegen_1.Name,dynamicItems:items instanceof codegen_1.Name},validate2.source&&(validate2.source.evaluated=(0,codegen_1.stringify)(validate2.evaluated))}return sch.validate=validate2,sch}catch(e){throw delete sch.validate,delete sch.validateName,sourceCode&&this.logger.error("Error compiling schema, function code:",sourceCode),e}finally{this._compilations.delete(sch)}}exports.compileSchema=compileSchema;function resolveRef2(root,baseId,ref){var _a3;ref=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,ref);let schOrFunc=root.refs[ref];if(schOrFunc)return schOrFunc;let _sch=resolve.call(this,root,ref);if(_sch===void 0){let schema2=(_a3=root.localRefs)===null||_a3===void 0?void 0:_a3[ref],{schemaId}=this.opts;schema2&&(_sch=new SchemaEnv({schema:schema2,schemaId,root,baseId}))}if(_sch!==void 0)return root.refs[ref]=inlineOrCompile.call(this,_sch)}exports.resolveRef=resolveRef2;function inlineOrCompile(sch){return(0,resolve_1.inlineRef)(sch.schema,this.opts.inlineRefs)?sch.schema:sch.validate?sch:compileSchema.call(this,sch)}function getCompilingSchema(schEnv){for(let sch of this._compilations)if(sameSchemaEnv(sch,schEnv))return sch}exports.getCompilingSchema=getCompilingSchema;function sameSchemaEnv(s1,s2){return s1.schema===s2.schema&&s1.root===s2.root&&s1.baseId===s2.baseId}function resolve(root,ref){let sch;for(;typeof(sch=this.refs[ref])=="string";)ref=sch;return sch||this.schemas[ref]||resolveSchema.call(this,root,ref)}function resolveSchema(root,ref){let p=this.opts.uriResolver.parse(ref),refPath=(0,resolve_1._getFullPath)(this.opts.uriResolver,p),baseId=(0,resolve_1.getFullPath)(this.opts.uriResolver,root.baseId,void 0);if(Object.keys(root.schema).length>0&&refPath===baseId)return getJsonPointer.call(this,p,root);let id=(0,resolve_1.normalizeId)(refPath),schOrRef=this.refs[id]||this.schemas[id];if(typeof schOrRef=="string"){let sch=resolveSchema.call(this,root,schOrRef);return typeof sch?.schema!="object"?void 0:getJsonPointer.call(this,p,sch)}if(typeof schOrRef?.schema=="object"){if(schOrRef.validate||compileSchema.call(this,schOrRef),id===(0,resolve_1.normalizeId)(ref)){let{schema:schema2}=schOrRef,{schemaId}=this.opts,schId=schema2[schemaId];return schId&&(baseId=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schId)),new SchemaEnv({schema:schema2,schemaId,root,baseId})}return getJsonPointer.call(this,p,schOrRef)}}exports.resolveSchema=resolveSchema;let PREVENT_SCOPE_CHANGE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(parsedRef,{baseId,schema:schema2,root}){var _a3;if(((_a3=parsedRef.fragment)===null||_a3===void 0?void 0:_a3[0])!=="/")return;for(let part of parsedRef.fragment.slice(1).split("/")){if(typeof schema2=="boolean")return;let partSchema=schema2[(0,util_1.unescapeFragment)(part)];if(partSchema===void 0)return;schema2=partSchema;let schId=typeof schema2=="object"&&schema2[this.opts.schemaId];!PREVENT_SCOPE_CHANGE.has(part)&&schId&&(baseId=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schId))}let env2;if(typeof schema2!="boolean"&&schema2.$ref&&!(0,util_1.schemaHasRulesButRef)(schema2,this.RULES)){let $ref=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schema2.$ref);env2=resolveSchema.call(this,root,$ref)}let{schemaId}=this.opts;if(env2=env2||new SchemaEnv({schema:schema2,schemaId,root,baseId}),env2.schema!==env2.root.schema)return env2}})),require_data=__commonJSMin(((exports,module)=>{module.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}})),require_utils=__commonJSMin(((exports,module)=>{let isUUID=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),isIPv4=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function stringArrayToHexStripped(input){let acc="",code=0,i=0;for(i=0;i<input.length;i++)if(code=input[i].charCodeAt(0),code!==48){if(!(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102))return"";acc+=input[i];break}for(i+=1;i<input.length;i++){if(code=input[i].charCodeAt(0),!(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102))return"";acc+=input[i]}return acc}let nonSimpleDomain=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function consumeIsZone(buffer){return buffer.length=0,!0}function consumeHextets(buffer,address,output){if(buffer.length){let hex=stringArrayToHexStripped(buffer);if(hex!=="")address.push(hex);else return output.error=!0,!1;buffer.length=0}return!0}function getIPV6(input){let tokenCount=0,output={error:!1,address:"",zone:""},address=[],buffer=[],endipv6Encountered=!1,endIpv6=!1,consume=consumeHextets;for(let i=0;i<input.length;i++){let cursor=input[i];if(!(cursor==="["||cursor==="]"))if(cursor===":"){if(endipv6Encountered===!0&&(endIpv6=!0),!consume(buffer,address,output))break;if(++tokenCount>7){output.error=!0;break}i>0&&input[i-1]===":"&&(endipv6Encountered=!0),address.push(":");continue}else if(cursor==="%"){if(!consume(buffer,address,output))break;consume=consumeIsZone}else{buffer.push(cursor);continue}}return buffer.length&&(consume===consumeIsZone?output.zone=buffer.join(""):endIpv6?address.push(buffer.join("")):address.push(stringArrayToHexStripped(buffer))),output.address=address.join(""),output}function normalizeIPv6(host){if(findToken(host,":")<2)return{host,isIPV6:!1};let ipv62=getIPV6(host);if(ipv62.error)return{host,isIPV6:!1};{let newHost=ipv62.address,escapedHost=ipv62.address;return ipv62.zone&&(newHost+="%"+ipv62.zone,escapedHost+="%25"+ipv62.zone),{host:newHost,isIPV6:!0,escapedHost}}}function findToken(str,token){let ind=0;for(let i=0;i<str.length;i++)str[i]===token&&ind++;return ind}function removeDotSegments(path){let input=path,output=[],nextSlash=-1,len=0;for(;len=input.length;){if(len===1){if(input===".")break;if(input==="/"){output.push("/");break}else{output.push(input);break}}else if(len===2){if(input[0]==="."){if(input[1]===".")break;if(input[1]==="/"){input=input.slice(2);continue}}else if(input[0]==="/"&&(input[1]==="."||input[1]==="/")){output.push("/");break}}else if(len===3&&input==="/.."){output.length!==0&&output.pop(),output.push("/");break}if(input[0]==="."){if(input[1]==="."){if(input[2]==="/"){input=input.slice(3);continue}}else if(input[1]==="/"){input=input.slice(2);continue}}else if(input[0]==="/"&&input[1]==="."){if(input[2]==="/"){input=input.slice(2);continue}else if(input[2]==="."&&input[3]==="/"){input=input.slice(3),output.length!==0&&output.pop();continue}}if((nextSlash=input.indexOf("/",1))===-1){output.push(input);break}else output.push(input.slice(0,nextSlash)),input=input.slice(nextSlash)}return output.join("")}function normalizeComponentEncoding(component,esc2){let func=esc2!==!0?escape:unescape;return component.scheme!==void 0&&(component.scheme=func(component.scheme)),component.userinfo!==void 0&&(component.userinfo=func(component.userinfo)),component.host!==void 0&&(component.host=func(component.host)),component.path!==void 0&&(component.path=func(component.path)),component.query!==void 0&&(component.query=func(component.query)),component.fragment!==void 0&&(component.fragment=func(component.fragment)),component}function recomposeAuthority(component){let uriTokens=[];if(component.userinfo!==void 0&&(uriTokens.push(component.userinfo),uriTokens.push("@")),component.host!==void 0){let host=unescape(component.host);if(!isIPv4(host)){let ipV6res=normalizeIPv6(host);ipV6res.isIPV6===!0?host=`[${ipV6res.escapedHost}]`:host=component.host}uriTokens.push(host)}return(typeof component.port=="number"||typeof component.port=="string")&&(uriTokens.push(":"),uriTokens.push(String(component.port))),uriTokens.length?uriTokens.join(""):void 0}module.exports={nonSimpleDomain,recomposeAuthority,normalizeComponentEncoding,removeDotSegments,isIPv4,isUUID,normalizeIPv6,stringArrayToHexStripped}})),require_schemes=__commonJSMin(((exports,module)=>{let{isUUID}=require_utils(),URN_REG=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,supportedSchemeNames=["http","https","ws","wss","urn","urn:uuid"];function isValidSchemeName(name){return supportedSchemeNames.indexOf(name)!==-1}function wsIsSecure(wsComponent){return wsComponent.secure===!0?!0:wsComponent.secure===!1?!1:wsComponent.scheme?wsComponent.scheme.length===3&&(wsComponent.scheme[0]==="w"||wsComponent.scheme[0]==="W")&&(wsComponent.scheme[1]==="s"||wsComponent.scheme[1]==="S")&&(wsComponent.scheme[2]==="s"||wsComponent.scheme[2]==="S"):!1}function httpParse(component){return component.host||(component.error=component.error||"HTTP URIs must have a host."),component}function httpSerialize(component){let secure=String(component.scheme).toLowerCase()==="https";return(component.port===(secure?443:80)||component.port==="")&&(component.port=void 0),component.path||(component.path="/"),component}function wsParse(wsComponent){return wsComponent.secure=wsIsSecure(wsComponent),wsComponent.resourceName=(wsComponent.path||"/")+(wsComponent.query?"?"+wsComponent.query:""),wsComponent.path=void 0,wsComponent.query=void 0,wsComponent}function wsSerialize(wsComponent){if((wsComponent.port===(wsIsSecure(wsComponent)?443:80)||wsComponent.port==="")&&(wsComponent.port=void 0),typeof wsComponent.secure=="boolean"&&(wsComponent.scheme=wsComponent.secure?"wss":"ws",wsComponent.secure=void 0),wsComponent.resourceName){let[path,query]=wsComponent.resourceName.split("?");wsComponent.path=path&&path!=="/"?path:void 0,wsComponent.query=query,wsComponent.resourceName=void 0}return wsComponent.fragment=void 0,wsComponent}function urnParse(urnComponent,options){if(!urnComponent.path)return urnComponent.error="URN can not be parsed",urnComponent;let matches=urnComponent.path.match(URN_REG);if(matches){let scheme=options.scheme||urnComponent.scheme||"urn";urnComponent.nid=matches[1].toLowerCase(),urnComponent.nss=matches[2];let schemeHandler=getSchemeHandler(`${scheme}:${options.nid||urnComponent.nid}`);urnComponent.path=void 0,schemeHandler&&(urnComponent=schemeHandler.parse(urnComponent,options))}else urnComponent.error=urnComponent.error||"URN can not be parsed.";return urnComponent}function urnSerialize(urnComponent,options){if(urnComponent.nid===void 0)throw new Error("URN without nid cannot be serialized");let scheme=options.scheme||urnComponent.scheme||"urn",nid=urnComponent.nid.toLowerCase(),schemeHandler=getSchemeHandler(`${scheme}:${options.nid||nid}`);schemeHandler&&(urnComponent=schemeHandler.serialize(urnComponent,options));let uriComponent=urnComponent,nss=urnComponent.nss;return uriComponent.path=`${nid||options.nid}:${nss}`,options.skipEscape=!0,uriComponent}function urnuuidParse(urnComponent,options){let uuidComponent=urnComponent;return uuidComponent.uuid=uuidComponent.nss,uuidComponent.nss=void 0,!options.tolerant&&(!uuidComponent.uuid||!isUUID(uuidComponent.uuid))&&(uuidComponent.error=uuidComponent.error||"UUID is not valid."),uuidComponent}function urnuuidSerialize(uuidComponent){let urnComponent=uuidComponent;return urnComponent.nss=(uuidComponent.uuid||"").toLowerCase(),urnComponent}let http={scheme:"http",domainHost:!0,parse:httpParse,serialize:httpSerialize},https={scheme:"https",domainHost:http.domainHost,parse:httpParse,serialize:httpSerialize},ws={scheme:"ws",domainHost:!0,parse:wsParse,serialize:wsSerialize},wss={scheme:"wss",domainHost:ws.domainHost,parse:ws.parse,serialize:ws.serialize},SCHEMES={http,https,ws,wss,urn:{scheme:"urn",parse:urnParse,serialize:urnSerialize,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:urnuuidParse,serialize:urnuuidSerialize,skipNormalize:!0}};Object.setPrototypeOf(SCHEMES,null);function getSchemeHandler(scheme){return scheme&&(SCHEMES[scheme]||SCHEMES[scheme.toLowerCase()])||void 0}module.exports={wsIsSecure,SCHEMES,isValidSchemeName,getSchemeHandler}})),require_fast_uri=__commonJSMin(((exports,module)=>{let{normalizeIPv6,removeDotSegments,recomposeAuthority,normalizeComponentEncoding,isIPv4,nonSimpleDomain}=require_utils(),{SCHEMES,getSchemeHandler}=require_schemes();function normalize(uri,options){return typeof uri=="string"?uri=serialize2(parse3(uri,options),options):typeof uri=="object"&&(uri=parse3(serialize2(uri,options),options)),uri}function resolve(baseURI,relativeURI,options){let schemelessOptions=options?Object.assign({scheme:"null"},options):{scheme:"null"},resolved=resolveComponent(parse3(baseURI,schemelessOptions),parse3(relativeURI,schemelessOptions),schemelessOptions,!0);return schemelessOptions.skipEscape=!0,serialize2(resolved,schemelessOptions)}function resolveComponent(base,relative,options,skipNormalization){let target={};return skipNormalization||(base=parse3(serialize2(base,options),options),relative=parse3(serialize2(relative,options),options)),options=options||{},!options.tolerant&&relative.scheme?(target.scheme=relative.scheme,target.userinfo=relative.userinfo,target.host=relative.host,target.port=relative.port,target.path=removeDotSegments(relative.path||""),target.query=relative.query):(relative.userinfo!==void 0||relative.host!==void 0||relative.port!==void 0?(target.userinfo=relative.userinfo,target.host=relative.host,target.port=relative.port,target.path=removeDotSegments(relative.path||""),target.query=relative.query):(relative.path?(relative.path[0]==="/"?target.path=removeDotSegments(relative.path):((base.userinfo!==void 0||base.host!==void 0||base.port!==void 0)&&!base.path?target.path="/"+relative.path:base.path?target.path=base.path.slice(0,base.path.lastIndexOf("/")+1)+relative.path:target.path=relative.path,target.path=removeDotSegments(target.path)),target.query=relative.query):(target.path=base.path,relative.query!==void 0?target.query=relative.query:target.query=base.query),target.userinfo=base.userinfo,target.host=base.host,target.port=base.port),target.scheme=base.scheme),target.fragment=relative.fragment,target}function equal(uriA,uriB,options){return typeof uriA=="string"?(uriA=unescape(uriA),uriA=serialize2(normalizeComponentEncoding(parse3(uriA,options),!0),{...options,skipEscape:!0})):typeof uriA=="object"&&(uriA=serialize2(normalizeComponentEncoding(uriA,!0),{...options,skipEscape:!0})),typeof uriB=="string"?(uriB=unescape(uriB),uriB=serialize2(normalizeComponentEncoding(parse3(uriB,options),!0),{...options,skipEscape:!0})):typeof uriB=="object"&&(uriB=serialize2(normalizeComponentEncoding(uriB,!0),{...options,skipEscape:!0})),uriA.toLowerCase()===uriB.toLowerCase()}function serialize2(cmpts,opts){let component={host:cmpts.host,scheme:cmpts.scheme,userinfo:cmpts.userinfo,port:cmpts.port,path:cmpts.path,query:cmpts.query,nid:cmpts.nid,nss:cmpts.nss,uuid:cmpts.uuid,fragment:cmpts.fragment,reference:cmpts.reference,resourceName:cmpts.resourceName,secure:cmpts.secure,error:""},options=Object.assign({},opts),uriTokens=[],schemeHandler=getSchemeHandler(options.scheme||component.scheme);schemeHandler&&schemeHandler.serialize&&schemeHandler.serialize(component,options),component.path!==void 0&&(options.skipEscape?component.path=unescape(component.path):(component.path=escape(component.path),component.scheme!==void 0&&(component.path=component.path.split("%3A").join(":")))),options.reference!=="suffix"&&component.scheme&&uriTokens.push(component.scheme,":");let authority=recomposeAuthority(component);if(authority!==void 0&&(options.reference!=="suffix"&&uriTokens.push("//"),uriTokens.push(authority),component.path&&component.path[0]!=="/"&&uriTokens.push("/")),component.path!==void 0){let s=component.path;!options.absolutePath&&(!schemeHandler||!schemeHandler.absolutePath)&&(s=removeDotSegments(s)),authority===void 0&&s[0]==="/"&&s[1]==="/"&&(s="/%2F"+s.slice(2)),uriTokens.push(s)}return component.query!==void 0&&uriTokens.push("?",component.query),component.fragment!==void 0&&uriTokens.push("#",component.fragment),uriTokens.join("")}let URI_PARSE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function parse3(uri,opts){let options=Object.assign({},opts),parsed={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},isIP=!1;options.reference==="suffix"&&(options.scheme?uri=options.scheme+":"+uri:uri="//"+uri);let matches=uri.match(URI_PARSE);if(matches){if(parsed.scheme=matches[1],parsed.userinfo=matches[3],parsed.host=matches[4],parsed.port=parseInt(matches[5],10),parsed.path=matches[6]||"",parsed.query=matches[7],parsed.fragment=matches[8],isNaN(parsed.port)&&(parsed.port=matches[5]),parsed.host)if(isIPv4(parsed.host)===!1){let ipv6result=normalizeIPv6(parsed.host);parsed.host=ipv6result.host.toLowerCase(),isIP=ipv6result.isIPV6}else isIP=!0;parsed.scheme===void 0&&parsed.userinfo===void 0&&parsed.host===void 0&&parsed.port===void 0&&parsed.query===void 0&&!parsed.path?parsed.reference="same-document":parsed.scheme===void 0?parsed.reference="relative":parsed.fragment===void 0?parsed.reference="absolute":parsed.reference="uri",options.reference&&options.reference!=="suffix"&&options.reference!==parsed.reference&&(parsed.error=parsed.error||"URI is not a "+options.reference+" reference.");let schemeHandler=getSchemeHandler(options.scheme||parsed.scheme);if(!options.unicodeSupport&&(!schemeHandler||!schemeHandler.unicodeSupport)&&parsed.host&&(options.domainHost||schemeHandler&&schemeHandler.domainHost)&&isIP===!1&&nonSimpleDomain(parsed.host))try{parsed.host=URL.domainToASCII(parsed.host.toLowerCase())}catch(e){parsed.error=parsed.error||"Host's domain name can not be converted to ASCII: "+e}(!schemeHandler||schemeHandler&&!schemeHandler.skipNormalize)&&(uri.indexOf("%")!==-1&&(parsed.scheme!==void 0&&(parsed.scheme=unescape(parsed.scheme)),parsed.host!==void 0&&(parsed.host=unescape(parsed.host))),parsed.path&&(parsed.path=escape(unescape(parsed.path))),parsed.fragment&&(parsed.fragment=encodeURI(decodeURIComponent(parsed.fragment)))),schemeHandler&&schemeHandler.parse&&schemeHandler.parse(parsed,options)}else parsed.error=parsed.error||"URI can not be parsed.";return parsed}let fastUri={SCHEMES,normalize,resolve,resolveComponent,equal,serialize:serialize2,parse:parse3};module.exports=fastUri,module.exports.default=fastUri,module.exports.fastUri=fastUri})),require_uri=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let uri=require_fast_uri();uri.code='require("ajv/dist/runtime/uri").default',exports.default=uri})),require_core$3=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=void 0;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});let validation_error_1=require_validation_error(),ref_error_1=require_ref_error(),rules_1=require_rules(),compile_1=require_compile(),codegen_2=require_codegen(),resolve_1=require_resolve(),dataType_1=require_dataType(),util_1=require_util(),$dataRefSchema=require_data(),uri_1=require_uri(),defaultRegExp=(str,flags)=>new RegExp(str,flags);defaultRegExp.code="new RegExp";let META_IGNORE_OPTIONS=["removeAdditional","useDefaults","coerceTypes"],EXT_SCOPE_NAMES=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),removedOptions={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},deprecatedOptions={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},MAX_EXPRESSION=200;function requiredOptions(o){var _a3,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_0;let s=o.strict,_optz=(_a3=o.code)===null||_a3===void 0?void 0:_a3.optimize,optimize=_optz===!0||_optz===void 0?1:_optz||0,regExp=(_c=(_b=o.code)===null||_b===void 0?void 0:_b.regExp)!==null&&_c!==void 0?_c:defaultRegExp,uriResolver=(_d=o.uriResolver)!==null&&_d!==void 0?_d:uri_1.default;return{strictSchema:(_f=(_e=o.strictSchema)!==null&&_e!==void 0?_e:s)!==null&&_f!==void 0?_f:!0,strictNumbers:(_h=(_g=o.strictNumbers)!==null&&_g!==void 0?_g:s)!==null&&_h!==void 0?_h:!0,strictTypes:(_k=(_j=o.strictTypes)!==null&&_j!==void 0?_j:s)!==null&&_k!==void 0?_k:"log",strictTuples:(_m=(_l=o.strictTuples)!==null&&_l!==void 0?_l:s)!==null&&_m!==void 0?_m:"log",strictRequired:(_p=(_o=o.strictRequired)!==null&&_o!==void 0?_o:s)!==null&&_p!==void 0?_p:!1,code:o.code?{...o.code,optimize,regExp}:{optimize,regExp},loopRequired:(_q=o.loopRequired)!==null&&_q!==void 0?_q:MAX_EXPRESSION,loopEnum:(_r=o.loopEnum)!==null&&_r!==void 0?_r:MAX_EXPRESSION,meta:(_s=o.meta)!==null&&_s!==void 0?_s:!0,messages:(_t=o.messages)!==null&&_t!==void 0?_t:!0,inlineRefs:(_u=o.inlineRefs)!==null&&_u!==void 0?_u:!0,schemaId:(_v=o.schemaId)!==null&&_v!==void 0?_v:"$id",addUsedSchema:(_w=o.addUsedSchema)!==null&&_w!==void 0?_w:!0,validateSchema:(_x=o.validateSchema)!==null&&_x!==void 0?_x:!0,validateFormats:(_y=o.validateFormats)!==null&&_y!==void 0?_y:!0,unicodeRegExp:(_z=o.unicodeRegExp)!==null&&_z!==void 0?_z:!0,int32range:(_0=o.int32range)!==null&&_0!==void 0?_0:!0,uriResolver}}var Ajv2=class{constructor(opts={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,opts=this.opts={...opts,...requiredOptions(opts)};let{es5,lines}=this.opts.code;this.scope=new codegen_2.ValueScope({scope:{},prefixes:EXT_SCOPE_NAMES,es5,lines}),this.logger=getLogger(opts.logger);let formatOpt=opts.validateFormats;opts.validateFormats=!1,this.RULES=(0,rules_1.getRules)(),checkOptions.call(this,removedOptions,opts,"NOT SUPPORTED"),checkOptions.call(this,deprecatedOptions,opts,"DEPRECATED","warn"),this._metaOpts=getMetaSchemaOptions.call(this),opts.formats&&addInitialFormats.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),opts.keywords&&addInitialKeywords.call(this,opts.keywords),typeof opts.meta=="object"&&this.addMetaSchema(opts.meta),addInitialSchemas.call(this),opts.validateFormats=formatOpt}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data,meta:meta2,schemaId}=this.opts,_dataRefSchema=$dataRefSchema;schemaId==="id"&&(_dataRefSchema={...$dataRefSchema},_dataRefSchema.id=_dataRefSchema.$id,delete _dataRefSchema.$id),meta2&&$data&&this.addMetaSchema(_dataRefSchema,_dataRefSchema[schemaId],!1)}defaultMeta(){let{meta:meta2,schemaId}=this.opts;return this.opts.defaultMeta=typeof meta2=="object"?meta2[schemaId]||meta2:void 0}validate(schemaKeyRef,data){let v;if(typeof schemaKeyRef=="string"){if(v=this.getSchema(schemaKeyRef),!v)throw new Error(`no schema with key or ref "${schemaKeyRef}"`)}else v=this.compile(schemaKeyRef);let valid=v(data);return"$async"in v||(this.errors=v.errors),valid}compile(schema2,_meta){let sch=this._addSchema(schema2,_meta);return sch.validate||this._compileSchemaEnv(sch)}compileAsync(schema2,meta2){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema}=this.opts;return runCompileAsync.call(this,schema2,meta2);async function runCompileAsync(_schema,_meta){await loadMetaSchema.call(this,_schema.$schema);let sch=this._addSchema(_schema,_meta);return sch.validate||_compileAsync.call(this,sch)}async function loadMetaSchema($ref){$ref&&!this.getSchema($ref)&&await runCompileAsync.call(this,{$ref},!0)}async function _compileAsync(sch){try{return this._compileSchemaEnv(sch)}catch(e){if(!(e instanceof ref_error_1.default))throw e;return checkLoaded.call(this,e),await loadMissingSchema.call(this,e.missingSchema),_compileAsync.call(this,sch)}}function checkLoaded({missingSchema:ref,missingRef}){if(this.refs[ref])throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)}async function loadMissingSchema(ref){let _schema=await _loadSchema.call(this,ref);this.refs[ref]||await loadMetaSchema.call(this,_schema.$schema),this.refs[ref]||this.addSchema(_schema,ref,meta2)}async function _loadSchema(ref){let p=this._loading[ref];if(p)return p;try{return await(this._loading[ref]=loadSchema(ref))}finally{delete this._loading[ref]}}}addSchema(schema2,key,_meta,_validateSchema=this.opts.validateSchema){if(Array.isArray(schema2)){for(let sch of schema2)this.addSchema(sch,void 0,_meta,_validateSchema);return this}let id;if(typeof schema2=="object"){let{schemaId}=this.opts;if(id=schema2[schemaId],id!==void 0&&typeof id!="string")throw new Error(`schema ${schemaId} must be string`)}return key=(0,resolve_1.normalizeId)(key||id),this._checkUnique(key),this.schemas[key]=this._addSchema(schema2,_meta,key,_validateSchema,!0),this}addMetaSchema(schema2,key,_validateSchema=this.opts.validateSchema){return this.addSchema(schema2,key,!0,_validateSchema),this}validateSchema(schema2,throwOrLogError){if(typeof schema2=="boolean")return!0;let $schema;if($schema=schema2.$schema,$schema!==void 0&&typeof $schema!="string")throw new Error("$schema must be a string");if($schema=$schema||this.opts.defaultMeta||this.defaultMeta(),!$schema)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let valid=this.validate($schema,schema2);if(!valid&&throwOrLogError){let message="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(message);else throw new Error(message)}return valid}getSchema(keyRef){let sch;for(;typeof(sch=getSchEnv.call(this,keyRef))=="string";)keyRef=sch;if(sch===void 0){let{schemaId}=this.opts,root=new compile_1.SchemaEnv({schema:{},schemaId});if(sch=compile_1.resolveSchema.call(this,root,keyRef),!sch)return;this.refs[keyRef]=sch}return sch.validate||this._compileSchemaEnv(sch)}removeSchema(schemaKeyRef){if(schemaKeyRef instanceof RegExp)return this._removeAllSchemas(this.schemas,schemaKeyRef),this._removeAllSchemas(this.refs,schemaKeyRef),this;switch(typeof schemaKeyRef){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let sch=getSchEnv.call(this,schemaKeyRef);return typeof sch=="object"&&this._cache.delete(sch.schema),delete this.schemas[schemaKeyRef],delete this.refs[schemaKeyRef],this}case"object":{let cacheKey=schemaKeyRef;this._cache.delete(cacheKey);let id=schemaKeyRef[this.opts.schemaId];return id&&(id=(0,resolve_1.normalizeId)(id),delete this.schemas[id],delete this.refs[id]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(definitions){for(let def of definitions)this.addKeyword(def);return this}addKeyword(kwdOrDef,def){let keyword;if(typeof kwdOrDef=="string")keyword=kwdOrDef,typeof def=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),def.keyword=keyword);else if(typeof kwdOrDef=="object"&&def===void 0){if(def=kwdOrDef,keyword=def.keyword,Array.isArray(keyword)&&!keyword.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(checkKeyword.call(this,keyword,def),!def)return(0,util_1.eachItem)(keyword,kwd=>addRule.call(this,kwd)),this;keywordMetaschema.call(this,def);let definition={...def,type:(0,dataType_1.getJSONTypes)(def.type),schemaType:(0,dataType_1.getJSONTypes)(def.schemaType)};return(0,util_1.eachItem)(keyword,definition.type.length===0?k=>addRule.call(this,k,definition):k=>definition.type.forEach(t=>addRule.call(this,k,definition,t))),this}getKeyword(keyword){let rule=this.RULES.all[keyword];return typeof rule=="object"?rule.definition:!!rule}removeKeyword(keyword){let{RULES}=this;delete RULES.keywords[keyword],delete RULES.all[keyword];for(let group of RULES.rules){let i=group.rules.findIndex(rule=>rule.keyword===keyword);i>=0&&group.rules.splice(i,1)}return this}addFormat(name,format){return typeof format=="string"&&(format=new RegExp(format)),this.formats[name]=format,this}errorsText(errors2=this.errors,{separator=", ",dataVar="data"}={}){return!errors2||errors2.length===0?"No errors":errors2.map(e=>`${dataVar}${e.instancePath} ${e.message}`).reduce((text2,msg)=>text2+separator+msg)}$dataMetaSchema(metaSchema,keywordsJsonPointers){let rules=this.RULES.all;metaSchema=JSON.parse(JSON.stringify(metaSchema));for(let jsonPointer of keywordsJsonPointers){let segments=jsonPointer.split("/").slice(1),keywords=metaSchema;for(let seg of segments)keywords=keywords[seg];for(let key in rules){let rule=rules[key];if(typeof rule!="object")continue;let{$data}=rule.definition,schema2=keywords[key];$data&&schema2&&(keywords[key]=schemaOrData(schema2))}}return metaSchema}_removeAllSchemas(schemas,regex){for(let keyRef in schemas){let sch=schemas[keyRef];(!regex||regex.test(keyRef))&&(typeof sch=="string"?delete schemas[keyRef]:sch&&!sch.meta&&(this._cache.delete(sch.schema),delete schemas[keyRef]))}}_addSchema(schema2,meta2,baseId,validateSchema=this.opts.validateSchema,addSchema=this.opts.addUsedSchema){let id,{schemaId}=this.opts;if(typeof schema2=="object")id=schema2[schemaId];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof schema2!="boolean")throw new Error("schema must be object or boolean")}let sch=this._cache.get(schema2);if(sch!==void 0)return sch;baseId=(0,resolve_1.normalizeId)(id||baseId);let localRefs=resolve_1.getSchemaRefs.call(this,schema2,baseId);return sch=new compile_1.SchemaEnv({schema:schema2,schemaId,meta:meta2,baseId,localRefs}),this._cache.set(sch.schema,sch),addSchema&&!baseId.startsWith("#")&&(baseId&&this._checkUnique(baseId),this.refs[baseId]=sch),validateSchema&&this.validateSchema(schema2,!0),sch}_checkUnique(id){if(this.schemas[id]||this.refs[id])throw new Error(`schema with key or id "${id}" already exists`)}_compileSchemaEnv(sch){if(sch.meta?this._compileMetaSchema(sch):compile_1.compileSchema.call(this,sch),!sch.validate)throw new Error("ajv implementation error");return sch.validate}_compileMetaSchema(sch){let currentOpts=this.opts;this.opts=this._metaOpts;try{compile_1.compileSchema.call(this,sch)}finally{this.opts=currentOpts}}};Ajv2.ValidationError=validation_error_1.default,Ajv2.MissingRefError=ref_error_1.default,exports.default=Ajv2;function checkOptions(checkOpts,options,msg,log="error"){for(let key in checkOpts){let opt=key;opt in options&&this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)}}function getSchEnv(keyRef){return keyRef=(0,resolve_1.normalizeId)(keyRef),this.schemas[keyRef]||this.refs[keyRef]}function addInitialSchemas(){let optsSchemas=this.opts.schemas;if(optsSchemas)if(Array.isArray(optsSchemas))this.addSchema(optsSchemas);else for(let key in optsSchemas)this.addSchema(optsSchemas[key],key)}function addInitialFormats(){for(let name in this.opts.formats){let format=this.opts.formats[name];format&&this.addFormat(name,format)}}function addInitialKeywords(defs){if(Array.isArray(defs)){this.addVocabulary(defs);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let keyword in defs){let def=defs[keyword];def.keyword||(def.keyword=keyword),this.addKeyword(def)}}function getMetaSchemaOptions(){let metaOpts={...this.opts};for(let opt of META_IGNORE_OPTIONS)delete metaOpts[opt];return metaOpts}let noLogs={log(){},warn(){},error(){}};function getLogger(logger){if(logger===!1)return noLogs;if(logger===void 0)return console;if(logger.log&&logger.warn&&logger.error)return logger;throw new Error("logger must implement log, warn and error methods")}let KEYWORD_NAME=/^[a-z_$][a-z0-9_$:-]*$/i;function checkKeyword(keyword,def){let{RULES}=this;if((0,util_1.eachItem)(keyword,kwd=>{if(RULES.keywords[kwd])throw new Error(`Keyword ${kwd} is already defined`);if(!KEYWORD_NAME.test(kwd))throw new Error(`Keyword ${kwd} has invalid name`)}),!!def&&def.$data&&!("code"in def||"validate"in def))throw new Error('$data keyword must have "code" or "validate" function')}function addRule(keyword,definition,dataType){var _a3;let post=definition?.post;if(dataType&&post)throw new Error('keyword with "post" flag cannot have "type"');let{RULES}=this,ruleGroup=post?RULES.post:RULES.rules.find(({type:t})=>t===dataType);if(ruleGroup||(ruleGroup={type:dataType,rules:[]},RULES.rules.push(ruleGroup)),RULES.keywords[keyword]=!0,!definition)return;let rule={keyword,definition:{...definition,type:(0,dataType_1.getJSONTypes)(definition.type),schemaType:(0,dataType_1.getJSONTypes)(definition.schemaType)}};definition.before?addBeforeRule.call(this,ruleGroup,rule,definition.before):ruleGroup.rules.push(rule),RULES.all[keyword]=rule,(_a3=definition.implements)===null||_a3===void 0||_a3.forEach(kwd=>this.addKeyword(kwd))}function addBeforeRule(ruleGroup,rule,before){let i=ruleGroup.rules.findIndex(_rule=>_rule.keyword===before);i>=0?ruleGroup.rules.splice(i,0,rule):(ruleGroup.rules.push(rule),this.logger.warn(`rule ${before} is not defined`))}function keywordMetaschema(def){let{metaSchema}=def;metaSchema!==void 0&&(def.$data&&this.opts.$data&&(metaSchema=schemaOrData(metaSchema)),def.validateSchema=this.compile(metaSchema,!0))}let $dataRef={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function schemaOrData(schema2){return{anyOf:[schema2,$dataRef]}}})),require_id=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let def={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};exports.default=def})),require_ref=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.callRef=exports.getValidate=void 0;let ref_error_1=require_ref_error(),code_1=require_code(),codegen_1=require_codegen(),names_1=require_names(),compile_1=require_compile(),util_1=require_util(),def={keyword:"$ref",schemaType:"string",code(cxt){let{gen,schema:$ref,it}=cxt,{baseId,schemaEnv:env2,validateName,opts,self}=it,{root}=env2;if(($ref==="#"||$ref==="#/")&&baseId===root.baseId)return callRootRef();let schOrEnv=compile_1.resolveRef.call(self,root,baseId,$ref);if(schOrEnv===void 0)throw new ref_error_1.default(it.opts.uriResolver,baseId,$ref);if(schOrEnv instanceof compile_1.SchemaEnv)return callValidate(schOrEnv);return inlineRefSchema(schOrEnv);function callRootRef(){if(env2===root)return callRef(cxt,validateName,env2,env2.$async);let rootName=gen.scopeValue("root",{ref:root});return callRef(cxt,(0,codegen_1._)`${rootName}.validate`,root,root.$async)}function callValidate(sch){callRef(cxt,getValidate(cxt,sch),sch,sch.$async)}function inlineRefSchema(sch){let schName=gen.scopeValue("schema",opts.code.source===!0?{ref:sch,code:(0,codegen_1.stringify)(sch)}:{ref:sch}),valid=gen.name("valid"),schCxt=cxt.subschema({schema:sch,dataTypes:[],schemaPath:codegen_1.nil,topSchemaRef:schName,errSchemaPath:$ref},valid);cxt.mergeEvaluated(schCxt),cxt.ok(valid)}}};function getValidate(cxt,sch){let{gen}=cxt;return sch.validate?gen.scopeValue("validate",{ref:sch.validate}):(0,codegen_1._)`${gen.scopeValue("wrapper",{ref:sch})}.validate`}exports.getValidate=getValidate;function callRef(cxt,v,sch,$async){let{gen,it}=cxt,{allErrors,schemaEnv:env2,opts}=it,passCxt=opts.passContext?names_1.default.this:codegen_1.nil;$async?callAsyncRef():callSyncRef();function callAsyncRef(){if(!env2.$async)throw new Error("async schema referenced by sync schema");let valid=gen.let("valid");gen.try(()=>{gen.code((0,codegen_1._)`await ${(0,code_1.callValidateCode)(cxt,v,passCxt)}`),addEvaluatedFrom(v),allErrors||gen.assign(valid,!0)},e=>{gen.if((0,codegen_1._)`!(${e} instanceof ${it.ValidationError})`,()=>gen.throw(e)),addErrorsFrom(e),allErrors||gen.assign(valid,!1)}),cxt.ok(valid)}function callSyncRef(){cxt.result((0,code_1.callValidateCode)(cxt,v,passCxt),()=>addEvaluatedFrom(v),()=>addErrorsFrom(v))}function addErrorsFrom(source){let errs=(0,codegen_1._)`${source}.errors`;gen.assign(names_1.default.vErrors,(0,codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`),gen.assign(names_1.default.errors,(0,codegen_1._)`${names_1.default.vErrors}.length`)}function addEvaluatedFrom(source){var _a3;if(!it.opts.unevaluated)return;let schEvaluated=(_a3=sch?.validate)===null||_a3===void 0?void 0:_a3.evaluated;if(it.props!==!0)if(schEvaluated&&!schEvaluated.dynamicProps)schEvaluated.props!==void 0&&(it.props=util_1.mergeEvaluated.props(gen,schEvaluated.props,it.props));else{let props=gen.var("props",(0,codegen_1._)`${source}.evaluated.props`);it.props=util_1.mergeEvaluated.props(gen,props,it.props,codegen_1.Name)}if(it.items!==!0)if(schEvaluated&&!schEvaluated.dynamicItems)schEvaluated.items!==void 0&&(it.items=util_1.mergeEvaluated.items(gen,schEvaluated.items,it.items));else{let items=gen.var("items",(0,codegen_1._)`${source}.evaluated.items`);it.items=util_1.mergeEvaluated.items(gen,items,it.items,codegen_1.Name)}}}exports.callRef=callRef,exports.default=def})),require_core$2=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let id_1=require_id(),ref_1=require_ref(),core=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",id_1.default,ref_1.default];exports.default=core})),require_limitNumber=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),ops=codegen_1.operators,KWDs={maximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},minimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},exclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},exclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}},def={keyword:Object.keys(KWDs),type:"number",schemaType:"number",$data:!0,error:{message:({keyword,schemaCode})=>(0,codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`},code(cxt){let{keyword,data,schemaCode}=cxt;cxt.fail$data((0,codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`)}};exports.default=def})),require_multipleOf=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),def={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode})=>(0,codegen_1.str)`must be multiple of ${schemaCode}`,params:({schemaCode})=>(0,codegen_1._)`{multipleOf: ${schemaCode}}`},code(cxt){let{gen,data,schemaCode,it}=cxt,prec=it.opts.multipleOfPrecision,res=gen.let("res"),invalid=prec?(0,codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`:(0,codegen_1._)`${res} !== parseInt(${res})`;cxt.fail$data((0,codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)}};exports.default=def})),require_ucs2length=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});function ucs2length(str){let len=str.length,length=0,pos=0,value;for(;pos<len;)length++,value=str.charCodeAt(pos++),value>=55296&&value<=56319&&pos<len&&(value=str.charCodeAt(pos),(value&64512)===56320&&pos++);return length}exports.default=ucs2length,ucs2length.code='require("ajv/dist/runtime/ucs2length").default'})),require_limitLength=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),ucs2length_1=require_ucs2length(),def={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword,schemaCode}){let comp=keyword==="maxLength"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`},code(cxt){let{keyword,data,schemaCode,it}=cxt,op=keyword==="maxLength"?codegen_1.operators.GT:codegen_1.operators.LT,len=it.opts.unicode===!1?(0,codegen_1._)`${data}.length`:(0,codegen_1._)`${(0,util_1.useFunc)(cxt.gen,ucs2length_1.default)}(${data})`;cxt.fail$data((0,codegen_1._)`${len} ${op} ${schemaCode}`)}};exports.default=def})),require_pattern=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let code_1=require_code(),util_1=require_util(),codegen_1=require_codegen(),def={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode})=>(0,codegen_1.str)`must match pattern "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{pattern: ${schemaCode}}`},code(cxt){let{gen,data,$data,schema:schema2,schemaCode,it}=cxt,u=it.opts.unicodeRegExp?"u":"";if($data){let{regExp}=it.opts.code,regExpCode=regExp.code==="new RegExp"?(0,codegen_1._)`new RegExp`:(0,util_1.useFunc)(gen,regExp),valid=gen.let("valid");gen.try(()=>gen.assign(valid,(0,codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`),()=>gen.assign(valid,!1)),cxt.fail$data((0,codegen_1._)`!${valid}`)}else{let regExp=(0,code_1.usePattern)(cxt,schema2);cxt.fail$data((0,codegen_1._)`!${regExp}.test(${data})`)}}};exports.default=def})),require_limitProperties=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),def={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword,schemaCode}){let comp=keyword==="maxProperties"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`},code(cxt){let{keyword,data,schemaCode}=cxt,op=keyword==="maxProperties"?codegen_1.operators.GT:codegen_1.operators.LT;cxt.fail$data((0,codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`)}};exports.default=def})),require_required=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let code_1=require_code(),codegen_1=require_codegen(),util_1=require_util(),def={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty}})=>(0,codegen_1.str)`must have required property '${missingProperty}'`,params:({params:{missingProperty}})=>(0,codegen_1._)`{missingProperty: ${missingProperty}}`},code(cxt){let{gen,schema:schema2,schemaCode,data,$data,it}=cxt,{opts}=it;if(!$data&&schema2.length===0)return;let useLoop=schema2.length>=opts.loopRequired;if(it.allErrors?allErrorsMode():exitOnErrorMode(),opts.strictRequired){let props=cxt.parentSchema.properties,{definedProperties}=cxt.it;for(let requiredKey of schema2)if(props?.[requiredKey]===void 0&&!definedProperties.has(requiredKey)){let msg=`required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId+it.errSchemaPath}" (strictRequired)`;(0,util_1.checkStrictMode)(it,msg,it.opts.strictRequired)}}function allErrorsMode(){if(useLoop||$data)cxt.block$data(codegen_1.nil,loopAllRequired);else for(let prop of schema2)(0,code_1.checkReportMissingProp)(cxt,prop)}function exitOnErrorMode(){let missing=gen.let("missing");if(useLoop||$data){let valid=gen.let("valid",!0);cxt.block$data(valid,()=>loopUntilMissing(missing,valid)),cxt.ok(valid)}else gen.if((0,code_1.checkMissingProp)(cxt,schema2,missing)),(0,code_1.reportMissingProp)(cxt,missing),gen.else()}function loopAllRequired(){gen.forOf("prop",schemaCode,prop=>{cxt.setParams({missingProperty:prop}),gen.if((0,code_1.noPropertyInData)(gen,data,prop,opts.ownProperties),()=>cxt.error())})}function loopUntilMissing(missing,valid){cxt.setParams({missingProperty:missing}),gen.forOf(missing,schemaCode,()=>{gen.assign(valid,(0,code_1.propertyInData)(gen,data,missing,opts.ownProperties)),gen.if((0,codegen_1.not)(valid),()=>{cxt.error(),gen.break()})},codegen_1.nil)}}};exports.default=def})),require_limitItems=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),def={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword,schemaCode}){let comp=keyword==="maxItems"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`},code(cxt){let{keyword,data,schemaCode}=cxt,op=keyword==="maxItems"?codegen_1.operators.GT:codegen_1.operators.LT;cxt.fail$data((0,codegen_1._)`${data}.length ${op} ${schemaCode}`)}};exports.default=def})),require_equal=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let equal=require_fast_deep_equal();equal.code='require("ajv/dist/runtime/equal").default',exports.default=equal})),require_uniqueItems=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dataType_1=require_dataType(),codegen_1=require_codegen(),util_1=require_util(),equal_1=require_equal(),def={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i,j}})=>(0,codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,params:({params:{i,j}})=>(0,codegen_1._)`{i: ${i}, j: ${j}}`},code(cxt){let{gen,data,$data,schema:schema2,parentSchema,schemaCode,it}=cxt;if(!$data&&!schema2)return;let valid=gen.let("valid"),itemTypes=parentSchema.items?(0,dataType_1.getSchemaTypes)(parentSchema.items):[];cxt.block$data(valid,validateUniqueItems,(0,codegen_1._)`${schemaCode} === false`),cxt.ok(valid);function validateUniqueItems(){let i=gen.let("i",(0,codegen_1._)`${data}.length`),j=gen.let("j");cxt.setParams({i,j}),gen.assign(valid,!0),gen.if((0,codegen_1._)`${i} > 1`,()=>(canOptimize()?loopN:loopN2)(i,j))}function canOptimize(){return itemTypes.length>0&&!itemTypes.some(t=>t==="object"||t==="array")}function loopN(i,j){let item=gen.name("item"),wrongType=(0,dataType_1.checkDataTypes)(itemTypes,item,it.opts.strictNumbers,dataType_1.DataType.Wrong),indices=gen.const("indices",(0,codegen_1._)`{}`);gen.for((0,codegen_1._)`;${i}--;`,()=>{gen.let(item,(0,codegen_1._)`${data}[${i}]`),gen.if(wrongType,(0,codegen_1._)`continue`),itemTypes.length>1&&gen.if((0,codegen_1._)`typeof ${item} == "string"`,(0,codegen_1._)`${item} += "_"`),gen.if((0,codegen_1._)`typeof ${indices}[${item}] == "number"`,()=>{gen.assign(j,(0,codegen_1._)`${indices}[${item}]`),cxt.error(),gen.assign(valid,!1).break()}).code((0,codegen_1._)`${indices}[${item}] = ${i}`)})}function loopN2(i,j){let eql=(0,util_1.useFunc)(gen,equal_1.default),outer=gen.name("outer");gen.label(outer).for((0,codegen_1._)`;${i}--;`,()=>gen.for((0,codegen_1._)`${j} = ${i}; ${j}--;`,()=>gen.if((0,codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`,()=>{cxt.error(),gen.assign(valid,!1).break(outer)})))}}};exports.default=def})),require_const=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),equal_1=require_equal(),def={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode})=>(0,codegen_1._)`{allowedValue: ${schemaCode}}`},code(cxt){let{gen,data,$data,schemaCode,schema:schema2}=cxt;$data||schema2&&typeof schema2=="object"?cxt.fail$data((0,codegen_1._)`!${(0,util_1.useFunc)(gen,equal_1.default)}(${data}, ${schemaCode})`):cxt.fail((0,codegen_1._)`${schema2} !== ${data}`)}};exports.default=def})),require_enum=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),equal_1=require_equal(),def={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode})=>(0,codegen_1._)`{allowedValues: ${schemaCode}}`},code(cxt){let{gen,data,$data,schema:schema2,schemaCode,it}=cxt;if(!$data&&schema2.length===0)throw new Error("enum must have non-empty array");let useLoop=schema2.length>=it.opts.loopEnum,eql,getEql=()=>eql??(eql=(0,util_1.useFunc)(gen,equal_1.default)),valid;if(useLoop||$data)valid=gen.let("valid"),cxt.block$data(valid,loopEnum);else{if(!Array.isArray(schema2))throw new Error("ajv implementation error");let vSchema=gen.const("vSchema",schemaCode);valid=(0,codegen_1.or)(...schema2.map((_x,i)=>equalCode(vSchema,i)))}cxt.pass(valid);function loopEnum(){gen.assign(valid,!1),gen.forOf("v",schemaCode,v=>gen.if((0,codegen_1._)`${getEql()}(${data}, ${v})`,()=>gen.assign(valid,!0).break()))}function equalCode(vSchema,i){let sch=schema2[i];return typeof sch=="object"&&sch!==null?(0,codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])`:(0,codegen_1._)`${data} === ${sch}`}}};exports.default=def})),require_validation$2=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let limitNumber_1=require_limitNumber(),multipleOf_1=require_multipleOf(),limitLength_1=require_limitLength(),pattern_1=require_pattern(),limitProperties_1=require_limitProperties(),required_1=require_required(),limitItems_1=require_limitItems(),uniqueItems_1=require_uniqueItems(),const_1=require_const(),enum_1=require_enum(),validation=[limitNumber_1.default,multipleOf_1.default,limitLength_1.default,pattern_1.default,limitProperties_1.default,required_1.default,limitItems_1.default,uniqueItems_1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},const_1.default,enum_1.default];exports.default=validation})),require_additionalItems=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateAdditionalItems=void 0;let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},code(cxt){let{parentSchema,it}=cxt,{items}=parentSchema;if(!Array.isArray(items)){(0,util_1.checkStrictMode)(it,'"additionalItems" is ignored when "items" is not an array of schemas');return}validateAdditionalItems(cxt,items)}};function validateAdditionalItems(cxt,items){let{gen,schema:schema2,data,keyword,it}=cxt;it.items=!0;let len=gen.const("len",(0,codegen_1._)`${data}.length`);if(schema2===!1)cxt.setParams({len:items.length}),cxt.pass((0,codegen_1._)`${len} <= ${items.length}`);else if(typeof schema2=="object"&&!(0,util_1.alwaysValidSchema)(it,schema2)){let valid=gen.var("valid",(0,codegen_1._)`${len} <= ${items.length}`);gen.if((0,codegen_1.not)(valid),()=>validateItems(valid)),cxt.ok(valid)}function validateItems(valid){gen.forRange("i",items.length,len,i=>{cxt.subschema({keyword,dataProp:i,dataPropType:util_1.Type.Num},valid),it.allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break())})}}exports.validateAdditionalItems=validateAdditionalItems,exports.default=def})),require_items=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateTuple=void 0;let codegen_1=require_codegen(),util_1=require_util(),code_1=require_code(),def={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(cxt){let{schema:schema2,it}=cxt;if(Array.isArray(schema2))return validateTuple(cxt,"additionalItems",schema2);it.items=!0,!(0,util_1.alwaysValidSchema)(it,schema2)&&cxt.ok((0,code_1.validateArray)(cxt))}};function validateTuple(cxt,extraItems,schArr=cxt.schema){let{gen,parentSchema,data,keyword,it}=cxt;checkStrictTuple(parentSchema),it.opts.unevaluated&&schArr.length&&it.items!==!0&&(it.items=util_1.mergeEvaluated.items(gen,schArr.length,it.items));let valid=gen.name("valid"),len=gen.const("len",(0,codegen_1._)`${data}.length`);schArr.forEach((sch,i)=>{(0,util_1.alwaysValidSchema)(it,sch)||(gen.if((0,codegen_1._)`${len} > ${i}`,()=>cxt.subschema({keyword,schemaProp:i,dataProp:i},valid)),cxt.ok(valid))});function checkStrictTuple(sch){let{opts,errSchemaPath}=it,l=schArr.length,fullTuple=l===sch.minItems&&(l===sch.maxItems||sch[extraItems]===!1);if(opts.strictTuples&&!fullTuple){let msg=`"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;(0,util_1.checkStrictMode)(it,msg,opts.strictTuples)}}}exports.validateTuple=validateTuple,exports.default=def})),require_prefixItems=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let items_1=require_items(),def={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:cxt=>(0,items_1.validateTuple)(cxt,"items")};exports.default=def})),require_items2020=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),code_1=require_code(),additionalItems_1=require_additionalItems(),def={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},code(cxt){let{schema:schema2,parentSchema,it}=cxt,{prefixItems}=parentSchema;it.items=!0,!(0,util_1.alwaysValidSchema)(it,schema2)&&(prefixItems?(0,additionalItems_1.validateAdditionalItems)(cxt,prefixItems):cxt.ok((0,code_1.validateArray)(cxt)))}};exports.default=def})),require_contains=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min,max}})=>max===void 0?(0,codegen_1.str)`must contain at least ${min} valid item(s)`:(0,codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,params:({params:{min,max}})=>max===void 0?(0,codegen_1._)`{minContains: ${min}}`:(0,codegen_1._)`{minContains: ${min}, maxContains: ${max}}`},code(cxt){let{gen,schema:schema2,parentSchema,data,it}=cxt,min,max,{minContains,maxContains}=parentSchema;it.opts.next?(min=minContains===void 0?1:minContains,max=maxContains):min=1;let len=gen.const("len",(0,codegen_1._)`${data}.length`);if(cxt.setParams({min,max}),max===void 0&&min===0){(0,util_1.checkStrictMode)(it,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(max!==void 0&&min>max){(0,util_1.checkStrictMode)(it,'"minContains" > "maxContains" is always invalid'),cxt.fail();return}if((0,util_1.alwaysValidSchema)(it,schema2)){let cond=(0,codegen_1._)`${len} >= ${min}`;max!==void 0&&(cond=(0,codegen_1._)`${cond} && ${len} <= ${max}`),cxt.pass(cond);return}it.items=!0;let valid=gen.name("valid");max===void 0&&min===1?validateItems(valid,()=>gen.if(valid,()=>gen.break())):min===0?(gen.let(valid,!0),max!==void 0&&gen.if((0,codegen_1._)`${data}.length > 0`,validateItemsWithCount)):(gen.let(valid,!1),validateItemsWithCount()),cxt.result(valid,()=>cxt.reset());function validateItemsWithCount(){let schValid=gen.name("_valid"),count=gen.let("count",0);validateItems(schValid,()=>gen.if(schValid,()=>checkLimits(count)))}function validateItems(_valid,block){gen.forRange("i",0,len,i=>{cxt.subschema({keyword:"contains",dataProp:i,dataPropType:util_1.Type.Num,compositeRule:!0},_valid),block()})}function checkLimits(count){gen.code((0,codegen_1._)`${count}++`),max===void 0?gen.if((0,codegen_1._)`${count} >= ${min}`,()=>gen.assign(valid,!0).break()):(gen.if((0,codegen_1._)`${count} > ${max}`,()=>gen.assign(valid,!1).break()),min===1?gen.assign(valid,!0):gen.if((0,codegen_1._)`${count} >= ${min}`,()=>gen.assign(valid,!0)))}}};exports.default=def})),require_dependencies=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateSchemaDeps=exports.validatePropertyDeps=exports.error=void 0;let codegen_1=require_codegen(),util_1=require_util(),code_1=require_code();exports.error={message:({params:{property,depsCount,deps}})=>{let property_ies=depsCount===1?"property":"properties";return(0,codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`},params:({params:{property,depsCount,deps,missingProperty}})=>(0,codegen_1._)`{property: ${property},
69
62
  missingProperty: ${missingProperty},
70
63
  depsCount: ${depsCount},
71
- deps: ${deps}}`};let def={keyword:"dependencies",type:"object",schemaType:"object",error:exports.error,code(cxt){let[propDeps,schDeps]=splitDependencies(cxt);validatePropertyDeps(cxt,propDeps),validateSchemaDeps(cxt,schDeps)}};function splitDependencies({schema:schema2}){let propertyDeps={},schemaDeps={};for(let key in schema2){if(key==="__proto__")continue;let deps=Array.isArray(schema2[key])?propertyDeps:schemaDeps;deps[key]=schema2[key]}return[propertyDeps,schemaDeps]}function validatePropertyDeps(cxt,propertyDeps=cxt.schema){let{gen,data,it}=cxt;if(Object.keys(propertyDeps).length===0)return;let missing=gen.let("missing");for(let prop in propertyDeps){let deps=propertyDeps[prop];if(deps.length===0)continue;let hasProperty=(0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties);cxt.setParams({property:prop,depsCount:deps.length,deps:deps.join(", ")}),it.allErrors?gen.if(hasProperty,()=>{for(let depProp of deps)(0,code_1.checkReportMissingProp)(cxt,depProp)}):(gen.if((0,codegen_1._)`${hasProperty} && (${(0,code_1.checkMissingProp)(cxt,deps,missing)})`),(0,code_1.reportMissingProp)(cxt,missing),gen.else())}}exports.validatePropertyDeps=validatePropertyDeps;function validateSchemaDeps(cxt,schemaDeps=cxt.schema){let{gen,data,keyword,it}=cxt,valid=gen.name("valid");for(let prop in schemaDeps)(0,util_1.alwaysValidSchema)(it,schemaDeps[prop])||(gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties),()=>{let schCxt=cxt.subschema({keyword,schemaProp:prop},valid);cxt.mergeValidEvaluated(schCxt,valid)},()=>gen.var(valid,!0)),cxt.ok(valid))}exports.validateSchemaDeps=validateSchemaDeps,exports.default=def})),require_propertyNames=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params})=>(0,codegen_1._)`{propertyName: ${params.propertyName}}`},code(cxt){let{gen,schema:schema2,data,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema2))return;let valid=gen.name("valid");gen.forIn("key",data,key=>{cxt.setParams({propertyName:key}),cxt.subschema({keyword:"propertyNames",data:key,dataTypes:["string"],propertyName:key,compositeRule:!0},valid),gen.if((0,codegen_1.not)(valid),()=>{cxt.error(!0),it.allErrors||gen.break()})}),cxt.ok(valid)}};exports.default=def})),require_additionalProperties=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let code_1=require_code(),codegen_1=require_codegen(),names_1=require_names(),util_1=require_util(),def={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params})=>(0,codegen_1._)`{additionalProperty: ${params.additionalProperty}}`},code(cxt){let{gen,schema:schema2,parentSchema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");let{allErrors,opts}=it;if(it.props=!0,opts.removeAdditional!=="all"&&(0,util_1.alwaysValidSchema)(it,schema2))return;let props=(0,code_1.allSchemaProperties)(parentSchema.properties),patProps=(0,code_1.allSchemaProperties)(parentSchema.patternProperties);checkAdditionalProperties(),cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function checkAdditionalProperties(){gen.forIn("key",data,key=>{!props.length&&!patProps.length?additionalPropertyCode(key):gen.if(isAdditional(key),()=>additionalPropertyCode(key))})}function isAdditional(key){let definedProp;if(props.length>8){let propsSchema=(0,util_1.schemaRefOrVal)(it,parentSchema.properties,"properties");definedProp=(0,code_1.isOwnProperty)(gen,propsSchema,key)}else props.length?definedProp=(0,codegen_1.or)(...props.map(p=>(0,codegen_1._)`${key} === ${p}`)):definedProp=codegen_1.nil;return patProps.length&&(definedProp=(0,codegen_1.or)(definedProp,...patProps.map(p=>(0,codegen_1._)`${(0,code_1.usePattern)(cxt,p)}.test(${key})`))),(0,codegen_1.not)(definedProp)}function deleteAdditional(key){gen.code((0,codegen_1._)`delete ${data}[${key}]`)}function additionalPropertyCode(key){if(opts.removeAdditional==="all"||opts.removeAdditional&&schema2===!1){deleteAdditional(key);return}if(schema2===!1){cxt.setParams({additionalProperty:key}),cxt.error(),allErrors||gen.break();return}if(typeof schema2=="object"&&!(0,util_1.alwaysValidSchema)(it,schema2)){let valid=gen.name("valid");opts.removeAdditional==="failing"?(applyAdditionalSchema(key,valid,!1),gen.if((0,codegen_1.not)(valid),()=>{cxt.reset(),deleteAdditional(key)})):(applyAdditionalSchema(key,valid),allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break()))}}function applyAdditionalSchema(key,valid,errors2){let subschema={keyword:"additionalProperties",dataProp:key,dataPropType:util_1.Type.Str};errors2===!1&&Object.assign(subschema,{compositeRule:!0,createErrors:!1,allErrors:!1}),cxt.subschema(subschema,valid)}}};exports.default=def})),require_properties=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let validate_1=require_validate(),code_1=require_code(),util_1=require_util(),additionalProperties_1=require_additionalProperties(),def={keyword:"properties",type:"object",schemaType:"object",code(cxt){let{gen,schema:schema2,parentSchema,data,it}=cxt;it.opts.removeAdditional==="all"&&parentSchema.additionalProperties===void 0&&additionalProperties_1.default.code(new validate_1.KeywordCxt(it,additionalProperties_1.default,"additionalProperties"));let allProps=(0,code_1.allSchemaProperties)(schema2);for(let prop of allProps)it.definedProperties.add(prop);it.opts.unevaluated&&allProps.length&&it.props!==!0&&(it.props=util_1.mergeEvaluated.props(gen,(0,util_1.toHash)(allProps),it.props));let properties=allProps.filter(p=>!(0,util_1.alwaysValidSchema)(it,schema2[p]));if(properties.length===0)return;let valid=gen.name("valid");for(let prop of properties)hasDefault(prop)?applyPropertySchema(prop):(gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties)),applyPropertySchema(prop),it.allErrors||gen.else().var(valid,!0),gen.endIf()),cxt.it.definedProperties.add(prop),cxt.ok(valid);function hasDefault(prop){return it.opts.useDefaults&&!it.compositeRule&&schema2[prop].default!==void 0}function applyPropertySchema(prop){cxt.subschema({keyword:"properties",schemaProp:prop,dataProp:prop},valid)}}};exports.default=def})),require_patternProperties=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let code_1=require_code(),codegen_1=require_codegen(),util_1=require_util(),util_2=require_util(),def={keyword:"patternProperties",type:"object",schemaType:"object",code(cxt){let{gen,schema:schema2,data,parentSchema,it}=cxt,{opts}=it,patterns=(0,code_1.allSchemaProperties)(schema2),alwaysValidPatterns=patterns.filter(p=>(0,util_1.alwaysValidSchema)(it,schema2[p]));if(patterns.length===0||alwaysValidPatterns.length===patterns.length&&(!it.opts.unevaluated||it.props===!0))return;let checkProperties=opts.strictSchema&&!opts.allowMatchingProperties&&parentSchema.properties,valid=gen.name("valid");it.props!==!0&&!(it.props instanceof codegen_1.Name)&&(it.props=(0,util_2.evaluatedPropsToName)(gen,it.props));let{props}=it;validatePatternProperties();function validatePatternProperties(){for(let pat of patterns)checkProperties&&checkMatchingProperties(pat),it.allErrors?validateProperties(pat):(gen.var(valid,!0),validateProperties(pat),gen.if(valid))}function checkMatchingProperties(pat){for(let prop in checkProperties)new RegExp(pat).test(prop)&&(0,util_1.checkStrictMode)(it,`property ${prop} matches pattern ${pat} (use allowMatchingProperties)`)}function validateProperties(pat){gen.forIn("key",data,key=>{gen.if((0,codegen_1._)`${(0,code_1.usePattern)(cxt,pat)}.test(${key})`,()=>{let alwaysValid=alwaysValidPatterns.includes(pat);alwaysValid||cxt.subschema({keyword:"patternProperties",schemaProp:pat,dataProp:key,dataPropType:util_2.Type.Str},valid),it.opts.unevaluated&&props!==!0?gen.assign((0,codegen_1._)`${props}[${key}]`,!0):!alwaysValid&&!it.allErrors&&gen.if((0,codegen_1.not)(valid),()=>gen.break())})})}}};exports.default=def})),require_not=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let util_1=require_util(),def={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(cxt){let{gen,schema:schema2,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema2)){cxt.fail();return}let valid=gen.name("valid");cxt.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},valid),cxt.failResult(valid,()=>cxt.reset(),()=>cxt.error())},error:{message:"must NOT be valid"}};exports.default=def})),require_anyOf=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let def={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:require_code().validateUnion,error:{message:"must match a schema in anyOf"}};exports.default=def})),require_oneOf=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params})=>(0,codegen_1._)`{passingSchemas: ${params.passing}}`},code(cxt){let{gen,schema:schema2,parentSchema,it}=cxt;if(!Array.isArray(schema2))throw new Error("ajv implementation error");if(it.opts.discriminator&&parentSchema.discriminator)return;let schArr=schema2,valid=gen.let("valid",!1),passing=gen.let("passing",null),schValid=gen.name("_valid");cxt.setParams({passing}),gen.block(validateOneOf),cxt.result(valid,()=>cxt.reset(),()=>cxt.error(!0));function validateOneOf(){schArr.forEach((sch,i)=>{let schCxt;(0,util_1.alwaysValidSchema)(it,sch)?gen.var(schValid,!0):schCxt=cxt.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},schValid),i>0&&gen.if((0,codegen_1._)`${schValid} && ${valid}`).assign(valid,!1).assign(passing,(0,codegen_1._)`[${passing}, ${i}]`).else(),gen.if(schValid,()=>{gen.assign(valid,!0),gen.assign(passing,i),schCxt&&cxt.mergeEvaluated(schCxt,codegen_1.Name)})})}}};exports.default=def})),require_allOf=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let util_1=require_util(),def={keyword:"allOf",schemaType:"array",code(cxt){let{gen,schema:schema2,it}=cxt;if(!Array.isArray(schema2))throw new Error("ajv implementation error");let valid=gen.name("valid");schema2.forEach((sch,i)=>{if((0,util_1.alwaysValidSchema)(it,sch))return;let schCxt=cxt.subschema({keyword:"allOf",schemaProp:i},valid);cxt.ok(valid),cxt.mergeEvaluated(schCxt)})}};exports.default=def})),require_if=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params})=>(0,codegen_1.str)`must match "${params.ifClause}" schema`,params:({params})=>(0,codegen_1._)`{failingKeyword: ${params.ifClause}}`},code(cxt){let{gen,parentSchema,it}=cxt;parentSchema.then===void 0&&parentSchema.else===void 0&&(0,util_1.checkStrictMode)(it,'"if" without "then" and "else" is ignored');let hasThen=hasSchema(it,"then"),hasElse=hasSchema(it,"else");if(!hasThen&&!hasElse)return;let valid=gen.let("valid",!0),schValid=gen.name("_valid");if(validateIf(),cxt.reset(),hasThen&&hasElse){let ifClause=gen.let("ifClause");cxt.setParams({ifClause}),gen.if(schValid,validateClause("then",ifClause),validateClause("else",ifClause))}else hasThen?gen.if(schValid,validateClause("then")):gen.if((0,codegen_1.not)(schValid),validateClause("else"));cxt.pass(valid,()=>cxt.error(!0));function validateIf(){let schCxt=cxt.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},schValid);cxt.mergeEvaluated(schCxt)}function validateClause(keyword,ifClause){return()=>{let schCxt=cxt.subschema({keyword},schValid);gen.assign(valid,schValid),cxt.mergeValidEvaluated(schCxt,valid),ifClause?gen.assign(ifClause,(0,codegen_1._)`${keyword}`):cxt.setParams({ifClause:keyword})}}}};function hasSchema(it,keyword){let schema2=it.schema[keyword];return schema2!==void 0&&!(0,util_1.alwaysValidSchema)(it,schema2)}exports.default=def})),require_thenElse=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let util_1=require_util(),def={keyword:["then","else"],schemaType:["object","boolean"],code({keyword,parentSchema,it}){parentSchema.if===void 0&&(0,util_1.checkStrictMode)(it,`"${keyword}" without "if" is ignored`)}};exports.default=def})),require_applicator$2=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let additionalItems_1=require_additionalItems(),prefixItems_1=require_prefixItems(),items_1=require_items(),items2020_1=require_items2020(),contains_1=require_contains(),dependencies_1=require_dependencies(),propertyNames_1=require_propertyNames(),additionalProperties_1=require_additionalProperties(),properties_1=require_properties(),patternProperties_1=require_patternProperties(),not_1=require_not(),anyOf_1=require_anyOf(),oneOf_1=require_oneOf(),allOf_1=require_allOf(),if_1=require_if(),thenElse_1=require_thenElse();function getApplicator(draft2020=!1){let applicator=[not_1.default,anyOf_1.default,oneOf_1.default,allOf_1.default,if_1.default,thenElse_1.default,propertyNames_1.default,additionalProperties_1.default,dependencies_1.default,properties_1.default,patternProperties_1.default];return draft2020?applicator.push(prefixItems_1.default,items2020_1.default):applicator.push(additionalItems_1.default,items_1.default),applicator.push(contains_1.default),applicator}exports.default=getApplicator})),require_format$2=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),def={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode})=>(0,codegen_1.str)`must match format "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{format: ${schemaCode}}`},code(cxt,ruleType){let{gen,data,$data,schema:schema2,schemaCode,it}=cxt,{opts,errSchemaPath,schemaEnv,self}=it;if(!opts.validateFormats)return;$data?validate$DataFormat():validateFormat();function validate$DataFormat(){let fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats}),fDef=gen.const("fDef",(0,codegen_1._)`${fmts}[${schemaCode}]`),fType=gen.let("fType"),format=gen.let("format");gen.if((0,codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,()=>gen.assign(fType,(0,codegen_1._)`${fDef}.type || "string"`).assign(format,(0,codegen_1._)`${fDef}.validate`),()=>gen.assign(fType,(0,codegen_1._)`"string"`).assign(format,fDef)),cxt.fail$data((0,codegen_1.or)(unknownFmt(),invalidFmt()));function unknownFmt(){return opts.strictSchema===!1?codegen_1.nil:(0,codegen_1._)`${schemaCode} && !${format}`}function invalidFmt(){let callFormat=schemaEnv.$async?(0,codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`:(0,codegen_1._)`${format}(${data})`,validData=(0,codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;return(0,codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`}}function validateFormat(){let formatDef=self.formats[schema2];if(!formatDef){unknownFormat();return}if(formatDef===!0)return;let[fmtType,format,fmtRef]=getFormat(formatDef);fmtType===ruleType&&cxt.pass(validCondition());function unknownFormat(){if(opts.strictSchema===!1){self.logger.warn(unknownMsg());return}throw new Error(unknownMsg());function unknownMsg(){return`unknown format "${schema2}" ignored in schema at path "${errSchemaPath}"`}}function getFormat(fmtDef){let code=fmtDef instanceof RegExp?(0,codegen_1.regexpCode)(fmtDef):opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(schema2)}`:void 0,fmt=gen.scopeValue("formats",{key:schema2,ref:fmtDef,code});return typeof fmtDef=="object"&&!(fmtDef instanceof RegExp)?[fmtDef.type||"string",fmtDef.validate,(0,codegen_1._)`${fmt}.validate`]:["string",fmtDef,fmt]}function validCondition(){if(typeof formatDef=="object"&&!(formatDef instanceof RegExp)&&formatDef.async){if(!schemaEnv.$async)throw new Error("async format in sync schema");return(0,codegen_1._)`await ${fmtRef}(${data})`}return typeof format=="function"?(0,codegen_1._)`${fmtRef}(${data})`:(0,codegen_1._)`${fmtRef}.test(${data})`}}}};exports.default=def})),require_format$1=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let format=[require_format$2().default];exports.default=format})),require_metadata=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.contentVocabulary=exports.metadataVocabulary=void 0,exports.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],exports.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]})),require_draft7=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let core_1=require_core$2(),validation_1=require_validation$2(),applicator_1=require_applicator$2(),format_1=require_format$1(),metadata_1=require_metadata(),draft7Vocabularies=[core_1.default,validation_1.default,(0,applicator_1.default)(),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary];exports.default=draft7Vocabularies})),require_types=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.DiscrError=void 0;var DiscrError;(function(DiscrError2){DiscrError2.Tag="tag",DiscrError2.Mapping="mapping"})(DiscrError||(exports.DiscrError=DiscrError={}))})),require_discriminator=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),types_1=require_types(),compile_1=require_compile(),ref_error_1=require_ref_error(),util_1=require_util(),def={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError,tagName}})=>discrError===types_1.DiscrError.Tag?`tag "${tagName}" must be string`:`value of tag "${tagName}" must be in oneOf`,params:({params:{discrError,tag,tagName}})=>(0,codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`},code(cxt){let{gen,data,schema:schema2,parentSchema,it}=cxt,{oneOf}=parentSchema;if(!it.opts.discriminator)throw new Error("discriminator: requires discriminator option");let tagName=schema2.propertyName;if(typeof tagName!="string")throw new Error("discriminator: requires propertyName");if(schema2.mapping)throw new Error("discriminator: mapping is not supported");if(!oneOf)throw new Error("discriminator: requires oneOf keyword");let valid=gen.let("valid",!1),tag=gen.const("tag",(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(tagName)}`);gen.if((0,codegen_1._)`typeof ${tag} == "string"`,()=>validateMapping(),()=>cxt.error(!1,{discrError:types_1.DiscrError.Tag,tag,tagName})),cxt.ok(valid);function validateMapping(){let mapping=getMapping();gen.if(!1);for(let tagValue in mapping)gen.elseIf((0,codegen_1._)`${tag} === ${tagValue}`),gen.assign(valid,applyTagSchema(mapping[tagValue]));gen.else(),cxt.error(!1,{discrError:types_1.DiscrError.Mapping,tag,tagName}),gen.endIf()}function applyTagSchema(schemaProp){let _valid=gen.name("valid"),schCxt=cxt.subschema({keyword:"oneOf",schemaProp},_valid);return cxt.mergeEvaluated(schCxt,codegen_1.Name),_valid}function getMapping(){var _a3;let oneOfMapping={},topRequired=hasRequired(parentSchema),tagRequired=!0;for(let i=0;i<oneOf.length;i++){let sch=oneOf[i];if(sch?.$ref&&!(0,util_1.schemaHasRulesButRef)(sch,it.self.RULES)){let ref=sch.$ref;if(sch=compile_1.resolveRef.call(it.self,it.schemaEnv.root,it.baseId,ref),sch instanceof compile_1.SchemaEnv&&(sch=sch.schema),sch===void 0)throw new ref_error_1.default(it.opts.uriResolver,it.baseId,ref)}let propSch=(_a3=sch?.properties)===null||_a3===void 0?void 0:_a3[tagName];if(typeof propSch!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);tagRequired=tagRequired&&(topRequired||hasRequired(sch)),addMappings(propSch,i)}if(!tagRequired)throw new Error(`discriminator: "${tagName}" must be required`);return oneOfMapping;function hasRequired({required:required2}){return Array.isArray(required2)&&required2.includes(tagName)}function addMappings(sch,i){if(sch.const)addMapping(sch.const,i);else if(sch.enum)for(let tagValue of sch.enum)addMapping(tagValue,i);else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)}function addMapping(tagValue,i){if(typeof tagValue!="string"||tagValue in oneOfMapping)throw new Error(`discriminator: "${tagName}" values must be unique strings`);oneOfMapping[tagValue]=i}}}};exports.default=def})),require_json_schema_draft_07=__commonJSMin(((exports,module)=>{module.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}})),require_ajv=__commonJSMin(((exports,module)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv=void 0;let core_1=require_core$3(),draft7_1=require_draft7(),discriminator_1=require_discriminator(),draft7MetaSchema=require_json_schema_draft_07(),META_SUPPORT_DATA=["/properties"],META_SCHEMA_ID="http://json-schema.org/draft-07/schema";var Ajv2=class extends core_1.default{_addVocabularies(){super._addVocabularies(),draft7_1.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let metaSchema=this.opts.$data?this.$dataMetaSchema(draft7MetaSchema,META_SUPPORT_DATA):draft7MetaSchema;this.addMetaSchema(metaSchema,META_SCHEMA_ID,!1),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv=Ajv2,module.exports=exports=Ajv2,module.exports.Ajv=Ajv2,Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=Ajv2;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})})),require_dynamicAnchor=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.dynamicAnchor=void 0;let codegen_1=require_codegen(),names_1=require_names(),compile_1=require_compile(),ref_1=require_ref(),def={keyword:"$dynamicAnchor",schemaType:"string",code:cxt=>dynamicAnchor(cxt,cxt.schema)};function dynamicAnchor(cxt,anchor){let{gen,it}=cxt;it.schemaEnv.root.dynamicAnchors[anchor]=!0;let v=(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor)}`,validate=it.errSchemaPath==="#"?it.validateName:_getValidate(cxt);gen.if((0,codegen_1._)`!${v}`,()=>gen.assign(v,validate))}exports.dynamicAnchor=dynamicAnchor;function _getValidate(cxt){let{schemaEnv,schema:schema2,self}=cxt.it,{root,baseId,localRefs,meta:meta2}=schemaEnv.root,{schemaId}=self.opts,sch=new compile_1.SchemaEnv({schema:schema2,schemaId,root,baseId,localRefs,meta:meta2});return compile_1.compileSchema.call(self,sch),(0,ref_1.getValidate)(cxt,sch)}exports.default=def})),require_dynamicRef=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.dynamicRef=void 0;let codegen_1=require_codegen(),names_1=require_names(),ref_1=require_ref(),def={keyword:"$dynamicRef",schemaType:"string",code:cxt=>dynamicRef(cxt,cxt.schema)};function dynamicRef(cxt,ref){let{gen,keyword,it}=cxt;if(ref[0]!=="#")throw new Error(`"${keyword}" only supports hash fragment reference`);let anchor=ref.slice(1);if(it.allErrors)_dynamicRef();else{let valid=gen.let("valid",!1);_dynamicRef(valid),cxt.ok(valid)}function _dynamicRef(valid){if(it.schemaEnv.root.dynamicAnchors[anchor]){let v=gen.let("_v",(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor)}`);gen.if(v,_callRef(v,valid),_callRef(it.validateName,valid))}else _callRef(it.validateName,valid)()}function _callRef(validate,valid){return valid?()=>gen.block(()=>{(0,ref_1.callRef)(cxt,validate),gen.let(valid,!0)}):()=>(0,ref_1.callRef)(cxt,validate)}}exports.dynamicRef=dynamicRef,exports.default=def})),require_recursiveAnchor=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dynamicAnchor_1=require_dynamicAnchor(),util_1=require_util(),def={keyword:"$recursiveAnchor",schemaType:"boolean",code(cxt){cxt.schema?(0,dynamicAnchor_1.dynamicAnchor)(cxt,""):(0,util_1.checkStrictMode)(cxt.it,"$recursiveAnchor: false is ignored")}};exports.default=def})),require_recursiveRef=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dynamicRef_1=require_dynamicRef(),def={keyword:"$recursiveRef",schemaType:"string",code:cxt=>(0,dynamicRef_1.dynamicRef)(cxt,cxt.schema)};exports.default=def})),require_dynamic=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dynamicAnchor_1=require_dynamicAnchor(),dynamicRef_1=require_dynamicRef(),recursiveAnchor_1=require_recursiveAnchor(),recursiveRef_1=require_recursiveRef(),dynamic=[dynamicAnchor_1.default,dynamicRef_1.default,recursiveAnchor_1.default,recursiveRef_1.default];exports.default=dynamic})),require_dependentRequired=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dependencies_1=require_dependencies(),def={keyword:"dependentRequired",type:"object",schemaType:"object",error:dependencies_1.error,code:cxt=>(0,dependencies_1.validatePropertyDeps)(cxt)};exports.default=def})),require_dependentSchemas=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dependencies_1=require_dependencies(),def={keyword:"dependentSchemas",type:"object",schemaType:"object",code:cxt=>(0,dependencies_1.validateSchemaDeps)(cxt)};exports.default=def})),require_limitContains=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let util_1=require_util(),def={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword,parentSchema,it}){parentSchema.contains===void 0&&(0,util_1.checkStrictMode)(it,`"${keyword}" without "contains" is ignored`)}};exports.default=def})),require_next=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dependentRequired_1=require_dependentRequired(),dependentSchemas_1=require_dependentSchemas(),limitContains_1=require_limitContains(),next=[dependentRequired_1.default,dependentSchemas_1.default,limitContains_1.default];exports.default=next})),require_unevaluatedProperties=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),names_1=require_names(),def={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params})=>(0,codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}`},code(cxt){let{gen,schema:schema2,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");let{allErrors,props}=it;props instanceof codegen_1.Name?gen.if((0,codegen_1._)`${props} !== true`,()=>gen.forIn("key",data,key=>gen.if(unevaluatedDynamic(props,key),()=>unevaluatedPropCode(key)))):props!==!0&&gen.forIn("key",data,key=>props===void 0?unevaluatedPropCode(key):gen.if(unevaluatedStatic(props,key),()=>unevaluatedPropCode(key))),it.props=!0,cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function unevaluatedPropCode(key){if(schema2===!1){cxt.setParams({unevaluatedProperty:key}),cxt.error(),allErrors||gen.break();return}if(!(0,util_1.alwaysValidSchema)(it,schema2)){let valid=gen.name("valid");cxt.subschema({keyword:"unevaluatedProperties",dataProp:key,dataPropType:util_1.Type.Str},valid),allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break())}}function unevaluatedDynamic(evaluatedProps,key){return(0,codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`}function unevaluatedStatic(evaluatedProps,key){let ps=[];for(let p in evaluatedProps)evaluatedProps[p]===!0&&ps.push((0,codegen_1._)`${key} !== ${p}`);return(0,codegen_1.and)(...ps)}}};exports.default=def})),require_unevaluatedItems=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},code(cxt){let{gen,schema:schema2,data,it}=cxt,items=it.items||0;if(items===!0)return;let len=gen.const("len",(0,codegen_1._)`${data}.length`);if(schema2===!1)cxt.setParams({len:items}),cxt.fail((0,codegen_1._)`${len} > ${items}`);else if(typeof schema2=="object"&&!(0,util_1.alwaysValidSchema)(it,schema2)){let valid=gen.var("valid",(0,codegen_1._)`${len} <= ${items}`);gen.if((0,codegen_1.not)(valid),()=>validateItems(valid,items)),cxt.ok(valid)}it.items=!0;function validateItems(valid,from){gen.forRange("i",from,len,i=>{cxt.subschema({keyword:"unevaluatedItems",dataProp:i,dataPropType:util_1.Type.Num},valid),it.allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break())})}}};exports.default=def})),require_unevaluated$1=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let unevaluatedProperties_1=require_unevaluatedProperties(),unevaluatedItems_1=require_unevaluatedItems(),unevaluated=[unevaluatedProperties_1.default,unevaluatedItems_1.default];exports.default=unevaluated})),require_schema$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/schema",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format"},{$ref:"meta/content"}],type:["object","boolean"],properties:{definitions:{$comment:"While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},dependencies:{$comment:'"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"',type:"object",additionalProperties:{anyOf:[{$recursiveRef:"#"},{$ref:"meta/validation#/$defs/stringArray"}]}}}}})),require_applicator$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{additionalItems:{$recursiveRef:"#"},unevaluatedItems:{$recursiveRef:"#"},items:{anyOf:[{$recursiveRef:"#"},{$ref:"#/$defs/schemaArray"}]},contains:{$recursiveRef:"#"},additionalProperties:{$recursiveRef:"#"},unevaluatedProperties:{$recursiveRef:"#"},properties:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$recursiveRef:"#"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$recursiveRef:"#"}},propertyNames:{$recursiveRef:"#"},if:{$recursiveRef:"#"},then:{$recursiveRef:"#"},else:{$recursiveRef:"#"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$recursiveRef:"#"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$recursiveRef:"#"}}}}})),require_content$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/content",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentMediaType:{type:"string"},contentEncoding:{type:"string"},contentSchema:{$recursiveRef:"#"}}}})),require_core$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/core",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{type:"string",format:"uri"},$anchor:{type:"string",pattern:"^[A-Za-z][-A-Za-z0-9.:_]*$"},$ref:{type:"string",format:"uri-reference"},$recursiveRef:{type:"string",format:"uri-reference"},$recursiveAnchor:{type:"boolean",default:!1},$vocabulary:{type:"object",propertyNames:{type:"string",format:"uri"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}}}}})),require_format=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/format",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:"Format vocabulary meta-schema",type:["object","boolean"],properties:{format:{type:"string"}}}})),require_meta_data$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),require_validation$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/validation",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}},const:!0,enum:{type:"array",items:!0},type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),require_json_schema_2019_09=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let metaSchema=require_schema$1(),applicator=require_applicator$1(),content=require_content$1(),core=require_core$1(),format=require_format(),metadata=require_meta_data$1(),validation=require_validation$1(),META_SUPPORT_DATA=["/properties"];function addMetaSchema2019($data){return[metaSchema,applicator,content,core,with$data(this,format),metadata,with$data(this,validation)].forEach(sch=>this.addMetaSchema(sch,void 0,!1)),this;function with$data(ajv,sch){return $data?ajv.$dataMetaSchema(sch,META_SUPPORT_DATA):sch}}exports.default=addMetaSchema2019})),require__2019=__commonJSMin(((exports,module)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv2019=void 0;let core_1=require_core$3(),draft7_1=require_draft7(),dynamic_1=require_dynamic(),next_1=require_next(),unevaluated_1=require_unevaluated$1(),discriminator_1=require_discriminator(),json_schema_2019_09_1=require_json_schema_2019_09(),META_SCHEMA_ID="https://json-schema.org/draft/2019-09/schema";var Ajv2019=class extends core_1.default{constructor(opts={}){super({...opts,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(dynamic_1.default),draft7_1.default.forEach(v=>this.addVocabulary(v)),this.addVocabulary(next_1.default),this.addVocabulary(unevaluated_1.default),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data,meta:meta2}=this.opts;meta2&&(json_schema_2019_09_1.default.call(this,$data),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv2019=Ajv2019,module.exports=exports=Ajv2019,module.exports.Ajv2019=Ajv2019,Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=Ajv2019;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})})),require_draft2020=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let core_1=require_core$2(),validation_1=require_validation$2(),applicator_1=require_applicator$2(),dynamic_1=require_dynamic(),next_1=require_next(),unevaluated_1=require_unevaluated$1(),format_1=require_format$1(),metadata_1=require_metadata(),draft2020Vocabularies=[dynamic_1.default,core_1.default,validation_1.default,(0,applicator_1.default)(!0),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary,next_1.default,unevaluated_1.default];exports.default=draft2020Vocabularies})),require_schema=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}})),require_applicator=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}})),require_unevaluated=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}})),require_content=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}})),require_core=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}})),require_format_annotation=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}})),require_meta_data=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),require_validation=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),require_json_schema_2020_12=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let metaSchema=require_schema(),applicator=require_applicator(),unevaluated=require_unevaluated(),content=require_content(),core=require_core(),format=require_format_annotation(),metadata=require_meta_data(),validation=require_validation(),META_SUPPORT_DATA=["/properties"];function addMetaSchema2020($data){return[metaSchema,applicator,unevaluated,content,core,with$data(this,format),metadata,with$data(this,validation)].forEach(sch=>this.addMetaSchema(sch,void 0,!1)),this;function with$data(ajv,sch){return $data?ajv.$dataMetaSchema(sch,META_SUPPORT_DATA):sch}}exports.default=addMetaSchema2020})),require__2020=__commonJSMin(((exports,module)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv2020=void 0;let core_1=require_core$3(),draft2020_1=require_draft2020(),discriminator_1=require_discriminator(),json_schema_2020_12_1=require_json_schema_2020_12(),META_SCHEMA_ID="https://json-schema.org/draft/2020-12/schema";var Ajv2020=class extends core_1.default{constructor(opts={}){super({...opts,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),draft2020_1.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data,meta:meta2}=this.opts;meta2&&(json_schema_2020_12_1.default.call(this,$data),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv2020=Ajv2020,module.exports=exports=Ajv2020,module.exports.Ajv2020=Ajv2020,Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=Ajv2020;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})})),require_formats=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatNames=exports.fastFormats=exports.fullFormats=void 0;function fmtDef(validate,compare){return{validate,compare}}exports.fullFormats={date:fmtDef(date4,compareDate),time:fmtDef(getTime(!0),compareTime),"date-time":fmtDef(getDateTime(!0),compareDateTime),"iso-time":fmtDef(getTime(),compareIsoTime),"iso-date-time":fmtDef(getDateTime(),compareIsoDateTime),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:!0,binary:!0},exports.fastFormats={...exports.fullFormats,date:fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,compareDate),time:fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareTime),"date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareDateTime),"iso-time":fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoTime),"iso-date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoDateTime),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},exports.formatNames=Object.keys(exports.fullFormats);function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}let DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date4(str){let matches=DATE.exec(str);if(!matches)return!1;let year=+matches[1],month=+matches[2],day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}function compareDate(d1,d2){if(d1&&d2)return d1>d2?1:d1<d2?-1:0}let TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function(str){let matches=TIME.exec(str);if(!matches)return!1;let hr=+matches[1],min=+matches[2],sec=+matches[3],tz=matches[4],tzSign=matches[5]==="-"?-1:1,tzH=+(matches[6]||0),tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return!1;if(hr<=23&&min<=59&&sec<60)return!0;let utcMin=min-tzM*tzSign,utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}function compareTime(s1,s2){if(!(s1&&s2))return;let t1=new Date("2020-01-01T"+s1).valueOf(),t2=new Date("2020-01-01T"+s2).valueOf();if(t1&&t2)return t1-t2}function compareIsoTime(t1,t2){if(!(t1&&t2))return;let a1=TIME.exec(t1),a2=TIME.exec(t2);if(a1&&a2)return t1=a1[1]+a1[2]+a1[3],t2=a2[1]+a2[2]+a2[3],t1>t2?1:t1<t2?-1:0}let DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){let time3=getTime(strictTimeZone);return function(str){let dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date4(dateTime[0])&&time3(dateTime[1])}}function compareDateTime(dt1,dt2){if(!(dt1&&dt2))return;let d1=new Date(dt1).valueOf(),d2=new Date(dt2).valueOf();if(d1&&d2)return d1-d2}function compareIsoDateTime(dt1,dt2){if(!(dt1&&dt2))return;let[d1,t1]=dt1.split(DATE_TIME_SEPARATOR),[d2,t2]=dt2.split(DATE_TIME_SEPARATOR),res=compareDate(d1,d2);if(res!==void 0)return res||compareTime(t1,t2)}let NOT_URI_FRAGMENT=/\/|:/,URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}let BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str){return BYTE.lastIndex=0,BYTE.test(str)}let MIN_INT32=-(2**31),MAX_INT32=2**31-1;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return!0}let Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return!1;try{return new RegExp(str),!0}catch{return!1}}})),require_limit=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatLimitDefinition=void 0;let ajv_1=require_ajv(),codegen_1=require_codegen(),ops=codegen_1.operators,KWDs={formatMaximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},formatMinimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},formatExclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},formatExclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}},error3={message:({keyword,schemaCode})=>(0,codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`};exports.formatLimitDefinition={keyword:Object.keys(KWDs),type:"string",schemaType:"string",$data:!0,error:error3,code(cxt){let{gen,data,schemaCode,keyword,it}=cxt,{opts,self}=it;if(!opts.validateFormats)return;let fCxt=new ajv_1.KeywordCxt(it,self.RULES.all.format.definition,"format");fCxt.$data?validate$DataFormat():validateFormat();function validate$DataFormat(){let fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats}),fmt=gen.const("fmt",(0,codegen_1._)`${fmts}[${fCxt.schemaCode}]`);cxt.fail$data((0,codegen_1.or)((0,codegen_1._)`typeof ${fmt} != "object"`,(0,codegen_1._)`${fmt} instanceof RegExp`,(0,codegen_1._)`typeof ${fmt}.compare != "function"`,compareCode(fmt)))}function validateFormat(){let format=fCxt.schema,fmtDef=self.formats[format];if(!fmtDef||fmtDef===!0)return;if(typeof fmtDef!="object"||fmtDef instanceof RegExp||typeof fmtDef.compare!="function")throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);let fmt=gen.scopeValue("formats",{key:format,ref:fmtDef,code:opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(format)}`:void 0});cxt.fail$data(compareCode(fmt))}function compareCode(fmt){return(0,codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`}},dependencies:["format"]};let formatLimitPlugin=ajv=>(ajv.addKeyword(exports.formatLimitDefinition),ajv);exports.default=formatLimitPlugin})),require_dist=__commonJSMin(((exports,module)=>{Object.defineProperty(exports,"__esModule",{value:!0});let formats_1=require_formats(),limit_1=require_limit(),codegen_1=require_codegen(),fullName=new codegen_1.Name("fullFormats"),fastName=new codegen_1.Name("fastFormats"),formatsPlugin=(ajv,opts={keywords:!0})=>{if(Array.isArray(opts))return addFormats2(ajv,opts,formats_1.fullFormats,fullName),ajv;let[formats,exportName]=opts.mode==="fast"?[formats_1.fastFormats,fastName]:[formats_1.fullFormats,fullName];return addFormats2(ajv,opts.formats||formats_1.formatNames,formats,exportName),opts.keywords&&(0,limit_1.default)(ajv),ajv};formatsPlugin.get=(name,mode="full")=>{let f=(mode==="fast"?formats_1.fastFormats:formats_1.fullFormats)[name];if(!f)throw new Error(`Unknown format "${name}"`);return f};function addFormats2(ajv,list,fs,exportName){var _a3,_b;(_a3=(_b=ajv.opts.code).formats)!==null&&_a3!==void 0||(_b.formats=(0,codegen_1._)`require("ajv-formats/dist/formats").${exportName}`);for(let f of list)ajv.addFormat(f,fs[f])}module.exports=exports=formatsPlugin,Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=formatsPlugin})),import_ajv=require_ajv(),import__2019=require__2019(),import__2020=require__2020(),import_dist=__toESM(require_dist(),1),addFormats=import_dist.default;AjvJsonSchemaValidator=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor(ajv){this._userAjv=ajv!==void 0,this._ajv=ajv}get ajv(){return this._ajv??=createDefaultAjvInstance(import__2020.Ajv2020)}_engineFor(schema2){if(this._userAjv)return this.ajv;let dialect=declaredDialect(schema2,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");return dialect==="2020-12"?this.ajv:dialect==="2019-09"?this._ajv2019??=createDefaultAjvInstance(import__2019.Ajv2019):this._ajvDraft7??=createDefaultAjvInstance(import_ajv.Ajv)}getValidator(schema2){let engine=this._engineFor(schema2),ajvValidator="$id"in schema2&&typeof schema2.$id=="string"?engine.getSchema(schema2.$id)??engine.compile(schema2):engine.compile(schema2);return input=>ajvValidator(input)?{valid:!0,data:input,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:engine.errorsText(ajvValidator.errors)}}},Ajv=import_ajv.Ajv}});import process3 from"process";var init_shimsNode=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/shimsNode.mjs"(){"use strict";init_ajvProvider_CEoC_sr()}});function completable(schema2,complete){return Object.defineProperty(schema2,COMPLETABLE_SYMBOL,{value:{complete},enumerable:!1,writable:!1,configurable:!1}),schema2}function isCompletable(schema2){return!!schema2&&typeof schema2=="object"&&COMPLETABLE_SYMBOL in schema2}function getCompleter(schema2){return schema2[COMPLETABLE_SYMBOL]?.complete}function armSseKeepAlive(intervalMs,onTick){if(!Number.isFinite(intervalMs)||intervalMs<1)return;let timer=setInterval(onTick,Math.min(intervalMs,MAX_TIMER_DELAY_MS));return timer.unref?.(),timer}function createServerNotifier(bus){return{toolsChanged:()=>bus.publish({kind:"tools_list_changed"}),promptsChanged:()=>bus.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>bus.publish({kind:"resources_list_changed"}),resourceUpdated:uri=>bus.publish({kind:"resource_updated",uri})}}function listenFilterAccepts(filter,event){switch(event.kind){case"tools_list_changed":return filter.toolsListChanged===!0;case"prompts_list_changed":return filter.promptsListChanged===!0;case"resources_list_changed":return filter.resourcesListChanged===!0;case"resource_updated":return filter.resourceSubscriptions!==void 0&&filter.resourceSubscriptions.includes(event.uri)}}function honoredSubset(requested,capabilities){let honored={},allow=bit=>capabilities===void 0||bit===!0;return requested.toolsListChanged===!0&&allow(capabilities?.tools?.listChanged)&&(honored.toolsListChanged=!0),requested.promptsListChanged===!0&&allow(capabilities?.prompts?.listChanged)&&(honored.promptsListChanged=!0),requested.resourcesListChanged===!0&&allow(capabilities?.resources?.listChanged)&&(honored.resourcesListChanged=!0),requested.resourceSubscriptions!==void 0&&requested.resourceSubscriptions.length>0&&allow(capabilities?.resources?.subscribe)&&(honored.resourceSubscriptions=[...requested.resourceSubscriptions]),honored}function serverEventToNotification(event){switch(event.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:event.uri}}}}function jsonRpcError(id,code,message){return Response.json({jsonrpc:"2.0",error:{code,message},id},{status:200})}function stampSubscriptionId(notification,subscriptionId){return{method:notification.method,params:{...notification.params,_meta:{...notification.params?._meta,[SUBSCRIPTION_ID_META_KEY]:subscriptionId}}}}function parseListenFilter(message){let outcome=codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen",message);return outcome.ok?outcome.value.params?.notifications:void 0}function createListenRouter(options){let{bus,onerror}=options,maxSubscriptions=options.maxSubscriptions??DEFAULT_MAX_SUBSCRIPTIONS,keepAliveMs=options.keepAliveMs??DEFAULT_SSE_KEEP_ALIVE_MS,open=new Set;function serve(message,signal,capabilities,serverInfo){if(open.size>=maxSubscriptions)return onerror?.(new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)),jsonRpcError(message.id,-32603,"Subscription limit reached");let filter=parseListenFilter(message);if(filter===void 0)return jsonRpcError(message.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let honored=honoredSubset(filter,capabilities),subscriptionId=message.id,encoder=new TextEncoder,controller,closed=!1,unsubscribe,keepAliveTimer,abortCleanup,writeFrame=frame=>{if(!closed)try{controller.enqueue(encoder.encode(frame))}catch(error3){onerror?.(error3 instanceof Error?error3:new Error(String(error3)))}},writeNotification=(method,params)=>{writeFrame(`event: message
64
+ deps: ${deps}}`};let def={keyword:"dependencies",type:"object",schemaType:"object",error:exports.error,code(cxt){let[propDeps,schDeps]=splitDependencies(cxt);validatePropertyDeps(cxt,propDeps),validateSchemaDeps(cxt,schDeps)}};function splitDependencies({schema:schema2}){let propertyDeps={},schemaDeps={};for(let key in schema2){if(key==="__proto__")continue;let deps=Array.isArray(schema2[key])?propertyDeps:schemaDeps;deps[key]=schema2[key]}return[propertyDeps,schemaDeps]}function validatePropertyDeps(cxt,propertyDeps=cxt.schema){let{gen,data,it}=cxt;if(Object.keys(propertyDeps).length===0)return;let missing=gen.let("missing");for(let prop in propertyDeps){let deps=propertyDeps[prop];if(deps.length===0)continue;let hasProperty=(0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties);cxt.setParams({property:prop,depsCount:deps.length,deps:deps.join(", ")}),it.allErrors?gen.if(hasProperty,()=>{for(let depProp of deps)(0,code_1.checkReportMissingProp)(cxt,depProp)}):(gen.if((0,codegen_1._)`${hasProperty} && (${(0,code_1.checkMissingProp)(cxt,deps,missing)})`),(0,code_1.reportMissingProp)(cxt,missing),gen.else())}}exports.validatePropertyDeps=validatePropertyDeps;function validateSchemaDeps(cxt,schemaDeps=cxt.schema){let{gen,data,keyword,it}=cxt,valid=gen.name("valid");for(let prop in schemaDeps)(0,util_1.alwaysValidSchema)(it,schemaDeps[prop])||(gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties),()=>{let schCxt=cxt.subschema({keyword,schemaProp:prop},valid);cxt.mergeValidEvaluated(schCxt,valid)},()=>gen.var(valid,!0)),cxt.ok(valid))}exports.validateSchemaDeps=validateSchemaDeps,exports.default=def})),require_propertyNames=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params})=>(0,codegen_1._)`{propertyName: ${params.propertyName}}`},code(cxt){let{gen,schema:schema2,data,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema2))return;let valid=gen.name("valid");gen.forIn("key",data,key=>{cxt.setParams({propertyName:key}),cxt.subschema({keyword:"propertyNames",data:key,dataTypes:["string"],propertyName:key,compositeRule:!0},valid),gen.if((0,codegen_1.not)(valid),()=>{cxt.error(!0),it.allErrors||gen.break()})}),cxt.ok(valid)}};exports.default=def})),require_additionalProperties=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let code_1=require_code(),codegen_1=require_codegen(),names_1=require_names(),util_1=require_util(),def={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params})=>(0,codegen_1._)`{additionalProperty: ${params.additionalProperty}}`},code(cxt){let{gen,schema:schema2,parentSchema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");let{allErrors,opts}=it;if(it.props=!0,opts.removeAdditional!=="all"&&(0,util_1.alwaysValidSchema)(it,schema2))return;let props=(0,code_1.allSchemaProperties)(parentSchema.properties),patProps=(0,code_1.allSchemaProperties)(parentSchema.patternProperties);checkAdditionalProperties(),cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function checkAdditionalProperties(){gen.forIn("key",data,key=>{!props.length&&!patProps.length?additionalPropertyCode(key):gen.if(isAdditional(key),()=>additionalPropertyCode(key))})}function isAdditional(key){let definedProp;if(props.length>8){let propsSchema=(0,util_1.schemaRefOrVal)(it,parentSchema.properties,"properties");definedProp=(0,code_1.isOwnProperty)(gen,propsSchema,key)}else props.length?definedProp=(0,codegen_1.or)(...props.map(p=>(0,codegen_1._)`${key} === ${p}`)):definedProp=codegen_1.nil;return patProps.length&&(definedProp=(0,codegen_1.or)(definedProp,...patProps.map(p=>(0,codegen_1._)`${(0,code_1.usePattern)(cxt,p)}.test(${key})`))),(0,codegen_1.not)(definedProp)}function deleteAdditional(key){gen.code((0,codegen_1._)`delete ${data}[${key}]`)}function additionalPropertyCode(key){if(opts.removeAdditional==="all"||opts.removeAdditional&&schema2===!1){deleteAdditional(key);return}if(schema2===!1){cxt.setParams({additionalProperty:key}),cxt.error(),allErrors||gen.break();return}if(typeof schema2=="object"&&!(0,util_1.alwaysValidSchema)(it,schema2)){let valid=gen.name("valid");opts.removeAdditional==="failing"?(applyAdditionalSchema(key,valid,!1),gen.if((0,codegen_1.not)(valid),()=>{cxt.reset(),deleteAdditional(key)})):(applyAdditionalSchema(key,valid),allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break()))}}function applyAdditionalSchema(key,valid,errors2){let subschema={keyword:"additionalProperties",dataProp:key,dataPropType:util_1.Type.Str};errors2===!1&&Object.assign(subschema,{compositeRule:!0,createErrors:!1,allErrors:!1}),cxt.subschema(subschema,valid)}}};exports.default=def})),require_properties=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let validate_1=require_validate(),code_1=require_code(),util_1=require_util(),additionalProperties_1=require_additionalProperties(),def={keyword:"properties",type:"object",schemaType:"object",code(cxt){let{gen,schema:schema2,parentSchema,data,it}=cxt;it.opts.removeAdditional==="all"&&parentSchema.additionalProperties===void 0&&additionalProperties_1.default.code(new validate_1.KeywordCxt(it,additionalProperties_1.default,"additionalProperties"));let allProps=(0,code_1.allSchemaProperties)(schema2);for(let prop of allProps)it.definedProperties.add(prop);it.opts.unevaluated&&allProps.length&&it.props!==!0&&(it.props=util_1.mergeEvaluated.props(gen,(0,util_1.toHash)(allProps),it.props));let properties=allProps.filter(p=>!(0,util_1.alwaysValidSchema)(it,schema2[p]));if(properties.length===0)return;let valid=gen.name("valid");for(let prop of properties)hasDefault(prop)?applyPropertySchema(prop):(gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties)),applyPropertySchema(prop),it.allErrors||gen.else().var(valid,!0),gen.endIf()),cxt.it.definedProperties.add(prop),cxt.ok(valid);function hasDefault(prop){return it.opts.useDefaults&&!it.compositeRule&&schema2[prop].default!==void 0}function applyPropertySchema(prop){cxt.subschema({keyword:"properties",schemaProp:prop,dataProp:prop},valid)}}};exports.default=def})),require_patternProperties=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let code_1=require_code(),codegen_1=require_codegen(),util_1=require_util(),util_2=require_util(),def={keyword:"patternProperties",type:"object",schemaType:"object",code(cxt){let{gen,schema:schema2,data,parentSchema,it}=cxt,{opts}=it,patterns=(0,code_1.allSchemaProperties)(schema2),alwaysValidPatterns=patterns.filter(p=>(0,util_1.alwaysValidSchema)(it,schema2[p]));if(patterns.length===0||alwaysValidPatterns.length===patterns.length&&(!it.opts.unevaluated||it.props===!0))return;let checkProperties=opts.strictSchema&&!opts.allowMatchingProperties&&parentSchema.properties,valid=gen.name("valid");it.props!==!0&&!(it.props instanceof codegen_1.Name)&&(it.props=(0,util_2.evaluatedPropsToName)(gen,it.props));let{props}=it;validatePatternProperties();function validatePatternProperties(){for(let pat of patterns)checkProperties&&checkMatchingProperties(pat),it.allErrors?validateProperties(pat):(gen.var(valid,!0),validateProperties(pat),gen.if(valid))}function checkMatchingProperties(pat){for(let prop in checkProperties)new RegExp(pat).test(prop)&&(0,util_1.checkStrictMode)(it,`property ${prop} matches pattern ${pat} (use allowMatchingProperties)`)}function validateProperties(pat){gen.forIn("key",data,key=>{gen.if((0,codegen_1._)`${(0,code_1.usePattern)(cxt,pat)}.test(${key})`,()=>{let alwaysValid=alwaysValidPatterns.includes(pat);alwaysValid||cxt.subschema({keyword:"patternProperties",schemaProp:pat,dataProp:key,dataPropType:util_2.Type.Str},valid),it.opts.unevaluated&&props!==!0?gen.assign((0,codegen_1._)`${props}[${key}]`,!0):!alwaysValid&&!it.allErrors&&gen.if((0,codegen_1.not)(valid),()=>gen.break())})})}}};exports.default=def})),require_not=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let util_1=require_util(),def={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(cxt){let{gen,schema:schema2,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema2)){cxt.fail();return}let valid=gen.name("valid");cxt.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},valid),cxt.failResult(valid,()=>cxt.reset(),()=>cxt.error())},error:{message:"must NOT be valid"}};exports.default=def})),require_anyOf=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let def={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:require_code().validateUnion,error:{message:"must match a schema in anyOf"}};exports.default=def})),require_oneOf=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params})=>(0,codegen_1._)`{passingSchemas: ${params.passing}}`},code(cxt){let{gen,schema:schema2,parentSchema,it}=cxt;if(!Array.isArray(schema2))throw new Error("ajv implementation error");if(it.opts.discriminator&&parentSchema.discriminator)return;let schArr=schema2,valid=gen.let("valid",!1),passing=gen.let("passing",null),schValid=gen.name("_valid");cxt.setParams({passing}),gen.block(validateOneOf),cxt.result(valid,()=>cxt.reset(),()=>cxt.error(!0));function validateOneOf(){schArr.forEach((sch,i)=>{let schCxt;(0,util_1.alwaysValidSchema)(it,sch)?gen.var(schValid,!0):schCxt=cxt.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},schValid),i>0&&gen.if((0,codegen_1._)`${schValid} && ${valid}`).assign(valid,!1).assign(passing,(0,codegen_1._)`[${passing}, ${i}]`).else(),gen.if(schValid,()=>{gen.assign(valid,!0),gen.assign(passing,i),schCxt&&cxt.mergeEvaluated(schCxt,codegen_1.Name)})})}}};exports.default=def})),require_allOf=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let util_1=require_util(),def={keyword:"allOf",schemaType:"array",code(cxt){let{gen,schema:schema2,it}=cxt;if(!Array.isArray(schema2))throw new Error("ajv implementation error");let valid=gen.name("valid");schema2.forEach((sch,i)=>{if((0,util_1.alwaysValidSchema)(it,sch))return;let schCxt=cxt.subschema({keyword:"allOf",schemaProp:i},valid);cxt.ok(valid),cxt.mergeEvaluated(schCxt)})}};exports.default=def})),require_if=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params})=>(0,codegen_1.str)`must match "${params.ifClause}" schema`,params:({params})=>(0,codegen_1._)`{failingKeyword: ${params.ifClause}}`},code(cxt){let{gen,parentSchema,it}=cxt;parentSchema.then===void 0&&parentSchema.else===void 0&&(0,util_1.checkStrictMode)(it,'"if" without "then" and "else" is ignored');let hasThen=hasSchema(it,"then"),hasElse=hasSchema(it,"else");if(!hasThen&&!hasElse)return;let valid=gen.let("valid",!0),schValid=gen.name("_valid");if(validateIf(),cxt.reset(),hasThen&&hasElse){let ifClause=gen.let("ifClause");cxt.setParams({ifClause}),gen.if(schValid,validateClause("then",ifClause),validateClause("else",ifClause))}else hasThen?gen.if(schValid,validateClause("then")):gen.if((0,codegen_1.not)(schValid),validateClause("else"));cxt.pass(valid,()=>cxt.error(!0));function validateIf(){let schCxt=cxt.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},schValid);cxt.mergeEvaluated(schCxt)}function validateClause(keyword,ifClause){return()=>{let schCxt=cxt.subschema({keyword},schValid);gen.assign(valid,schValid),cxt.mergeValidEvaluated(schCxt,valid),ifClause?gen.assign(ifClause,(0,codegen_1._)`${keyword}`):cxt.setParams({ifClause:keyword})}}}};function hasSchema(it,keyword){let schema2=it.schema[keyword];return schema2!==void 0&&!(0,util_1.alwaysValidSchema)(it,schema2)}exports.default=def})),require_thenElse=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let util_1=require_util(),def={keyword:["then","else"],schemaType:["object","boolean"],code({keyword,parentSchema,it}){parentSchema.if===void 0&&(0,util_1.checkStrictMode)(it,`"${keyword}" without "if" is ignored`)}};exports.default=def})),require_applicator$2=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let additionalItems_1=require_additionalItems(),prefixItems_1=require_prefixItems(),items_1=require_items(),items2020_1=require_items2020(),contains_1=require_contains(),dependencies_1=require_dependencies(),propertyNames_1=require_propertyNames(),additionalProperties_1=require_additionalProperties(),properties_1=require_properties(),patternProperties_1=require_patternProperties(),not_1=require_not(),anyOf_1=require_anyOf(),oneOf_1=require_oneOf(),allOf_1=require_allOf(),if_1=require_if(),thenElse_1=require_thenElse();function getApplicator(draft2020=!1){let applicator=[not_1.default,anyOf_1.default,oneOf_1.default,allOf_1.default,if_1.default,thenElse_1.default,propertyNames_1.default,additionalProperties_1.default,dependencies_1.default,properties_1.default,patternProperties_1.default];return draft2020?applicator.push(prefixItems_1.default,items2020_1.default):applicator.push(additionalItems_1.default,items_1.default),applicator.push(contains_1.default),applicator}exports.default=getApplicator})),require_format$2=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),def={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode})=>(0,codegen_1.str)`must match format "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{format: ${schemaCode}}`},code(cxt,ruleType){let{gen,data,$data,schema:schema2,schemaCode,it}=cxt,{opts,errSchemaPath,schemaEnv,self}=it;if(!opts.validateFormats)return;$data?validate$DataFormat():validateFormat();function validate$DataFormat(){let fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats}),fDef=gen.const("fDef",(0,codegen_1._)`${fmts}[${schemaCode}]`),fType=gen.let("fType"),format=gen.let("format");gen.if((0,codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,()=>gen.assign(fType,(0,codegen_1._)`${fDef}.type || "string"`).assign(format,(0,codegen_1._)`${fDef}.validate`),()=>gen.assign(fType,(0,codegen_1._)`"string"`).assign(format,fDef)),cxt.fail$data((0,codegen_1.or)(unknownFmt(),invalidFmt()));function unknownFmt(){return opts.strictSchema===!1?codegen_1.nil:(0,codegen_1._)`${schemaCode} && !${format}`}function invalidFmt(){let callFormat=schemaEnv.$async?(0,codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`:(0,codegen_1._)`${format}(${data})`,validData=(0,codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;return(0,codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`}}function validateFormat(){let formatDef=self.formats[schema2];if(!formatDef){unknownFormat();return}if(formatDef===!0)return;let[fmtType,format,fmtRef]=getFormat(formatDef);fmtType===ruleType&&cxt.pass(validCondition());function unknownFormat(){if(opts.strictSchema===!1){self.logger.warn(unknownMsg());return}throw new Error(unknownMsg());function unknownMsg(){return`unknown format "${schema2}" ignored in schema at path "${errSchemaPath}"`}}function getFormat(fmtDef){let code=fmtDef instanceof RegExp?(0,codegen_1.regexpCode)(fmtDef):opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(schema2)}`:void 0,fmt=gen.scopeValue("formats",{key:schema2,ref:fmtDef,code});return typeof fmtDef=="object"&&!(fmtDef instanceof RegExp)?[fmtDef.type||"string",fmtDef.validate,(0,codegen_1._)`${fmt}.validate`]:["string",fmtDef,fmt]}function validCondition(){if(typeof formatDef=="object"&&!(formatDef instanceof RegExp)&&formatDef.async){if(!schemaEnv.$async)throw new Error("async format in sync schema");return(0,codegen_1._)`await ${fmtRef}(${data})`}return typeof format=="function"?(0,codegen_1._)`${fmtRef}(${data})`:(0,codegen_1._)`${fmtRef}.test(${data})`}}}};exports.default=def})),require_format$1=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let format=[require_format$2().default];exports.default=format})),require_metadata=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.contentVocabulary=exports.metadataVocabulary=void 0,exports.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],exports.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]})),require_draft7=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let core_1=require_core$2(),validation_1=require_validation$2(),applicator_1=require_applicator$2(),format_1=require_format$1(),metadata_1=require_metadata(),draft7Vocabularies=[core_1.default,validation_1.default,(0,applicator_1.default)(),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary];exports.default=draft7Vocabularies})),require_types=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.DiscrError=void 0;var DiscrError;(function(DiscrError2){DiscrError2.Tag="tag",DiscrError2.Mapping="mapping"})(DiscrError||(exports.DiscrError=DiscrError={}))})),require_discriminator=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),types_1=require_types(),compile_1=require_compile(),ref_error_1=require_ref_error(),util_1=require_util(),def={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError,tagName}})=>discrError===types_1.DiscrError.Tag?`tag "${tagName}" must be string`:`value of tag "${tagName}" must be in oneOf`,params:({params:{discrError,tag,tagName}})=>(0,codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`},code(cxt){let{gen,data,schema:schema2,parentSchema,it}=cxt,{oneOf}=parentSchema;if(!it.opts.discriminator)throw new Error("discriminator: requires discriminator option");let tagName=schema2.propertyName;if(typeof tagName!="string")throw new Error("discriminator: requires propertyName");if(schema2.mapping)throw new Error("discriminator: mapping is not supported");if(!oneOf)throw new Error("discriminator: requires oneOf keyword");let valid=gen.let("valid",!1),tag=gen.const("tag",(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(tagName)}`);gen.if((0,codegen_1._)`typeof ${tag} == "string"`,()=>validateMapping(),()=>cxt.error(!1,{discrError:types_1.DiscrError.Tag,tag,tagName})),cxt.ok(valid);function validateMapping(){let mapping=getMapping();gen.if(!1);for(let tagValue in mapping)gen.elseIf((0,codegen_1._)`${tag} === ${tagValue}`),gen.assign(valid,applyTagSchema(mapping[tagValue]));gen.else(),cxt.error(!1,{discrError:types_1.DiscrError.Mapping,tag,tagName}),gen.endIf()}function applyTagSchema(schemaProp){let _valid=gen.name("valid"),schCxt=cxt.subschema({keyword:"oneOf",schemaProp},_valid);return cxt.mergeEvaluated(schCxt,codegen_1.Name),_valid}function getMapping(){var _a3;let oneOfMapping={},topRequired=hasRequired(parentSchema),tagRequired=!0;for(let i=0;i<oneOf.length;i++){let sch=oneOf[i];if(sch?.$ref&&!(0,util_1.schemaHasRulesButRef)(sch,it.self.RULES)){let ref=sch.$ref;if(sch=compile_1.resolveRef.call(it.self,it.schemaEnv.root,it.baseId,ref),sch instanceof compile_1.SchemaEnv&&(sch=sch.schema),sch===void 0)throw new ref_error_1.default(it.opts.uriResolver,it.baseId,ref)}let propSch=(_a3=sch?.properties)===null||_a3===void 0?void 0:_a3[tagName];if(typeof propSch!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);tagRequired=tagRequired&&(topRequired||hasRequired(sch)),addMappings(propSch,i)}if(!tagRequired)throw new Error(`discriminator: "${tagName}" must be required`);return oneOfMapping;function hasRequired({required:required2}){return Array.isArray(required2)&&required2.includes(tagName)}function addMappings(sch,i){if(sch.const)addMapping(sch.const,i);else if(sch.enum)for(let tagValue of sch.enum)addMapping(tagValue,i);else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)}function addMapping(tagValue,i){if(typeof tagValue!="string"||tagValue in oneOfMapping)throw new Error(`discriminator: "${tagName}" values must be unique strings`);oneOfMapping[tagValue]=i}}}};exports.default=def})),require_json_schema_draft_07=__commonJSMin(((exports,module)=>{module.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}})),require_ajv=__commonJSMin(((exports,module)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv=void 0;let core_1=require_core$3(),draft7_1=require_draft7(),discriminator_1=require_discriminator(),draft7MetaSchema=require_json_schema_draft_07(),META_SUPPORT_DATA=["/properties"],META_SCHEMA_ID="http://json-schema.org/draft-07/schema";var Ajv2=class extends core_1.default{_addVocabularies(){super._addVocabularies(),draft7_1.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let metaSchema=this.opts.$data?this.$dataMetaSchema(draft7MetaSchema,META_SUPPORT_DATA):draft7MetaSchema;this.addMetaSchema(metaSchema,META_SCHEMA_ID,!1),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv=Ajv2,module.exports=exports=Ajv2,module.exports.Ajv=Ajv2,Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=Ajv2;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})})),require_dynamicAnchor=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.dynamicAnchor=void 0;let codegen_1=require_codegen(),names_1=require_names(),compile_1=require_compile(),ref_1=require_ref(),def={keyword:"$dynamicAnchor",schemaType:"string",code:cxt=>dynamicAnchor(cxt,cxt.schema)};function dynamicAnchor(cxt,anchor2){let{gen,it}=cxt;it.schemaEnv.root.dynamicAnchors[anchor2]=!0;let v=(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor2)}`,validate2=it.errSchemaPath==="#"?it.validateName:_getValidate(cxt);gen.if((0,codegen_1._)`!${v}`,()=>gen.assign(v,validate2))}exports.dynamicAnchor=dynamicAnchor;function _getValidate(cxt){let{schemaEnv,schema:schema2,self}=cxt.it,{root,baseId,localRefs,meta:meta2}=schemaEnv.root,{schemaId}=self.opts,sch=new compile_1.SchemaEnv({schema:schema2,schemaId,root,baseId,localRefs,meta:meta2});return compile_1.compileSchema.call(self,sch),(0,ref_1.getValidate)(cxt,sch)}exports.default=def})),require_dynamicRef=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.dynamicRef=void 0;let codegen_1=require_codegen(),names_1=require_names(),ref_1=require_ref(),def={keyword:"$dynamicRef",schemaType:"string",code:cxt=>dynamicRef(cxt,cxt.schema)};function dynamicRef(cxt,ref){let{gen,keyword,it}=cxt;if(ref[0]!=="#")throw new Error(`"${keyword}" only supports hash fragment reference`);let anchor2=ref.slice(1);if(it.allErrors)_dynamicRef();else{let valid=gen.let("valid",!1);_dynamicRef(valid),cxt.ok(valid)}function _dynamicRef(valid){if(it.schemaEnv.root.dynamicAnchors[anchor2]){let v=gen.let("_v",(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor2)}`);gen.if(v,_callRef(v,valid),_callRef(it.validateName,valid))}else _callRef(it.validateName,valid)()}function _callRef(validate2,valid){return valid?()=>gen.block(()=>{(0,ref_1.callRef)(cxt,validate2),gen.let(valid,!0)}):()=>(0,ref_1.callRef)(cxt,validate2)}}exports.dynamicRef=dynamicRef,exports.default=def})),require_recursiveAnchor=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dynamicAnchor_1=require_dynamicAnchor(),util_1=require_util(),def={keyword:"$recursiveAnchor",schemaType:"boolean",code(cxt){cxt.schema?(0,dynamicAnchor_1.dynamicAnchor)(cxt,""):(0,util_1.checkStrictMode)(cxt.it,"$recursiveAnchor: false is ignored")}};exports.default=def})),require_recursiveRef=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dynamicRef_1=require_dynamicRef(),def={keyword:"$recursiveRef",schemaType:"string",code:cxt=>(0,dynamicRef_1.dynamicRef)(cxt,cxt.schema)};exports.default=def})),require_dynamic=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dynamicAnchor_1=require_dynamicAnchor(),dynamicRef_1=require_dynamicRef(),recursiveAnchor_1=require_recursiveAnchor(),recursiveRef_1=require_recursiveRef(),dynamic=[dynamicAnchor_1.default,dynamicRef_1.default,recursiveAnchor_1.default,recursiveRef_1.default];exports.default=dynamic})),require_dependentRequired=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dependencies_1=require_dependencies(),def={keyword:"dependentRequired",type:"object",schemaType:"object",error:dependencies_1.error,code:cxt=>(0,dependencies_1.validatePropertyDeps)(cxt)};exports.default=def})),require_dependentSchemas=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dependencies_1=require_dependencies(),def={keyword:"dependentSchemas",type:"object",schemaType:"object",code:cxt=>(0,dependencies_1.validateSchemaDeps)(cxt)};exports.default=def})),require_limitContains=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let util_1=require_util(),def={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword,parentSchema,it}){parentSchema.contains===void 0&&(0,util_1.checkStrictMode)(it,`"${keyword}" without "contains" is ignored`)}};exports.default=def})),require_next=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let dependentRequired_1=require_dependentRequired(),dependentSchemas_1=require_dependentSchemas(),limitContains_1=require_limitContains(),next=[dependentRequired_1.default,dependentSchemas_1.default,limitContains_1.default];exports.default=next})),require_unevaluatedProperties=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),names_1=require_names(),def={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params})=>(0,codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}`},code(cxt){let{gen,schema:schema2,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");let{allErrors,props}=it;props instanceof codegen_1.Name?gen.if((0,codegen_1._)`${props} !== true`,()=>gen.forIn("key",data,key=>gen.if(unevaluatedDynamic(props,key),()=>unevaluatedPropCode(key)))):props!==!0&&gen.forIn("key",data,key=>props===void 0?unevaluatedPropCode(key):gen.if(unevaluatedStatic(props,key),()=>unevaluatedPropCode(key))),it.props=!0,cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function unevaluatedPropCode(key){if(schema2===!1){cxt.setParams({unevaluatedProperty:key}),cxt.error(),allErrors||gen.break();return}if(!(0,util_1.alwaysValidSchema)(it,schema2)){let valid=gen.name("valid");cxt.subschema({keyword:"unevaluatedProperties",dataProp:key,dataPropType:util_1.Type.Str},valid),allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break())}}function unevaluatedDynamic(evaluatedProps,key){return(0,codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`}function unevaluatedStatic(evaluatedProps,key){let ps=[];for(let p in evaluatedProps)evaluatedProps[p]===!0&&ps.push((0,codegen_1._)`${key} !== ${p}`);return(0,codegen_1.and)(...ps)}}};exports.default=def})),require_unevaluatedItems=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},code(cxt){let{gen,schema:schema2,data,it}=cxt,items=it.items||0;if(items===!0)return;let len=gen.const("len",(0,codegen_1._)`${data}.length`);if(schema2===!1)cxt.setParams({len:items}),cxt.fail((0,codegen_1._)`${len} > ${items}`);else if(typeof schema2=="object"&&!(0,util_1.alwaysValidSchema)(it,schema2)){let valid=gen.var("valid",(0,codegen_1._)`${len} <= ${items}`);gen.if((0,codegen_1.not)(valid),()=>validateItems(valid,items)),cxt.ok(valid)}it.items=!0;function validateItems(valid,from){gen.forRange("i",from,len,i=>{cxt.subschema({keyword:"unevaluatedItems",dataProp:i,dataPropType:util_1.Type.Num},valid),it.allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break())})}}};exports.default=def})),require_unevaluated$1=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let unevaluatedProperties_1=require_unevaluatedProperties(),unevaluatedItems_1=require_unevaluatedItems(),unevaluated=[unevaluatedProperties_1.default,unevaluatedItems_1.default];exports.default=unevaluated})),require_schema$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/schema",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format"},{$ref:"meta/content"}],type:["object","boolean"],properties:{definitions:{$comment:"While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},dependencies:{$comment:'"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"',type:"object",additionalProperties:{anyOf:[{$recursiveRef:"#"},{$ref:"meta/validation#/$defs/stringArray"}]}}}}})),require_applicator$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{additionalItems:{$recursiveRef:"#"},unevaluatedItems:{$recursiveRef:"#"},items:{anyOf:[{$recursiveRef:"#"},{$ref:"#/$defs/schemaArray"}]},contains:{$recursiveRef:"#"},additionalProperties:{$recursiveRef:"#"},unevaluatedProperties:{$recursiveRef:"#"},properties:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$recursiveRef:"#"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$recursiveRef:"#"}},propertyNames:{$recursiveRef:"#"},if:{$recursiveRef:"#"},then:{$recursiveRef:"#"},else:{$recursiveRef:"#"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$recursiveRef:"#"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$recursiveRef:"#"}}}}})),require_content$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/content",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentMediaType:{type:"string"},contentEncoding:{type:"string"},contentSchema:{$recursiveRef:"#"}}}})),require_core$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/core",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{type:"string",format:"uri"},$anchor:{type:"string",pattern:"^[A-Za-z][-A-Za-z0-9.:_]*$"},$ref:{type:"string",format:"uri-reference"},$recursiveRef:{type:"string",format:"uri-reference"},$recursiveAnchor:{type:"boolean",default:!1},$vocabulary:{type:"object",propertyNames:{type:"string",format:"uri"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}}}}})),require_format=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/format",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:"Format vocabulary meta-schema",type:["object","boolean"],properties:{format:{type:"string"}}}})),require_meta_data$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),require_validation$1=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/validation",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}},const:!0,enum:{type:"array",items:!0},type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),require_json_schema_2019_09=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let metaSchema=require_schema$1(),applicator=require_applicator$1(),content=require_content$1(),core=require_core$1(),format=require_format(),metadata=require_meta_data$1(),validation=require_validation$1(),META_SUPPORT_DATA=["/properties"];function addMetaSchema2019($data){return[metaSchema,applicator,content,core,with$data(this,format),metadata,with$data(this,validation)].forEach(sch=>this.addMetaSchema(sch,void 0,!1)),this;function with$data(ajv,sch){return $data?ajv.$dataMetaSchema(sch,META_SUPPORT_DATA):sch}}exports.default=addMetaSchema2019})),require__2019=__commonJSMin(((exports,module)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv2019=void 0;let core_1=require_core$3(),draft7_1=require_draft7(),dynamic_1=require_dynamic(),next_1=require_next(),unevaluated_1=require_unevaluated$1(),discriminator_1=require_discriminator(),json_schema_2019_09_1=require_json_schema_2019_09(),META_SCHEMA_ID="https://json-schema.org/draft/2019-09/schema";var Ajv2019=class extends core_1.default{constructor(opts={}){super({...opts,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(dynamic_1.default),draft7_1.default.forEach(v=>this.addVocabulary(v)),this.addVocabulary(next_1.default),this.addVocabulary(unevaluated_1.default),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data,meta:meta2}=this.opts;meta2&&(json_schema_2019_09_1.default.call(this,$data),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv2019=Ajv2019,module.exports=exports=Ajv2019,module.exports.Ajv2019=Ajv2019,Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=Ajv2019;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})})),require_draft2020=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let core_1=require_core$2(),validation_1=require_validation$2(),applicator_1=require_applicator$2(),dynamic_1=require_dynamic(),next_1=require_next(),unevaluated_1=require_unevaluated$1(),format_1=require_format$1(),metadata_1=require_metadata(),draft2020Vocabularies=[dynamic_1.default,core_1.default,validation_1.default,(0,applicator_1.default)(!0),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary,next_1.default,unevaluated_1.default];exports.default=draft2020Vocabularies})),require_schema=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}})),require_applicator=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}})),require_unevaluated=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}})),require_content=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}})),require_core=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}})),require_format_annotation=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}})),require_meta_data=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),require_validation=__commonJSMin(((exports,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),require_json_schema_2020_12=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let metaSchema=require_schema(),applicator=require_applicator(),unevaluated=require_unevaluated(),content=require_content(),core=require_core(),format=require_format_annotation(),metadata=require_meta_data(),validation=require_validation(),META_SUPPORT_DATA=["/properties"];function addMetaSchema2020($data){return[metaSchema,applicator,unevaluated,content,core,with$data(this,format),metadata,with$data(this,validation)].forEach(sch=>this.addMetaSchema(sch,void 0,!1)),this;function with$data(ajv,sch){return $data?ajv.$dataMetaSchema(sch,META_SUPPORT_DATA):sch}}exports.default=addMetaSchema2020})),require__2020=__commonJSMin(((exports,module)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv2020=void 0;let core_1=require_core$3(),draft2020_1=require_draft2020(),discriminator_1=require_discriminator(),json_schema_2020_12_1=require_json_schema_2020_12(),META_SCHEMA_ID="https://json-schema.org/draft/2020-12/schema";var Ajv2020=class extends core_1.default{constructor(opts={}){super({...opts,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),draft2020_1.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data,meta:meta2}=this.opts;meta2&&(json_schema_2020_12_1.default.call(this,$data),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv2020=Ajv2020,module.exports=exports=Ajv2020,module.exports.Ajv2020=Ajv2020,Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=Ajv2020;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})})),require_formats=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatNames=exports.fastFormats=exports.fullFormats=void 0;function fmtDef(validate2,compare){return{validate:validate2,compare}}exports.fullFormats={date:fmtDef(date4,compareDate),time:fmtDef(getTime(!0),compareTime),"date-time":fmtDef(getDateTime(!0),compareDateTime),"iso-time":fmtDef(getTime(),compareIsoTime),"iso-date-time":fmtDef(getDateTime(),compareIsoDateTime),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:!0,binary:!0},exports.fastFormats={...exports.fullFormats,date:fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,compareDate),time:fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareTime),"date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareDateTime),"iso-time":fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoTime),"iso-date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoDateTime),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},exports.formatNames=Object.keys(exports.fullFormats);function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}let DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date4(str){let matches=DATE.exec(str);if(!matches)return!1;let year=+matches[1],month=+matches[2],day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}function compareDate(d1,d2){if(d1&&d2)return d1>d2?1:d1<d2?-1:0}let TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function(str){let matches=TIME.exec(str);if(!matches)return!1;let hr=+matches[1],min=+matches[2],sec=+matches[3],tz=matches[4],tzSign=matches[5]==="-"?-1:1,tzH=+(matches[6]||0),tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return!1;if(hr<=23&&min<=59&&sec<60)return!0;let utcMin=min-tzM*tzSign,utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}function compareTime(s1,s2){if(!(s1&&s2))return;let t1=new Date("2020-01-01T"+s1).valueOf(),t2=new Date("2020-01-01T"+s2).valueOf();if(t1&&t2)return t1-t2}function compareIsoTime(t1,t2){if(!(t1&&t2))return;let a1=TIME.exec(t1),a2=TIME.exec(t2);if(a1&&a2)return t1=a1[1]+a1[2]+a1[3],t2=a2[1]+a2[2]+a2[3],t1>t2?1:t1<t2?-1:0}let DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){let time3=getTime(strictTimeZone);return function(str){let dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date4(dateTime[0])&&time3(dateTime[1])}}function compareDateTime(dt1,dt2){if(!(dt1&&dt2))return;let d1=new Date(dt1).valueOf(),d2=new Date(dt2).valueOf();if(d1&&d2)return d1-d2}function compareIsoDateTime(dt1,dt2){if(!(dt1&&dt2))return;let[d1,t1]=dt1.split(DATE_TIME_SEPARATOR),[d2,t2]=dt2.split(DATE_TIME_SEPARATOR),res=compareDate(d1,d2);if(res!==void 0)return res||compareTime(t1,t2)}let NOT_URI_FRAGMENT=/\/|:/,URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}let BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str){return BYTE.lastIndex=0,BYTE.test(str)}let MIN_INT32=-(2**31),MAX_INT32=2**31-1;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return!0}let Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return!1;try{return new RegExp(str),!0}catch{return!1}}})),require_limit=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatLimitDefinition=void 0;let ajv_1=require_ajv(),codegen_1=require_codegen(),ops=codegen_1.operators,KWDs={formatMaximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},formatMinimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},formatExclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},formatExclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}},error3={message:({keyword,schemaCode})=>(0,codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`};exports.formatLimitDefinition={keyword:Object.keys(KWDs),type:"string",schemaType:"string",$data:!0,error:error3,code(cxt){let{gen,data,schemaCode,keyword,it}=cxt,{opts,self}=it;if(!opts.validateFormats)return;let fCxt=new ajv_1.KeywordCxt(it,self.RULES.all.format.definition,"format");fCxt.$data?validate$DataFormat():validateFormat();function validate$DataFormat(){let fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats}),fmt=gen.const("fmt",(0,codegen_1._)`${fmts}[${fCxt.schemaCode}]`);cxt.fail$data((0,codegen_1.or)((0,codegen_1._)`typeof ${fmt} != "object"`,(0,codegen_1._)`${fmt} instanceof RegExp`,(0,codegen_1._)`typeof ${fmt}.compare != "function"`,compareCode(fmt)))}function validateFormat(){let format=fCxt.schema,fmtDef=self.formats[format];if(!fmtDef||fmtDef===!0)return;if(typeof fmtDef!="object"||fmtDef instanceof RegExp||typeof fmtDef.compare!="function")throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);let fmt=gen.scopeValue("formats",{key:format,ref:fmtDef,code:opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(format)}`:void 0});cxt.fail$data(compareCode(fmt))}function compareCode(fmt){return(0,codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`}},dependencies:["format"]};let formatLimitPlugin=ajv=>(ajv.addKeyword(exports.formatLimitDefinition),ajv);exports.default=formatLimitPlugin})),require_dist=__commonJSMin(((exports,module)=>{Object.defineProperty(exports,"__esModule",{value:!0});let formats_1=require_formats(),limit_1=require_limit(),codegen_1=require_codegen(),fullName=new codegen_1.Name("fullFormats"),fastName=new codegen_1.Name("fastFormats"),formatsPlugin=(ajv,opts={keywords:!0})=>{if(Array.isArray(opts))return addFormats2(ajv,opts,formats_1.fullFormats,fullName),ajv;let[formats,exportName]=opts.mode==="fast"?[formats_1.fastFormats,fastName]:[formats_1.fullFormats,fullName];return addFormats2(ajv,opts.formats||formats_1.formatNames,formats,exportName),opts.keywords&&(0,limit_1.default)(ajv),ajv};formatsPlugin.get=(name,mode="full")=>{let f=(mode==="fast"?formats_1.fastFormats:formats_1.fullFormats)[name];if(!f)throw new Error(`Unknown format "${name}"`);return f};function addFormats2(ajv,list,fs,exportName){var _a3,_b;(_a3=(_b=ajv.opts.code).formats)!==null&&_a3!==void 0||(_b.formats=(0,codegen_1._)`require("ajv-formats/dist/formats").${exportName}`);for(let f of list)ajv.addFormat(f,fs[f])}module.exports=exports=formatsPlugin,Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=formatsPlugin})),import_ajv=require_ajv(),import__2019=require__2019(),import__2020=require__2020(),import_dist=__toESM(require_dist(),1),addFormats=import_dist.default;AjvJsonSchemaValidator=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor(ajv){this._userAjv=ajv!==void 0,this._ajv=ajv}get ajv(){return this._ajv??=createDefaultAjvInstance(import__2020.Ajv2020)}_engineFor(schema2){if(this._userAjv)return this.ajv;let dialect=declaredDialect(schema2,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");return dialect==="2020-12"?this.ajv:dialect==="2019-09"?this._ajv2019??=createDefaultAjvInstance(import__2019.Ajv2019):this._ajvDraft7??=createDefaultAjvInstance(import_ajv.Ajv)}getValidator(schema2){let engine=this._engineFor(schema2),ajvValidator="$id"in schema2&&typeof schema2.$id=="string"?engine.getSchema(schema2.$id)??engine.compile(schema2):engine.compile(schema2);return input=>ajvValidator(input)?{valid:!0,data:input,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:engine.errorsText(ajvValidator.errors)}}},Ajv=import_ajv.Ajv}});import process2 from"process";var init_shimsNode=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/shimsNode.mjs"(){"use strict";init_ajvProvider_CEoC_sr()}});function completable(schema2,complete){return Object.defineProperty(schema2,COMPLETABLE_SYMBOL,{value:{complete},enumerable:!1,writable:!1,configurable:!1}),schema2}function isCompletable(schema2){return!!schema2&&typeof schema2=="object"&&COMPLETABLE_SYMBOL in schema2}function getCompleter(schema2){return schema2[COMPLETABLE_SYMBOL]?.complete}function armSseKeepAlive(intervalMs,onTick){if(!Number.isFinite(intervalMs)||intervalMs<1)return;let timer=setInterval(onTick,Math.min(intervalMs,MAX_TIMER_DELAY_MS));return timer.unref?.(),timer}function createServerNotifier(bus){return{toolsChanged:()=>bus.publish({kind:"tools_list_changed"}),promptsChanged:()=>bus.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>bus.publish({kind:"resources_list_changed"}),resourceUpdated:uri=>bus.publish({kind:"resource_updated",uri})}}function listenFilterAccepts(filter,event){switch(event.kind){case"tools_list_changed":return filter.toolsListChanged===!0;case"prompts_list_changed":return filter.promptsListChanged===!0;case"resources_list_changed":return filter.resourcesListChanged===!0;case"resource_updated":return filter.resourceSubscriptions!==void 0&&filter.resourceSubscriptions.includes(event.uri)}}function honoredSubset(requested,capabilities){let honored={},allow=bit=>capabilities===void 0||bit===!0;return requested.toolsListChanged===!0&&allow(capabilities?.tools?.listChanged)&&(honored.toolsListChanged=!0),requested.promptsListChanged===!0&&allow(capabilities?.prompts?.listChanged)&&(honored.promptsListChanged=!0),requested.resourcesListChanged===!0&&allow(capabilities?.resources?.listChanged)&&(honored.resourcesListChanged=!0),requested.resourceSubscriptions!==void 0&&requested.resourceSubscriptions.length>0&&allow(capabilities?.resources?.subscribe)&&(honored.resourceSubscriptions=[...requested.resourceSubscriptions]),honored}function serverEventToNotification(event){switch(event.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:event.uri}}}}function jsonRpcError(id,code,message){return Response.json({jsonrpc:"2.0",error:{code,message},id},{status:200})}function stampSubscriptionId(notification,subscriptionId){return{method:notification.method,params:{...notification.params,_meta:{...notification.params?._meta,[SUBSCRIPTION_ID_META_KEY]:subscriptionId}}}}function parseListenFilter(message){let outcome=codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen",message);return outcome.ok?outcome.value.params?.notifications:void 0}function createListenRouter(options){let{bus,onerror}=options,maxSubscriptions=options.maxSubscriptions??DEFAULT_MAX_SUBSCRIPTIONS,keepAliveMs=options.keepAliveMs??DEFAULT_SSE_KEEP_ALIVE_MS,open2=new Set;function serve(message,signal,capabilities,serverInfo){if(open2.size>=maxSubscriptions)return onerror?.(new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)),jsonRpcError(message.id,-32603,"Subscription limit reached");let filter=parseListenFilter(message);if(filter===void 0)return jsonRpcError(message.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let honored=honoredSubset(filter,capabilities),subscriptionId=message.id,encoder=new TextEncoder,controller,closed=!1,unsubscribe,keepAliveTimer,abortCleanup,writeFrame=frame=>{if(!closed)try{controller.enqueue(encoder.encode(frame))}catch(error3){onerror?.(error3 instanceof Error?error3:new Error(String(error3)))}},writeNotification=(method,params)=>{writeFrame(`event: message
72
65
  data: ${JSON.stringify({jsonrpc:"2.0",method,params})}
73
66
 
74
67
  `)},teardown=graceful=>{if(!closed){graceful&&writeFrame(`event: message
75
68
  data: ${JSON.stringify({jsonrpc:"2.0",id:subscriptionId,result:{resultType:"complete",_meta:{[SUBSCRIPTION_ID_META_KEY]:subscriptionId,[SERVER_INFO_META_KEY]:serverInfo}}})}
76
69
 
77
- `),closed=!0;try{unsubscribe?.()}catch(error3){onerror?.(error3 instanceof Error?error3:new Error(String(error3)))}keepAliveTimer!==void 0&&clearInterval(keepAliveTimer),abortCleanup?.(),open.delete(teardown);try{controller.close()}catch{}}},readable=new ReadableStream({start(streamController){controller=streamController;let ack=stampSubscriptionId({method:"notifications/subscriptions/acknowledged",params:{notifications:honored}},subscriptionId);if(writeNotification(ack.method,ack.params),Object.keys(honored).length===0){teardown(!0);return}unsubscribe=bus.subscribe(event=>{if(closed||!listenFilterAccepts(honored,event))return;let note=stampSubscriptionId(serverEventToNotification(event),subscriptionId);writeNotification(note.method,note.params)}),keepAliveTimer=armSseKeepAlive(keepAliveMs,()=>writeFrame(`: keepalive
70
+ `),closed=!0;try{unsubscribe?.()}catch(error3){onerror?.(error3 instanceof Error?error3:new Error(String(error3)))}keepAliveTimer!==void 0&&clearInterval(keepAliveTimer),abortCleanup?.(),open2.delete(teardown);try{controller.close()}catch{}}},readable=new ReadableStream({start(streamController){controller=streamController;let ack=stampSubscriptionId({method:"notifications/subscriptions/acknowledged",params:{notifications:honored}},subscriptionId);if(writeNotification(ack.method,ack.params),Object.keys(honored).length===0){teardown(!0);return}unsubscribe=bus.subscribe(event=>{if(closed||!listenFilterAccepts(honored,event))return;let note=stampSubscriptionId(serverEventToNotification(event),subscriptionId);writeNotification(note.method,note.params)}),keepAliveTimer=armSseKeepAlive(keepAliveMs,()=>writeFrame(`: keepalive
78
71
 
79
- `)),open.add(teardown)},cancel(){teardown(!1)}});if(signal!==void 0)if(signal.aborted)teardown(!1);else{let onAbort=()=>teardown(!1);signal.addEventListener("abort",onAbort,{once:!0}),abortCleanup=()=>signal.removeEventListener("abort",onAbort)}return new Response(readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}return{serve,closeAll(){for(let teardown of open)teardown(!0)},get openCount(){return open.size}}}function comparableResource(value){let text2=String(value),hash=text2.indexOf("#");return(hash===-1?text2:text2.slice(0,hash)).replace(/\/$/,"")}function sameResource(reported,expected){return reported?comparableResource(reported)===comparableResource(expected):!1}function headerQuotedValue(value){return value.replaceAll(/[\\"]/g,String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g," ")}function buildWwwAuthenticateHeader(errorCode,description,requiredScopes,resourceMetadataUrl){let header=`Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`;return requiredScopes.length>0&&(header+=`, scope="${headerQuotedValue(requiredScopes.join(" "))}"`),resourceMetadataUrl&&(header+=`, resource_metadata="${headerQuotedValue(resourceMetadataUrl)}"`),header}async function verifyBearerToken(authorizationHeader,options){let{verifier,requiredScopes=[],expectedResource}=options;if(!authorizationHeader)throw new OAuthError(OAuthErrorCode.InvalidToken,"Missing Authorization header");let[type,token]=authorizationHeader.split(" ");if(type?.toLowerCase()!=="bearer"||!token)throw new OAuthError(OAuthErrorCode.InvalidToken,"Invalid Authorization header format, expected 'Bearer TOKEN'");let authInfo=await verifier.verifyAccessToken(token);if(expectedResource!==void 0&&!sameResource(authInfo.resource,expectedResource))throw new OAuthError(OAuthErrorCode.InvalidToken,"Token was not issued for this resource");if(requiredScopes.length>0&&!requiredScopes.every(scope=>authInfo.scopes.includes(scope)))throw new OAuthError(OAuthErrorCode.InsufficientScope,"Insufficient scope");if(typeof authInfo.expiresAt!="number"||Number.isNaN(authInfo.expiresAt))throw new OAuthError(OAuthErrorCode.InvalidToken,"Token has no expiration time");if(authInfo.expiresAt<Date.now()/1e3)throw new OAuthError(OAuthErrorCode.InvalidToken,"Token has expired");return options.resourceMetadataUrl!==void 0&&authInfo.resourceMetadataUrl===void 0?{...authInfo,resourceMetadataUrl:options.resourceMetadataUrl}:authInfo}function bearerAuthChallengeResponse(error3,options){let{requiredScopes=[],resourceMetadataUrl}=options??{};if(!(error3 instanceof OAuthError)){let serverError=new OAuthError(OAuthErrorCode.ServerError,"Internal Server Error");return Response.json(serverError.toResponseObject(),{status:500})}switch(error3.code){case OAuthErrorCode.InvalidToken:{let challenge=buildWwwAuthenticateHeader(error3.code,error3.message,requiredScopes,resourceMetadataUrl);return Response.json(error3.toResponseObject(),{status:401,headers:{"WWW-Authenticate":challenge}})}case OAuthErrorCode.InsufficientScope:{let challenge=buildWwwAuthenticateHeader(error3.code,error3.message,requiredScopes,resourceMetadataUrl);return Response.json(error3.toResponseObject(),{status:403,headers:{"WWW-Authenticate":challenge}})}case OAuthErrorCode.ServerError:return Response.json(error3.toResponseObject(),{status:500});default:return Response.json(error3.toResponseObject(),{status:400})}}function checkIssuerUrl(issuer,allowInsecure){if(issuer.protocol!=="https:"&&issuer.hostname!=="localhost"&&issuer.hostname!=="127.0.0.1"&&!allowInsecure)throw new Error("Issuer URL must be HTTPS");if(issuer.hash)throw new Error(`Issuer URL must not have a fragment: ${issuer}`);if(issuer.search)throw new Error(`Issuer URL must not have a query string: ${issuer}`)}function buildOAuthProtectedResourceMetadata(options){return checkIssuerUrl(new URL(options.oauthMetadata.issuer),options.dangerouslyAllowInsecureIssuerUrl),{resource:options.resourceServerUrl.href,authorization_servers:[options.oauthMetadata.issuer],scopes_supported:options.scopesSupported,resource_name:options.resourceName,resource_documentation:options.serviceDocumentationUrl?.href}}function getOAuthProtectedResourceMetadataUrl(serverUrl){let metadataUrl=new URL(serverUrl);return metadataUrl.pathname=protectedResourceMetadataPath(serverUrl),metadataUrl.hash="",metadataUrl.href}function protectedResourceMetadataPath(resourceServerUrl){let rsPath=stripTrailingSlash(resourceServerUrl.pathname);return`/.well-known/oauth-protected-resource${rsPath==="/"?"":rsPath}`}function stripTrailingSlash(path){return path.length>1&&path.endsWith("/")?path.slice(0,-1):path}function metadataDocumentResponse(request,metadata){if(request.method==="OPTIONS"){let requestedHeaders=request.headers.get("access-control-request-headers");return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":ALLOWED_METHODS,...requestedHeaders===null?{}:{"Access-Control-Allow-Headers":requestedHeaders,Vary:"Access-Control-Request-Headers"}}})}if(request.method!=="GET"&&request.method!=="HEAD"){let error3=new OAuthError(OAuthErrorCode.MethodNotAllowed,`The method ${request.method} is not allowed for this endpoint`);return Response.json(error3.toResponseObject(),{status:405,headers:{Allow:ALLOWED_METHODS,"Access-Control-Allow-Origin":"*"}})}let response=Response.json(metadata,{headers:{"Access-Control-Allow-Origin":"*"}});return request.method==="HEAD"?new Response(null,{status:response.status,headers:response.headers}):response}function oauthMetadataResponse(request,options){let requestPath=stripTrailingSlash(new URL(request.url).pathname);if(requestPath===protectedResourceMetadataPath(options.resourceServerUrl))return metadataDocumentResponse(request,buildOAuthProtectedResourceMetadata(options));if(requestPath==="/.well-known/oauth-authorization-server")return buildOAuthProtectedResourceMetadata(options),metadataDocumentResponse(request,options.oauthMetadata)}function supportsScopeChallengeResolver(transport){return typeof transport=="object"&&transport!==null&&"setScopeChallengeResolver"in transport&&typeof transport.setScopeChallengeResolver=="function"}function assertScope(scope,location){if(typeof scope!="string"||!/^[\u0021\u0023-\u005B\u005D-\u007E]+$/.test(scope))throw new TypeError(`${location} must satisfy the OAuth scope-token grammar`)}function validateScopeChallenge(challenge){if(challenge===null||typeof challenge!="object"||!Array.isArray(challenge.scopes)||challenge.scopes.length===0)throw new TypeError("scope challenge must contain at least one scope");for(let[index,scope]of challenge.scopes.entries())assertScope(scope,`scope challenge scopes[${index}]`);if(challenge.errorDescription!==void 0&&typeof challenge.errorDescription!="string")throw new TypeError("scope challenge errorDescription must be a string");if(challenge.errorDescription!==void 0&&!/^[\u0020-\u0021\u0023-\u005B\u005D-\u007E]+$/.test(challenge.errorDescription))throw new TypeError("scope challenge errorDescription must satisfy the RFC 6750 error-description grammar");return challenge}async function findScopeChallenge(requests,authInfo,resolve){for(let request of requests){let challenge=await resolve({request,...authInfo!==void 0&&{authInfo}});if(challenge!==void 0)return validateScopeChallenge(challenge)}}function scopeChallengeResourceMetadataUrl(authInfo){if(authInfo?.resourceMetadataUrl!==void 0)return authInfo.resourceMetadataUrl;if(authInfo?.resource?.protocol==="https:"||authInfo?.resource?.protocol==="http:")return getOAuthProtectedResourceMetadataUrl(authInfo.resource)}function createScopeChallengeResponse(challenge,resourceMetadataUrl){return bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InsufficientScope,challenge.errorDescription??"Insufficient scope"),{requiredScopes:[...challenge.scopes],resourceMetadataUrl})}function resolveLegacyShimOptions(options){if(options?.maxRounds!==void 0&&(!Number.isInteger(options.maxRounds)||options.maxRounds<1))throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`);if(options?.roundTimeoutMs!==void 0&&(!Number.isFinite(options.roundTimeoutMs)||options.roundTimeoutMs<=0))throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`);return{maxRounds:options?.maxRounds??DEFAULT_LEGACY_SHIM_MAX_ROUNDS,roundTimeoutMs:options?.roundTimeoutMs??DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS,legacyShim:options?.legacyShim??!0}}function coerceEmbeddedInputRequest(method,key,entry){if(entry===null||typeof entry!="object"||typeof entry.method!="string")throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let embedded=entry,required2=requiredClientCapabilitiesForInputRequest(embedded);if(required2===void 0)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded,required:required2}}function syntheticElicitationId(){let webCrypto=globalThis.crypto;if(webCrypto?.randomUUID!==void 0)return webCrypto.randomUUID();let bytes=new Uint8Array(16);webCrypto.getRandomValues(bytes),bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[...bytes].map(byte=>byte.toString(16).padStart(2,"0")).join("");return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function legacyShimFailure(method,message){if(method==="tools/call")return{content:[{type:"text",text:message}],isError:!0};throw new ProtocolError(ProtocolErrorCode.InternalError,message)}function seedClientIdentityFromEnvelope(server,identity2){writeClientIdentity(server,identity2)}function installModernOnlyHandlers(server,servedModernVersions){installDiscoverHandler(server,servedModernVersions)}function serverIdentityOf(server){return readServerIdentity(server)}function discoverAdvertisedCapabilities(capabilities){return{...capabilities}}function toolInputElementCount(value,max){let count=0,stack=[value];for(;stack.length>0;){let node=stack.pop();if(!(node===null||typeof node!="object"))if(Array.isArray(node))for(let child of node){if(++count>max)return count;child!==null&&typeof child=="object"&&stack.push(child)}else for(let key in node){if(!Object.prototype.hasOwnProperty.call(node,key))continue;if(++count>max)return count;let child=node[key];child!==null&&typeof child=="object"&&stack.push(child)}}return count}function resolveMaxToolInputElements(value){if(!(value===void 0||value===1/0)){if(typeof value!="number"||Number.isNaN(value)||value<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`);return value}}function createToolExecutor(inputSchema2,handler){if(inputSchema2){let callback$1=handler;return async(args,ctx)=>callback$1(args,ctx)}let callback=handler;return async(_args,ctx)=>callback(ctx)}function convertListedInputSchema(name,inputSchema2){let json=standardSchemaToJsonSchema(inputSchema2,"input"),scan=scanXMcpHeaderDeclarations(json);return scan.valid||console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`),json}function convertOutputSchemaJson(outputSchema2){if(outputSchema2!==void 0)try{return standardSchemaToJsonSchema(outputSchema2,"output")}catch{return}}function createPromptHandler(name,argsSchema,callback){if(argsSchema){let typedCallback=callback;return async(args,ctx)=>{let parseResult=await validateStandardSchema(argsSchema,args??{});if(!parseResult.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid arguments for prompt ${name}: ${parseResult.error}`);return typedCallback(parseResult.data,ctx)}}else{let typedCallback=callback;return async(_args,ctx)=>typedCallback(ctx)}}function createCompletionResult(suggestions){return{completion:{values:suggestions.map(String).slice(0,100),total:suggestions.length,hasMore:suggestions.length>100}}}function getSchemaShape(schema2){let candidate=schema2;if(candidate.shape&&typeof candidate.shape=="object")return candidate.shape}function isOptionalSchema(schema2){return schema2?.type==="optional"}function unwrapOptionalSchema(schema2){return isOptionalSchema(schema2)?schema2.def?.innerType??schema2:schema2}var COMPLETABLE_SYMBOL,DEFAULT_SSE_KEEP_ALIVE_MS,MAX_TIMER_DELAY_MS,InMemoryServerEventBus,DEFAULT_MAX_SUBSCRIPTIONS,ALLOWED_METHODS,DEFAULT_LEGACY_SHIM_MAX_ROUNDS,DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS,LegacyInputRequiredShim,INPUT_REQUIRED_CAPABLE_METHODS,writeClientIdentity,installDiscoverHandler,readServerIdentity,Server,McpServer,ResourceTemplate,EMPTY_OBJECT_JSON_SCHEMA,EMPTY_COMPLETION_RESULT,init_mcp_DIH4cS6P=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/mcp-DIH4cS6P.mjs"(){"use strict";init_src_Cqbh3MYc();init_shimsNode();COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");DEFAULT_SSE_KEEP_ALIVE_MS=15e3,MAX_TIMER_DELAY_MS=2**31-1;InMemoryServerEventBus=class{_listeners=new Set;constructor(onerror){this.onerror=onerror}publish(event){for(let listener of this._listeners)try{listener(event)}catch(error3){this.onerror?.(error3 instanceof Error?error3:new Error(String(error3)))}}subscribe(listener){this._listeners.add(listener);let live=!0;return()=>{live&&(live=!1,this._listeners.delete(listener))}}get listenerCount(){return this._listeners.size}};DEFAULT_MAX_SUBSCRIPTIONS=1024;ALLOWED_METHODS="GET, HEAD, OPTIONS";DEFAULT_LEGACY_SHIM_MAX_ROUNDS=8,DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS=6e5;LegacyInputRequiredShim=class{constructor(_host){this._host=_host}async fulfill(method,handler,request,ctx,firstResult){let{maxRounds,roundTimeoutMs}=this._host,outerSignal=ctx.mcpReq.signal,current=firstResult,round=0;for(;;){if(round+=1,round>maxRounds)return legacyShimFailure(method,inputRequiredRoundsExceededMessage(method,maxRounds));let inputRequests=current.inputRequests,hasInputRequests=inputRequests!=null&&Object.keys(inputRequests).length>0,requestState=typeof current.requestState=="string"?current.requestState:void 0;if(!hasInputRequests&&requestState===void 0)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let responses;if(hasInputRequests){let declared=this._host.resolvedClientCapabilities(ctx),coerced=[];for(let[key,entry]of Object.entries(inputRequests)){let{embedded,required:required2}=coerceEmbeddedInputRequest(method,key,entry);if(embedded.method!=="roots/list"&&embedded.params===void 0)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`);if(missingClientCapabilities(required2,declared)!==void 0)return legacyShimFailure(method,`Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared===void 0?" (no client capabilities are available on this connection \u2014 per-request legacy serving cannot receive server-to-client requests)":""}`);coerced.push([key,embedded])}let roundAbort=linkedRoundAbort(outerSignal);try{let legOptions={relatedRequestId:ctx.mcpReq.id,timeout:roundTimeoutMs,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:roundAbort.signal},fulfilled=await Promise.all(coerced.map(async([key,embedded])=>{try{return[key,await this._dispatchLeg(embedded,legOptions)]}catch(error3){throw roundAbort.abort(error3),error3}}));responses=Object.fromEntries(fulfilled)}catch(error3){if(outerSignal.aborted)throw error3;return legacyShimFailure(method,`Fulfilling input required by '${method}' failed: ${error3 instanceof Error?error3.message:String(error3)}`)}finally{roundAbort.dispose()}}else await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS,outerSignal);let ctxNext={...ctx,mcpReq:{...ctx.mcpReq,inputResponses:responses,droppedInputResponseKeys:void 0,requestState:requestStateAccessor(requestState)}};if(requestState!==void 0){let decoded=await this._host.verifyRequestState(requestState,ctxNext,method);decoded!==void 0&&(ctxNext=withRequestStateValue(ctxNext,decoded))}let next=await handler(request,ctxNext);if(!isInputRequiredResult(next))return next;current=next}}async _dispatchLeg(embedded,options){switch(embedded.method){case"elicitation/create":{let params=embedded.params;return params.mode==="url"&&params.elicitationId===void 0&&(params={...params,elicitationId:syntheticElicitationId()}),await this._host.sendElicitation(params,options)}case"sampling/createMessage":return await this._host.sendSampling(embedded.params,options);case"roots/list":return await this._host.listRoots(embedded.params,options)}}},INPUT_REQUIRED_CAPABLE_METHODS=new Set(["tools/call","prompts/get","resources/read"]);Server=class extends Protocol{_clientCapabilities;_clientVersion;static{writeClientIdentity=(server,identity2)=>{identity2.clientCapabilities!==void 0&&(server._clientCapabilities=identity2.clientCapabilities),identity2.clientInfo!==void 0&&(server._clientVersion=identity2.clientInfo)},installDiscoverHandler=(server,servedModernVersions)=>{let missing=servedModernVersions.filter(version2=>!server._supportedProtocolVersions.includes(version2));missing.length>0&&(server._supportedProtocolVersions=[...server._supportedProtocolVersions,...missing]),server.setRequestHandler("server/discover",()=>server._ondiscover())},readServerIdentity=server=>server._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new LegacyInputRequiredShim({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:ctx=>this._inputRequestCapabilityView(ctx),verifyRequestState:(state,ctx,method)=>this._verifyRequestState(state,ctx,method),sendElicitation:(params,options)=>this._sendElicitationLeg(params,options,{validateAcceptedContent:!1}),sendSampling:(params,options)=>this.createMessage(params,options),listRoots:(params,options)=>this.listRoots(params,options)})}oninitialized;constructor(_serverInfo,options){if(super(options),this._serverInfo=_serverInfo,this._capabilities=options?.capabilities?{...options.capabilities}:{},this._instructions=options?.instructions,this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this._requestStateVerify=options?.requestState?.verify,this._inputRequiredServing=resolveLegacyShimOptions(options?.inputRequired),options?.cacheHints!==void 0){for(let[operation,hint]of Object.entries(options.cacheHints))hint!==void 0&&assertValidCacheHint(hint,`cacheHints['${operation}']`);this._cacheHints=options.cacheHints}this.setRequestHandler("initialize",request=>this._oninitialize(request)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),modernProtocolVersions(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}async connect(transport){if(this.transport!==void 0)throw new SdkError(SdkErrorCode.AlreadyConnected,"Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.");await super.connect(transport)}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(request,ctx)=>{let transportSessionId=ctx.sessionId||ctx.http?.req?.headers.get("mcp-session-id")||void 0,{level}=request.params,parseResult=parseSchema(LoggingLevelSchema,level);return parseResult.success&&this._loggingLevels.set(transportSessionId,parseResult.data),{}})}buildContext(ctx,transportInfo){let hasHttpInfo=ctx.http||transportInfo?.request||transportInfo?.closeSSEStream||transportInfo?.closeStandaloneSSEStream;return{...ctx,mcpReq:{...ctx.mcpReq,log:(level,data,logger)=>{if(!this._capabilities.logging)return Promise.resolve();let threshold;if(this._servedModernEra()){if(threshold=ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY],threshold===void 0)return Promise.resolve()}else threshold=this._loggingLevels.get(ctx.sessionId)??this._loggingLevels.get(void 0);return threshold!==void 0&&this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(threshold)?Promise.resolve():ctx.mcpReq.notify({method:"notifications/message",params:{level,data,logger}})},elicitInput:(params,options)=>this.elicitInput(params,options),requestSampling:(params,options)=>this.createMessage(params,options)},http:hasHttpInfo?{...ctx.http,req:transportInfo?.request,closeSSE:transportInfo?.closeSSEStream,closeStandaloneSSE:transportInfo?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index)=>[level,index]));isMessageIgnored=(level,sessionId)=>{let currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):!1};registerCapabilities(capabilities){if(this.transport)throw new SdkError(SdkErrorCode.AlreadyConnected,"Cannot register capabilities after connecting to transport");let hadLogging=!!this._capabilities.logging;this._capabilities=mergeCapabilities(this._capabilities,capabilities),!hadLogging&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(method,handler){if(method!=="tools/call"){let cacheHint=this._cacheHints?.[method],isInputRequiredCapable=INPUT_REQUIRED_CAPABLE_METHODS.has(method);return cacheHint===void 0&&!isInputRequiredCapable?async(request,ctx)=>{let result=await handler(request,ctx);if(isInputRequiredResult(result))throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return result}:async(request,ctx)=>{let result=isInputRequiredCapable?await this._invokeInputRequiredCapableHandler(method,handler,request,ctx):await handler(request,ctx);if(isInputRequiredResult(result)){if(!isInputRequiredCapable)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return result}return cacheHint===void 0?result:attachCacheHintFallback(result,cacheHint)}}return async(request,ctx)=>{let codec=codecForVersion(this._negotiatedProtocolVersion),validatedRequest=codec.validateRequest("tools/call",request);if(!validatedRequest.ok)throw new ProtocolError(validatedRequest.reason==="not-in-era"?ProtocolErrorCode.InternalError:ProtocolErrorCode.InvalidParams,validatedRequest.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${validatedRequest.message}`);let result=await this._invokeInputRequiredCapableHandler("tools/call",handler,request,ctx);if(isInputRequiredResult(result))return result;let normalizedResult=normalizeContentlessToolResult(result),validationResult=codec.validateResult("tools/call",normalizedResult);if(!validationResult.ok)throw new ProtocolError(validationResult.reason==="not-in-era"?ProtocolErrorCode.InternalError:ProtocolErrorCode.InvalidParams,validationResult.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${validationResult.message}`);return validationResult.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&isModernProtocolVersion(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(method,handler,request,ctx){let servedModern=this._servedModernEra(),rawRequestState=ctx.mcpReq.requestState();if(rawRequestState!==void 0&&typeof rawRequestState!="string")throw new ProtocolError(ProtocolErrorCode.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let ctxForHandler=ctx;if(typeof rawRequestState=="string"){let decoded=await this._verifyRequestState(rawRequestState,ctx,method);decoded!==void 0&&(ctxForHandler=withRequestStateValue(ctx,decoded))}let result;try{result=await handler(request,ctxForHandler)}catch(error3){throw error3 instanceof ProtocolError&&error3.code===ProtocolErrorCode.UrlElicitationRequired&&servedModern?new ProtocolError(ProtocolErrorCode.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { \u2026: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):error3}if(!isInputRequiredResult(result))return result;if(!servedModern){if(!this._inputRequiredServing.legacyShim)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(method,handler,request,ctxForHandler,result)}let inputRequests=result.inputRequests,hasInputRequests=inputRequests!=null&&Object.keys(inputRequests).length>0,hasRequestState=typeof result.requestState=="string";if(!hasInputRequests&&!hasRequestState)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(hasInputRequests){let declared=this._inputRequestCapabilityView(ctx);for(let[key,entry]of Object.entries(inputRequests)){let{embedded,required:required2}=coerceEmbeddedInputRequest(method,key,entry),missing=missingClientCapabilities(required2,declared);if(missing!==void 0)throw new MissingRequiredClientCapabilityError({requiredCapabilities:missing},`Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`)}}return result}async _verifyRequestState(state,ctx,method){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(state,ctx)}catch(error3){throw this.onerror?.(new Error(`requestState verification rejected ${method}: ${error3 instanceof Error?error3.message:String(error3)}`)),new ProtocolError(ProtocolErrorCode.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(ctx){return this._servedModernEra()?ctx.mcpReq.envelope?.[CLIENT_CAPABILITIES_META_KEY]:this._clientCapabilities}_assertPushApiInServedEra(method){if(this._servedModernEra())throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead \u2014 the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method,era:"2026-07-28"})}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support sampling (required for ${method})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support elicitation (required for ${method})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support listing roots (required for ${method})`);break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support logging (required for ${method})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support notifying about resources (required for ${method})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${method})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${method})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support URL elicitation (required for ${method})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){switch(method){case"completion/complete":if(!this._capabilities.completions)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support completions (required for ${method})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support resources (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support tools (required for ${method})`);break;case"ping":case"initialize":break}}async _oninitialize(request){let requestedVersion=request.params.protocolVersion;this._clientCapabilities=request.params.capabilities,this._clientVersion=request.params.clientInfo;let legacyVersions=legacyProtocolVersions(this._supportedProtocolVersions),protocolVersion=legacyVersions.includes(requestedVersion)?requestedVersion:legacyVersions[0]??LATEST_PROTOCOL_VERSION;return this._negotiatedProtocolVersion=protocolVersion,this.transport?.setProtocolVersion?.(protocolVersion),{protocolVersion,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:modernProtocolVersions(this._supportedProtocolVersions),capabilities:discoverAdvertisedCapabilities(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(result,advertisedOutputSchema){return this._wireCodec().projectCallToolResult(result,advertisedOutputSchema)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(params,options){if(this._assertPushApiInServedEra("sampling/createMessage"),(params.tools||params.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages.at(-1),lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c=>c.type==="tool_result"),previousMessage=params.messages.length>1?params.messages.at(-2):void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c=>c.type==="tool_use");if(hasToolResults){if(lastContent.some(c=>c.type!=="tool_result"))throw new ProtocolError(ProtocolErrorCode.InvalidParams,"The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new ProtocolError(ProtocolErrorCode.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c=>c.type==="tool_use").map(c=>c.id)),toolResultIds=new Set(lastContent.filter(c=>c.type==="tool_result").map(c=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new ProtocolError(ProtocolErrorCode.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let hasTools=!!(params.tools||params.toolChoice),wide=await this.request({method:"sampling/createMessage",params},options),outcome=this._wireCodec().samplingResultVariant(hasTools,wide);if(!outcome.ok)throw new SdkError(SdkErrorCode.InvalidResult,`Invalid sampling/createMessage result: ${outcome.reason==="invalid"?outcome.message:outcome.reason}`);return outcome.value}async elicitInput(params,options){switch(this._assertPushApiInServedEra("elicitation/create"),params.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support form elicitation.");break}return this._sendElicitationLeg(params,options)}async _sendElicitationLeg(params,options,behavior){let mode=params.mode??"form",validateAcceptedContent=behavior?.validateAcceptedContent??!0;switch(mode){case"url":{let urlParams=params;return this.request({method:"elicitation/create",params:urlParams},options)}case"form":{let formParams=params.mode==="form"?params:{...params,mode:"form"},result=await this.request({method:"elicitation/create",params:formParams},options);if(validateAcceptedContent&&result.action==="accept"&&result.content&&formParams.requestedSchema)try{let validationResult=this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);if(!validationResult.valid)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}catch(error3){throw error3 instanceof ProtocolError?error3:new ProtocolError(ProtocolErrorCode.InternalError,`Error validating elicitation response: ${error3 instanceof Error?error3.message:String(error3)}`)}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params},options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging&&!this.isMessageIgnored(params.level,sessionId))return this.notification({method:"notifications/message",params})}async sendResourceUpdated(params){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"})}};McpServer=class{server;_maxToolInputElements;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(name){let tool=this._registeredTools[name];if(!(tool===void 0||!tool.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,name))return this._toolInputSchemaJson[name];if(tool.inputSchema===void 0)return EMPTY_OBJECT_JSON_SCHEMA;try{let json=standardSchemaToJsonSchema(tool.inputSchema,"input");return this._toolInputSchemaJson[name]=json,json}catch{return}}}constructor(serverInfo,options){this.server=new Server(serverInfo,options),this._maxToolInputElements=resolveMaxToolInputElements(options?.maxToolInputElements),options?.capabilities?.tools&&this.setToolRequestHandlers(),options?.capabilities?.resources&&this.setResourceRequestHandlers(),options?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(transport){return supportsScopeChallengeResolver(transport)&&transport.setScopeChallengeResolver(context=>this.resolveScopeChallenge(context)),await this.server.connect(transport)}async close(){await this.server.close()}resolveScopeChallenge=context=>{switch(context.request.method){case"tools/call":{let toolName=context.request.params?.name;if(typeof toolName!="string")return;let tool=this._registeredTools[toolName];return tool===void 0||!tool.enabled?void 0:tool.scopeChallenge?.(context)}case"resources/read":{let resourceUri=context.request.params?.uri;if(typeof resourceUri!="string")return;let uri;try{uri=new URL(resourceUri)}catch{return}let resource2=this._registeredResources[uri.toString()];if(resource2!==void 0)return resource2.enabled?resource2.scopeChallenge?.(context):void 0;for(let template of Object.values(this._registeredResourceTemplates))if(template.resourceTemplate.uriTemplate.match(uri.toString()))return template.enabled?template.scopeChallenge?.(context):void 0;return}case"prompts/get":{let promptName=context.request.params?.name;if(typeof promptName!="string")return;let prompt=this._registeredPrompts[promptName];return prompt===void 0||!prompt.enabled?void 0:prompt.scopeChallenge?.(context)}default:return}};_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,tool])=>tool.enabled).map(([name,tool])=>{let toolDefinition={name,title:tool.title,description:tool.description,inputSchema:tool.inputSchema?convertListedInputSchema(name,tool.inputSchema):EMPTY_OBJECT_JSON_SCHEMA,annotations:tool.annotations,icons:tool.icons,execution:tool.execution,_meta:tool._meta};return tool.outputSchema&&(toolDefinition.outputSchema=standardSchemaToJsonSchema(tool.outputSchema,"output")),toolDefinition})})),this.server.setRequestHandler("tools/call",async(request,ctx)=>{let tool=this._registeredTools[request.params.name];if(!tool)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Tool ${request.params.name} not found`);if(!tool.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Tool ${request.params.name} disabled`);try{let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),result=await this.executeToolHandler(tool,args,ctx);return await this.validateToolOutput(tool,result,request.params.name),isInputRequiredResult(result)?result:this.server.projectCallToolResult(result,tool.outputSchemaJson)}catch(error3){if(error3 instanceof ProtocolError&&error3.code===ProtocolErrorCode.UrlElicitationRequired)throw error3;return this.createToolError(error3 instanceof Error?error3.message:String(error3))}}),this._toolHandlersInitialized=!0)}createToolError(errorMessage){return{content:[{type:"text",text:errorMessage}],isError:!0}}async validateToolInput(tool,args,toolName){if(this._maxToolInputElements!==void 0&&toolInputElementCount(args,this._maxToolInputElements)>this._maxToolInputElements)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!tool.inputSchema)return;let parseResult=await validateStandardSchema(tool.inputSchema,args??{});if(!parseResult.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`);return parseResult.data}async validateToolOutput(tool,result,toolName){if(!tool.outputSchema||isInputRequiredResult(result)||result.isError)return;if(result.structuredContent===void 0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);let parseResult=await validateStandardSchema(tool.outputSchema,result.structuredContent);if(!parseResult.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`)}async executeToolHandler(tool,args,ctx){return tool.executor(args,ctx)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async request=>{switch(request.params.ref.type){case"ref/prompt":return assertCompleteRequestPrompt(request),this.handlePromptCompletion(request,request.params.ref);case"ref/resource":return assertCompleteRequestResourceTemplate(request),this.handleResourceCompletion(request,request.params.ref);default:throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid completion reference: ${request.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(request,ref){let prompt=this._registeredPrompts[ref.name];if(!prompt)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${ref.name} not found`);if(!prompt.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${ref.name} disabled`);if(!prompt.argsSchema)return EMPTY_COMPLETION_RESULT;let field=unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]);if(!isCompletable(field))return EMPTY_COMPLETION_RESULT;let completer=getCompleter(field);return completer?createCompletionResult(await completer(request.params.argument.value,request.params.context)):EMPTY_COMPLETION_RESULT}async handleResourceCompletion(request,ref){let template=Object.values(this._registeredResourceTemplates).find(t=>t.resourceTemplate.uriTemplate.toString()===ref.uri);if(!template){if(this._registeredResources[ref.uri])return EMPTY_COMPLETION_RESULT;throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource template ${request.params.ref.uri} not found`)}let completer=template.resourceTemplate.completeCallback(request.params.argument.name);return completer?createCompletionResult(await completer(request.params.argument.value,request.params.context)):EMPTY_COMPLETION_RESULT}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler("resources/list",async(_request,ctx)=>{let resources=Object.entries(this._registeredResources).filter(([_,resource2])=>resource2.enabled).map(([uri,resource2])=>({uri,name:resource2.name,...resource2.metadata})),templateResources=[];for(let template of Object.values(this._registeredResourceTemplates)){if(!template.resourceTemplate.listCallback)continue;let result=await template.resourceTemplate.listCallback(ctx);for(let resource2 of result.resources)templateResources.push({...template.metadata,...resource2})}return{resources:[...resources,...templateResources]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([name,template])=>({name,uriTemplate:template.resourceTemplate.uriTemplate.toString(),...template.metadata}))})),this.server.setRequestHandler("resources/read",async(request,ctx)=>{let uri;try{uri=new URL(request.params.uri)}catch{throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource URI ${request.params.uri} is invalid`,{uri:request.params.uri,reason:"invalid_uri"})}let resource2=this._registeredResources[uri.toString()];if(resource2){if(!resource2.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource ${uri} disabled`);return attachCacheHintFallback(await resource2.readCallback(uri,ctx),resource2.cacheHint)}for(let template of Object.values(this._registeredResourceTemplates)){let variables=template.resourceTemplate.uriTemplate.match(uri.toString());if(variables){if(!template.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource template ${template.resourceTemplate.uriTemplate} disabled`);return attachCacheHintFallback(await template.readCallback(uri,variables,ctx),template.cacheHint)}}throw new ResourceNotFoundError(request.params.uri)}),this._resourceHandlersInitialized=!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,prompt])=>prompt.enabled).map(([name,prompt])=>({name,title:prompt.title,description:prompt.description,arguments:prompt.argsSchema?promptArgumentsFromStandardSchema(prompt.argsSchema):void 0,icons:prompt.icons,_meta:prompt._meta}))})),this.server.setRequestHandler("prompts/get",async(request,ctx)=>{let prompt=this._registeredPrompts[request.params.name];if(!prompt)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${request.params.name} not found`);if(!prompt.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${request.params.name} disabled`);return prompt.handler(request.params.arguments,ctx)}),this._promptHandlersInitialized=!0)}registerResource(name,uriOrTemplate,config2,readCallback){let{cacheHint,scopeChallenge,...resourceMetadata}=config2,metadata=resourceMetadata;if(cacheHint!==void 0&&assertValidCacheHint(cacheHint,`resource ${name}`),typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,config2.title,uriOrTemplate,metadata,scopeChallenge,readCallback);return cacheHint!==void 0&&(registeredResource.cacheHint=cacheHint),this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,config2.title,uriOrTemplate,metadata,scopeChallenge,readCallback);return cacheHint!==void 0&&(registeredResourceTemplate.cacheHint=cacheHint),this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}_createRegisteredResource(name,title,uri,metadata,scopeChallenge,readCallback){let registeredResource={name,title,metadata,readCallback,scopeChallenge,enabled:!0,disable:()=>registeredResource.update({enabled:!1}),enable:()=>registeredResource.update({enabled:!0}),remove:()=>registeredResource.update({uri:null}),update:updates=>{updates.uri!==void 0&&updates.uri!==uri&&(delete this._registeredResources[uri],updates.uri&&(this._registeredResources[updates.uri]=registeredResource)),updates.name!==void 0&&(registeredResource.name=updates.name),updates.title!==void 0&&(registeredResource.title=updates.title),updates.metadata!==void 0&&(registeredResource.metadata=updates.metadata),updates.callback!==void 0&&(registeredResource.readCallback=updates.callback),updates.scopeChallenge!==void 0&&(registeredResource.scopeChallenge=updates.scopeChallenge===null?void 0:updates.scopeChallenge),updates.enabled!==void 0&&(registeredResource.enabled=updates.enabled),this.sendResourceListChanged()}};return this._registeredResources[uri]=registeredResource,registeredResource}_createRegisteredResourceTemplate(name,title,template,metadata,scopeChallenge,readCallback){let registeredResourceTemplate={resourceTemplate:template,title,metadata,readCallback,scopeChallenge,enabled:!0,disable:()=>registeredResourceTemplate.update({enabled:!1}),enable:()=>registeredResourceTemplate.update({enabled:!0}),remove:()=>registeredResourceTemplate.update({name:null}),update:updates=>{updates.name!==void 0&&updates.name!==name&&(delete this._registeredResourceTemplates[name],updates.name&&(this._registeredResourceTemplates[updates.name]=registeredResourceTemplate)),updates.title!==void 0&&(registeredResourceTemplate.title=updates.title),updates.template!==void 0&&(registeredResourceTemplate.resourceTemplate=updates.template),updates.metadata!==void 0&&(registeredResourceTemplate.metadata=updates.metadata),updates.callback!==void 0&&(registeredResourceTemplate.readCallback=updates.callback),updates.scopeChallenge!==void 0&&(registeredResourceTemplate.scopeChallenge=updates.scopeChallenge===null?void 0:updates.scopeChallenge),updates.enabled!==void 0&&(registeredResourceTemplate.enabled=updates.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[name]=registeredResourceTemplate;let variableNames=template.uriTemplate.variableNames;return Array.isArray(variableNames)&&variableNames.some(v=>!!template.completeCallback(v))&&this.setCompletionRequestHandler(),registeredResourceTemplate}_createRegisteredPrompt(name,title,description,argsSchema,callback,icons,scopeChallenge,_meta){let currentArgsSchema=argsSchema,currentCallback=callback,registeredPrompt={title,description,argsSchema,icons,scopeChallenge,_meta,handler:createPromptHandler(name,argsSchema,callback),enabled:!0,disable:()=>registeredPrompt.update({enabled:!1}),enable:()=>registeredPrompt.update({enabled:!0}),remove:()=>registeredPrompt.update({name:null}),update:updates=>{updates.name!==void 0&&updates.name!==name&&(delete this._registeredPrompts[name],updates.name&&(this._registeredPrompts[updates.name]=registeredPrompt)),updates.title!==void 0&&(registeredPrompt.title=updates.title),updates.description!==void 0&&(registeredPrompt.description=updates.description),updates.icons!==void 0&&(registeredPrompt.icons=updates.icons),updates.scopeChallenge!==void 0&&(registeredPrompt.scopeChallenge=updates.scopeChallenge===null?void 0:updates.scopeChallenge),updates._meta!==void 0&&(registeredPrompt._meta=updates._meta);let needsHandlerRegen=!1;updates.argsSchema!==void 0&&(registeredPrompt.argsSchema=updates.argsSchema,currentArgsSchema=updates.argsSchema,needsHandlerRegen=!0),updates.callback!==void 0&&(currentCallback=updates.callback,needsHandlerRegen=!0),needsHandlerRegen&&(registeredPrompt.handler=createPromptHandler(name,currentArgsSchema,currentCallback)),updates.enabled!==void 0&&(registeredPrompt.enabled=updates.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[name]=registeredPrompt,argsSchema){let shape=getSchemaShape(argsSchema);shape&&Object.values(shape).some(field=>isCompletable(unwrapOptionalSchema(field)))&&this.setCompletionRequestHandler()}return registeredPrompt}_createRegisteredTool(name,title,description,inputSchema2,outputSchema2,annotations,icons,execution,scopeChallenge,_meta,handler){validateAndWarnToolName(name);let currentHandler=handler,outputSchemaJson,registeredTool={title,description,inputSchema:inputSchema2,outputSchema:outputSchema2,get outputSchemaJson(){return outputSchemaJson??=convertOutputSchemaJson(registeredTool.outputSchema)},set outputSchemaJson(value){outputSchemaJson=value},annotations,icons,execution,scopeChallenge,_meta,handler,executor:createToolExecutor(inputSchema2,handler),enabled:!0,disable:()=>registeredTool.update({enabled:!1}),enable:()=>registeredTool.update({enabled:!0}),remove:()=>registeredTool.update({name:null}),update:updates=>{updates.name!==void 0&&updates.name!==name&&(typeof updates.name=="string"&&validateAndWarnToolName(updates.name),delete this._registeredTools[name],delete this._toolInputSchemaJson[name],updates.name&&(delete this._toolInputSchemaJson[updates.name],this._registeredTools[updates.name]=registeredTool,name=updates.name)),updates.title!==void 0&&(registeredTool.title=updates.title),updates.description!==void 0&&(registeredTool.description=updates.description);let needsExecutorRegen=!1;updates.paramsSchema!==void 0&&(registeredTool.inputSchema=updates.paramsSchema,delete this._toolInputSchemaJson[name],needsExecutorRegen=!0),updates.callback!==void 0&&(registeredTool.handler=updates.callback,currentHandler=updates.callback,needsExecutorRegen=!0),needsExecutorRegen&&(registeredTool.executor=createToolExecutor(registeredTool.inputSchema,currentHandler)),updates.outputSchema!==void 0&&(registeredTool.outputSchema=updates.outputSchema,registeredTool.outputSchemaJson=convertOutputSchemaJson(updates.outputSchema)),updates.annotations!==void 0&&(registeredTool.annotations=updates.annotations),updates.icons!==void 0&&(registeredTool.icons=updates.icons),updates.scopeChallenge!==void 0&&(registeredTool.scopeChallenge=updates.scopeChallenge===null?void 0:updates.scopeChallenge),updates._meta!==void 0&&(registeredTool._meta=updates._meta),updates.enabled!==void 0&&(registeredTool.enabled=updates.enabled),this.sendToolListChanged()}};return this._registeredTools[name]=registeredTool,this.setToolRequestHandlers(),this.sendToolListChanged(),registeredTool}registerTool(name,config2,cb){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let{title,description,inputSchema:inputSchema2,outputSchema:outputSchema2,annotations,icons,scopeChallenge,_meta}=config2;return this._createRegisteredTool(name,title,description,normalizeRawShapeSchema(inputSchema2),normalizeRawShapeSchema(outputSchema2),annotations,icons,void 0,scopeChallenge,_meta,cb)}registerPrompt(name,config2,cb){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let{title,description,argsSchema,icons,scopeChallenge,_meta}=config2,registeredPrompt=this._createRegisteredPrompt(name,title,description,normalizeRawShapeSchema(argsSchema),cb,icons,scopeChallenge,_meta);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(params,sessionId){return this.server.sendLoggingMessage(params,sessionId)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},ResourceTemplate=class{_uriTemplate;constructor(uriTemplate,_callbacks){this._callbacks=_callbacks,this._uriTemplate=typeof uriTemplate=="string"?new UriTemplate(uriTemplate):uriTemplate}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(variable){return this._callbacks.complete?.[variable]}};EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}}}});async function invoke(server,message,ctx){let transport=new PerRequestHTTPServerTransport({classification:ctx.classification,...ctx.responseMode!==void 0&&{responseMode:ctx.responseMode},...ctx.keepAliveMs!==void 0&&{keepAliveMs:ctx.keepAliveMs}});return await server.connect(transport),transport.handleMessage(message,{...ctx.request!==void 0&&{request:ctx.request},...ctx.authInfo!==void 0&&{authInfo:ctx.authInfo}})}function requestBodyTooLargeMessage(maxBytes){return`Payload Too Large: Request body must not exceed ${maxBytes} bytes`}function resolveMaxRequestBodySize(value){if(value===void 0)return DEFAULT_MAX_REQUEST_BODY_SIZE;if(typeof value!="number"||!Number.isFinite(value)||value<=0)throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(value)}`);return value}async function readRequestBody(request,maxBytes=DEFAULT_MAX_REQUEST_BODY_SIZE){if(Number(request.headers.get("content-length"))>maxBytes)return{tooLarge:!0};if(request.body===null)return{tooLarge:!1,text:""};let reader=request.body.getReader(),decoder=new TextDecoder,received=0,text2="";try{for(;;){let{done,value}=await reader.read();if(done)break;if(received+=value.byteLength,received>maxBytes)return{tooLarge:!0};text2+=decoder.decode(value,{stream:!0})}}finally{reader.releaseLock()}return{tooLarge:!1,text:text2+decoder.decode()}}function echoableRequestId(body){if(body===null||typeof body!="object"||Array.isArray(body))return null;let{method,id}=body;return typeof method!="string"?null:typeof id=="string"||typeof id=="number"?id:null}function jsonRpcErrorResponse(httpStatus,code,message,data,id=null){return Response.json({jsonrpc:"2.0",error:{code,message,...data!==void 0&&{data}},id},{status:httpStatus})}function rejectionResponse(rejection2,id=null){return jsonRpcErrorResponse(rejection2.httpStatus,rejection2.code,rejection2.message,rejection2.data,id)}function toError(value){return value instanceof Error?value:new Error(String(value))}function internalServerErrorResponse(id=null){return jsonRpcErrorResponse(500,-32603,"Internal server error",void 0,id)}function assertNotServing(server){if(server.transport!==void 0)throw new Error("The factory returned an instance that is still serving another request. Return a new instance for each request.")}function createLegacyStatelessFallback(factory,onerror,keepAliveMs,maxRequestBodySize){return async(request,options)=>{if(request.method.toUpperCase()!=="POST")return jsonRpcErrorResponse(405,-32e3,"Method not allowed.");try{let product=await factory({era:"legacy",...options?.authInfo!==void 0&&{authInfo:options.authInfo},requestInfo:request}),transport=new WebStandardStreamableHTTPServerTransport({sessionIdGenerator:void 0,...keepAliveMs!==void 0&&{keepAliveMs},...maxRequestBodySize!==void 0&&{maxRequestBodySize}});await product.connect(transport);let teardown=()=>{transport.close().catch(()=>{}),product.close().catch(()=>{})};request.signal?.addEventListener("abort",teardown,{once:!0});let response=await transport.handleRequest(request,{...options?.authInfo!==void 0&&{authInfo:options.authInfo},...options?.parsedBody!==void 0&&{parsedBody:options.parsedBody}});if(response.body===null||mediaTypeEssence(response.headers.get("content-type"))!=="text/event-stream")return teardown(),response;let reader=response.body.getReader(),toreDown=!1,completeExchange=()=>{toreDown||(toreDown=!0,teardown())},monitoredBody=new ReadableStream({pull:async controller=>{try{let{done,value}=await reader.read();if(done){completeExchange(),controller.close();return}value!==void 0&&controller.enqueue(value)}catch(error3){completeExchange(),controller.error(error3)}},cancel:reason=>(completeExchange(),reader.cancel(reason).catch(()=>{}))});return new Response(monitoredBody,{status:response.status,statusText:response.statusText,headers:response.headers})}catch(error3){try{onerror?.(toError(error3))}catch{}return internalServerErrorResponse(echoableRequestId(options?.parsedBody))}}}function standardHeadersOf(request){return{protocolVersionHeader:request.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:request.headers.get("mcp-method")??void 0,mcpNameHeader:request.headers.get("mcp-name")??void 0}}async function classifyEntryRequest(request,providedParsedBody,needsForward=!0,maxRequestBodySize=DEFAULT_MAX_REQUEST_BODY_SIZE){let httpMethod=request.method.toUpperCase(),body,parsedBody=providedParsedBody,forwardRequest=request,unparseable=!1;if(httpMethod==="POST"){if(parsedBody===void 0){needsForward&&(forwardRequest=request.clone());let bodyText;try{let read=await readRequestBody(request,maxRequestBodySize);if(read.tooLarge)return{step:"body-too-large"};bodyText=read.text}catch{return{step:"unreadable-body"}}try{body=bodyText.length===0?void 0:JSON.parse(bodyText)}catch{unparseable=!0}!unparseable&&body!==void 0&&(parsedBody=body)}else body=parsedBody;if(unparseable||body===void 0)return{step:"no-json-body",forwardRequest}}return{step:"classified",outcome:classifyInboundRequest({httpMethod,...standardHeadersOf(request),...body!==void 0&&{body}}),body,parsedBody,forwardRequest}}function createMcpHandler(factory,options={}){let{legacy,onerror,responseMode}=options,maxRequestBodySize=resolveMaxRequestBodySize(options.maxRequestBodySize);if(typeof legacy=="function")throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let inflight=new Set,closed=!1,reportError=error3=>{try{onerror?.(error3)}catch{}},bus=options.bus??new InMemoryServerEventBus(reportError),notify=createServerNotifier(bus),listenRouter=createListenRouter({bus,maxSubscriptions:options.maxSubscriptions??DEFAULT_MAX_SUBSCRIPTIONS,keepAliveMs:options.keepAliveMs??DEFAULT_SSE_KEEP_ALIVE_MS,onerror:reportError});responseMode==="json"&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let legacyHandler=legacy==="reject"?void 0:createLegacyStatelessFallback(factory,reportError,options.keepAliveMs,maxRequestBodySize);async function serveModern(route,request,authInfo){let claimedRevision=route.classification.revision;if(claimedRevision===void 0||!SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)){let error3=new UnsupportedProtocolVersionError({supported:[...SUPPORTED_MODERN_PROTOCOL_VERSIONS],requested:claimedRevision??"unknown"});return reportError(error3),jsonRpcErrorResponse(400,error3.code,error3.message,error3.data,echoableRequestId(route.message))}let stdHeaderRejection=validateStandardRequestHeaders({httpMethod:request.method,...standardHeadersOf(request)},route);if(stdHeaderRejection!==void 0)return reportError(new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)),rejectionResponse(stdHeaderRejection,echoableRequestId(route.message));let meta2=route.messageKind==="request"?requestMetaOf(route.message.params):void 0,declaredClientCapabilities=meta2?.[CLIENT_CAPABILITIES_META_KEY];if(route.messageKind==="request"){let required2=requiredClientCapabilitiesForRequest(route.message.method);if(required2!==void 0){let missing=missingClientCapabilities(required2,declaredClientCapabilities);if(missing!==void 0){let error3=new MissingRequiredClientCapabilityError({requiredCapabilities:missing});return reportError(error3),jsonRpcErrorResponse(httpStatusForErrorCode(error3.code,"ladder"),error3.code,error3.message,error3.data,route.message.id)}}}let product=await factory({era:"modern",...authInfo!==void 0&&{authInfo},requestInfo:request}),server=product instanceof McpServer?product.server:product;if(assertNotServing(server),route.messageKind==="request"&&route.message.method==="subscriptions/listen"){let capabilities=server.getCapabilities(),serverInfo=serverIdentityOf(server);return product.close().catch(reportError),listenRouter.serve(route.message,request.signal,capabilities,serverInfo)}if(route.messageKind==="request"&&route.message.method==="tools/call"&&product instanceof McpServer){let callParams=route.message.params,toolName=typeof callParams?.name=="string"?callParams.name:void 0,inputSchema2=toolName===void 0?void 0:product.toolInputSchemaJson(toolName);if(inputSchema2!==void 0){let scan=scanXMcpHeaderDeclarations(inputSchema2);if(scan.valid&&scan.declarations.length>0){let rejection2=validateMcpParamHeaders(scan.declarations,callParams?.arguments,request.headers);if(rejection2!==void 0)return product.close().catch(reportError),reportError(new Error(`Rejected inbound request (${rejection2.cell}): ${rejection2.message}`)),rejectionResponse(rejection2,route.message.id)}}}if(route.messageKind==="request"&&product instanceof McpServer)try{let challenge=await findScopeChallenge([route.message],authInfo,context=>product.resolveScopeChallenge(context));if(challenge!==void 0)return product.close().catch(reportError),createScopeChallengeResponse(challenge,scopeChallengeResourceMetadataUrl(authInfo))}catch(error3){return product.close().catch(reportError),reportError(toError(error3)),internalServerErrorResponse(route.message.id)}assertNotServing(server),setNegotiatedProtocolVersion(server,claimedRevision),installModernOnlyHandlers(server,SUPPORTED_MODERN_PROTOCOL_VERSIONS),meta2!==void 0&&seedClientIdentityFromEnvelope(server,{clientInfo:meta2[CLIENT_INFO_META_KEY],clientCapabilities:declaredClientCapabilities});let previousOnClose=server.onclose;inflight.add(server);let onExchangeClose=()=>{inflight.delete(server),server.onclose===onExchangeClose&&(server.onclose=previousOnClose),previousOnClose?.()};server.onclose=onExchangeClose;try{let response=await invoke(product,route.message,{classification:route.classification,request,...authInfo!==void 0&&{authInfo},...responseMode!==void 0&&{responseMode},...options.keepAliveMs!==void 0&&{keepAliveMs:options.keepAliveMs}});return route.messageKind==="notification"&&queueMicrotask(()=>{server.close().catch(()=>{})}),response}catch(error3){return error3 instanceof SdkError&&error3.code===SdkErrorCode.ConnectionClosed?new Response(null,{status:499}):(await server.close().catch(()=>{}),inflight.delete(server),reportError(toError(error3)),internalServerErrorResponse(echoableRequestId(route.message)))}}async function serveLegacyRoute(route,forwardRequest,authInfo,parsedBody){if(legacyHandler!==void 0)return legacyHandler(forwardRequest,{...authInfo!==void 0&&{authInfo},...parsedBody!==void 0&&{parsedBody}});let strict=modernOnlyStrictRejection(route,SUPPORTED_MODERN_PROTOCOL_VERSIONS);return strict===void 0?new Response(null,{status:202}):(reportError(new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)),rejectionResponse(strict,echoableRequestId(parsedBody)))}async function handle(request,requestOptions){let authInfo=requestOptions?.authInfo;if(request.method.toUpperCase()==="POST"&&!isJsonContentType(request.headers.get("content-type")))return reportError(new Error("Unsupported Media Type: Content-Type must be application/json")),jsonRpcErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let classified=await classifyEntryRequest(request,requestOptions?.parsedBody,!0,maxRequestBodySize);if(classified.step==="unreadable-body")return jsonRpcErrorResponse(400,-32700,"Parse error: the request body could not be read");if(classified.step==="body-too-large")return jsonRpcErrorResponse(413,-32e3,requestBodyTooLargeMessage(maxRequestBodySize));if(classified.step==="no-json-body")return legacyHandler!==void 0?legacyHandler(classified.forwardRequest,{...authInfo!==void 0&&{authInfo}}):jsonRpcErrorResponse(400,-32700,"Parse error: the request body is not valid JSON");let{outcome,body,parsedBody,forwardRequest}=classified;try{switch(outcome.kind){case"reject":return reportError(new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)),rejectionResponse(outcome,echoableRequestId(body));case"modern":return await serveModern(outcome,request,authInfo);case"legacy":return await serveLegacyRoute(outcome,forwardRequest,authInfo,parsedBody)}}catch(error3){return reportError(toError(error3)),internalServerErrorResponse(echoableRequestId(body))}}return{fetch:async(request,requestOptions)=>{if(closed)throw new Error("This MCP handler has been closed");try{return await handle(request,requestOptions)}catch(error3){return reportError(toError(error3)),internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody))}},notify,bus,close:async()=>{closed=!0,listenRouter.closeAll();let closing=[...inflight].map(server=>server.close().catch(()=>{}));inflight.clear(),await Promise.all(closing)}}}function validateHostHeader(hostHeader,allowedHostnames){if(!hostHeader)return{ok:!1,errorCode:"missing_host",message:"Missing Host header"};let hostname;try{hostname=new URL(`http://${hostHeader}`).hostname}catch{return{ok:!1,errorCode:"invalid_host_header",message:`Invalid Host header: ${hostHeader}`,hostHeader}}return allowedHostnames.includes(hostname)?{ok:!0,hostname}:{ok:!1,errorCode:"invalid_host",message:`Invalid Host: ${hostname}`,hostHeader,hostname}}function localhostAllowedHostnames(){return["localhost","127.0.0.1","[::1]"]}function hostHeaderValidationResponse(req,allowedHostnames){let result=validateHostHeader(req.headers.get("host"),allowedHostnames);if(!result.ok)return Response.json({jsonrpc:"2.0",error:{code:-32e3,message:result.message},id:null},{status:403,headers:{"Content-Type":"application/json"}})}function validateOriginHeader(originHeader,allowedOriginHostnames){if(originHeader==null||originHeader==="")return{ok:!0};let hostname,scheme;try{let url2=new URL(originHeader);hostname=url2.hostname,scheme=url2.protocol}catch{return{ok:!1,errorCode:"invalid_origin_header",message:`Invalid Origin header: ${originHeader}`,originHeader}}return hostname===""?{ok:!1,errorCode:"invalid_origin_header",message:`Invalid Origin header: ${originHeader}`,originHeader}:!(scheme!=="http:"&&scheme!=="https:"&&allowedOriginHostnames.includes(`${scheme}//*`))&&!allowedOriginHostnames.includes(hostname)?{ok:!1,errorCode:"invalid_origin",message:`Invalid Origin: ${hostname}`,originHeader,hostname}:{ok:!0,origin:originHeader,hostname}}function localhostAllowedOrigins(){return["localhost","127.0.0.1","[::1]"]}function originValidationResponse(req,allowedOriginHostnames){let result=validateOriginHeader(req.headers.get("origin"),allowedOriginHostnames);if(!result.ok)return Response.json({jsonrpc:"2.0",error:{code:-32e3,message:result.message},id:null},{status:403,headers:{"Content-Type":"application/json"}})}function bytesToBase64Url(bytes){let bin="";for(let b of bytes)bin+=String.fromCodePoint(b);return btoa(bin).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function constantTimeTagEqual(a,b){if(a.length!==b.length)return!1;let r=0;for(let i=0;i<a.length;i++)r|=a.codePointAt(i)^b.codePointAt(i);return r===0}function base64UrlToBytes(s){let b64=s.replaceAll("-","+").replaceAll("_","/"),bin=atob(b64),bytes=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)bytes[i]=bin.codePointAt(i);return bytes}function createRequestStateCodec(options){let subtle=globalThis.crypto?.subtle;if(subtle===void 0)throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions");let keyBytes=typeof options.key=="string"?new TextEncoder().encode(options.key):Uint8Array.from(options.key);if(keyBytes.byteLength<32)throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`);let ttlSeconds=options.ttlSeconds??600;if(!Number.isFinite(ttlSeconds))throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number");let bind=options.bind,cryptoKey,importedKey=()=>cryptoKey??=subtle.importKey("raw",keyBytes,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"]),utf8=new TextEncoder,BIND_LABEL="mcp.requestState.bind:",bindTag=async value=>bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC",await importedKey(),utf8.encode(BIND_LABEL+value))).slice(0,16));return{async mint(payload,ctx){let envelope={p:payload,exp:Math.floor(Date.now()/1e3)+ttlSeconds};if(bind!==void 0){if(ctx===void 0)throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured");envelope.b=await bindTag(bind(ctx))}let body=bytesToBase64Url(utf8.encode(JSON.stringify(envelope)));return`${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC",await importedKey(),utf8.encode(PREFIX+body))))}`},async verify(state,ctx){let dot=state.lastIndexOf(".");if(!state.startsWith(PREFIX)||dot<=3)throw new Error("malformed");let body=state.slice(3,dot),macBytes;try{macBytes=base64UrlToBytes(state.slice(dot+1))}catch{throw new Error("malformed")}if(!await subtle.verify("HMAC",await importedKey(),macBytes,utf8.encode(PREFIX+body)))throw new Error("mac");let envelope;try{envelope=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(base64UrlToBytes(body)))}catch{throw new Error("malformed")}if(typeof envelope.exp!="number"||envelope.exp<Math.floor(Date.now()/1e3))throw new Error("expired");if(bind!==void 0){let expected=await bindTag(bind(ctx));if(envelope.b===void 0||!constantTimeTagEqual(envelope.b,expected))throw new Error("bind")}else if(envelope.b!==void 0)throw new Error("bind");return envelope.p}}}function fromJsonSchema2(schema2,validator){return fromJsonSchema(schema2,validator??(_defaultValidator??=new AjvJsonSchemaValidator))}var PerRequestHTTPServerTransport,DEFAULT_MAX_REQUEST_BODY_SIZE,MAX_BATCH_SIZE,WebStandardStreamableHTTPServerTransport,PREFIX,_defaultValidator,init_dist=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/index.mjs"(){"use strict";init_mcp_DIH4cS6P();init_src_Cqbh3MYc();init_shimsNode();PerRequestHTTPServerTransport=class{onclose;onerror;onmessage;_classification;_responseMode;_started=!1;_used=!1;_closed=!1;_terminalDelivered=!1;_dispatchWindowOpen=!1;_requestId;_deferredResponse;_sse;_abortCleanup;_keepAliveMs;constructor(options){this._classification=options.classification,this._responseMode=options.responseMode??"auto",this._keepAliveMs=options.keepAliveMs??DEFAULT_SSE_KEEP_ALIVE_MS}async start(){if(this._started)throw new Error("PerRequestHTTPServerTransport is already started");this._started=!0}async handleMessage(message,extra){if(this._used)throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request");if(!this._started||this.onmessage===void 0)throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message");if(this._closed)throw new Error("PerRequestHTTPServerTransport is closed");this._used=!0;let signal=extra?.request?.signal;if(signal?.aborted)throw await this.close(),new SdkError(SdkErrorCode.ConnectionClosed,"The request was aborted before it could be handled");let messageExtra={classification:this._classification,...extra?.request!==void 0&&{request:extra.request},...extra?.authInfo!==void 0&&{authInfo:extra.authInfo}};if(isJSONRPCRequest(message)){this._requestId=message.id;let resolve,reject,promise=new Promise((promiseResolve,promiseReject)=>{resolve=promiseResolve,reject=promiseReject});if(this._deferredResponse={promise,resolve,reject,settled:!1},signal!==void 0){let onAbort=()=>{this.close()};signal.addEventListener("abort",onAbort,{once:!0}),this._abortCleanup=()=>signal.removeEventListener("abort",onAbort)}this._dispatchWindowOpen=!0;try{this.onmessage(message,messageExtra)}finally{this._dispatchWindowOpen=!1}return this._responseMode==="sse"&&!this._closed&&!this._deferredResponse.settled&&this.upgradeToSse(),promise}return this.onmessage(message,messageExtra),new Response(null,{status:202})}async send(message,options){if(this._closed)return;let isResponse=isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message),relatedId=isResponse?message.id:options?.relatedRequestId;if(this._requestId===void 0||relatedId===void 0||relatedId!==this._requestId){isResponse&&this.onerror?.(new Error(`Received a response for an unknown request id: ${String(message.id)}`));return}if(isResponse){if(this._terminalDelivered)return;this._terminalDelivered=!0;let errorCode=isJSONRPCErrorResponse(message)?message.error.code:void 0,ladderStatus=errorCode!==void 0&&(this._dispatchWindowOpen||errorCode===ProtocolErrorCode.MissingRequiredClientCapability)?LADDER_ERROR_HTTP_STATUS[errorCode]:void 0;if(ladderStatus!==void 0&&this._sse===void 0){this.settleResponse(Response.json(message,{status:ladderStatus,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>{this.close()});return}if(this._sse!==void 0||this._responseMode==="sse"){this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(message),this.finalizeStream();return}this.settleResponse(Response.json(message,{status:200,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>{this.close()});return}this._responseMode!=="json"&&(this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(message))}writeCommentFrame(comment){if(this._closed||this._sse===void 0||this._sse.closed)return;let frame=comment.split(`
72
+ `)),open2.add(teardown)},cancel(){teardown(!1)}});if(signal!==void 0)if(signal.aborted)teardown(!1);else{let onAbort=()=>teardown(!1);signal.addEventListener("abort",onAbort,{once:!0}),abortCleanup=()=>signal.removeEventListener("abort",onAbort)}return new Response(readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}return{serve,closeAll(){for(let teardown of open2)teardown(!0)},get openCount(){return open2.size}}}function comparableResource(value){let text2=String(value),hash=text2.indexOf("#");return(hash===-1?text2:text2.slice(0,hash)).replace(/\/$/,"")}function sameResource(reported,expected){return reported?comparableResource(reported)===comparableResource(expected):!1}function headerQuotedValue(value){return value.replaceAll(/[\\"]/g,String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g," ")}function buildWwwAuthenticateHeader(errorCode,description,requiredScopes,resourceMetadataUrl){let header=`Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`;return requiredScopes.length>0&&(header+=`, scope="${headerQuotedValue(requiredScopes.join(" "))}"`),resourceMetadataUrl&&(header+=`, resource_metadata="${headerQuotedValue(resourceMetadataUrl)}"`),header}async function verifyBearerToken(authorizationHeader,options){let{verifier,requiredScopes=[],expectedResource}=options;if(!authorizationHeader)throw new OAuthError(OAuthErrorCode.InvalidToken,"Missing Authorization header");let[type,token]=authorizationHeader.split(" ");if(type?.toLowerCase()!=="bearer"||!token)throw new OAuthError(OAuthErrorCode.InvalidToken,"Invalid Authorization header format, expected 'Bearer TOKEN'");let authInfo=await verifier.verifyAccessToken(token);if(expectedResource!==void 0&&!sameResource(authInfo.resource,expectedResource))throw new OAuthError(OAuthErrorCode.InvalidToken,"Token was not issued for this resource");if(requiredScopes.length>0&&!requiredScopes.every(scope=>authInfo.scopes.includes(scope)))throw new OAuthError(OAuthErrorCode.InsufficientScope,"Insufficient scope");if(typeof authInfo.expiresAt!="number"||Number.isNaN(authInfo.expiresAt))throw new OAuthError(OAuthErrorCode.InvalidToken,"Token has no expiration time");if(authInfo.expiresAt<Date.now()/1e3)throw new OAuthError(OAuthErrorCode.InvalidToken,"Token has expired");return options.resourceMetadataUrl!==void 0&&authInfo.resourceMetadataUrl===void 0?{...authInfo,resourceMetadataUrl:options.resourceMetadataUrl}:authInfo}function bearerAuthChallengeResponse(error3,options){let{requiredScopes=[],resourceMetadataUrl}=options??{};if(!(error3 instanceof OAuthError)){let serverError=new OAuthError(OAuthErrorCode.ServerError,"Internal Server Error");return Response.json(serverError.toResponseObject(),{status:500})}switch(error3.code){case OAuthErrorCode.InvalidToken:{let challenge=buildWwwAuthenticateHeader(error3.code,error3.message,requiredScopes,resourceMetadataUrl);return Response.json(error3.toResponseObject(),{status:401,headers:{"WWW-Authenticate":challenge}})}case OAuthErrorCode.InsufficientScope:{let challenge=buildWwwAuthenticateHeader(error3.code,error3.message,requiredScopes,resourceMetadataUrl);return Response.json(error3.toResponseObject(),{status:403,headers:{"WWW-Authenticate":challenge}})}case OAuthErrorCode.ServerError:return Response.json(error3.toResponseObject(),{status:500});default:return Response.json(error3.toResponseObject(),{status:400})}}function checkIssuerUrl(issuer,allowInsecure){if(issuer.protocol!=="https:"&&issuer.hostname!=="localhost"&&issuer.hostname!=="127.0.0.1"&&!allowInsecure)throw new Error("Issuer URL must be HTTPS");if(issuer.hash)throw new Error(`Issuer URL must not have a fragment: ${issuer}`);if(issuer.search)throw new Error(`Issuer URL must not have a query string: ${issuer}`)}function buildOAuthProtectedResourceMetadata(options){return checkIssuerUrl(new URL(options.oauthMetadata.issuer),options.dangerouslyAllowInsecureIssuerUrl),{resource:options.resourceServerUrl.href,authorization_servers:[options.oauthMetadata.issuer],scopes_supported:options.scopesSupported,resource_name:options.resourceName,resource_documentation:options.serviceDocumentationUrl?.href}}function getOAuthProtectedResourceMetadataUrl(serverUrl){let metadataUrl=new URL(serverUrl);return metadataUrl.pathname=protectedResourceMetadataPath(serverUrl),metadataUrl.hash="",metadataUrl.href}function protectedResourceMetadataPath(resourceServerUrl){let rsPath=stripTrailingSlash(resourceServerUrl.pathname);return`/.well-known/oauth-protected-resource${rsPath==="/"?"":rsPath}`}function stripTrailingSlash(path){return path.length>1&&path.endsWith("/")?path.slice(0,-1):path}function metadataDocumentResponse(request,metadata){if(request.method==="OPTIONS"){let requestedHeaders=request.headers.get("access-control-request-headers");return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":ALLOWED_METHODS,...requestedHeaders===null?{}:{"Access-Control-Allow-Headers":requestedHeaders,Vary:"Access-Control-Request-Headers"}}})}if(request.method!=="GET"&&request.method!=="HEAD"){let error3=new OAuthError(OAuthErrorCode.MethodNotAllowed,`The method ${request.method} is not allowed for this endpoint`);return Response.json(error3.toResponseObject(),{status:405,headers:{Allow:ALLOWED_METHODS,"Access-Control-Allow-Origin":"*"}})}let response=Response.json(metadata,{headers:{"Access-Control-Allow-Origin":"*"}});return request.method==="HEAD"?new Response(null,{status:response.status,headers:response.headers}):response}function oauthMetadataResponse(request,options){let requestPath=stripTrailingSlash(new URL(request.url).pathname);if(requestPath===protectedResourceMetadataPath(options.resourceServerUrl))return metadataDocumentResponse(request,buildOAuthProtectedResourceMetadata(options));if(requestPath==="/.well-known/oauth-authorization-server")return buildOAuthProtectedResourceMetadata(options),metadataDocumentResponse(request,options.oauthMetadata)}function supportsScopeChallengeResolver(transport){return typeof transport=="object"&&transport!==null&&"setScopeChallengeResolver"in transport&&typeof transport.setScopeChallengeResolver=="function"}function assertScope(scope,location){if(typeof scope!="string"||!/^[\u0021\u0023-\u005B\u005D-\u007E]+$/.test(scope))throw new TypeError(`${location} must satisfy the OAuth scope-token grammar`)}function validateScopeChallenge(challenge){if(challenge===null||typeof challenge!="object"||!Array.isArray(challenge.scopes)||challenge.scopes.length===0)throw new TypeError("scope challenge must contain at least one scope");for(let[index,scope]of challenge.scopes.entries())assertScope(scope,`scope challenge scopes[${index}]`);if(challenge.errorDescription!==void 0&&typeof challenge.errorDescription!="string")throw new TypeError("scope challenge errorDescription must be a string");if(challenge.errorDescription!==void 0&&!/^[\u0020-\u0021\u0023-\u005B\u005D-\u007E]+$/.test(challenge.errorDescription))throw new TypeError("scope challenge errorDescription must satisfy the RFC 6750 error-description grammar");return challenge}async function findScopeChallenge(requests,authInfo,resolve){for(let request of requests){let challenge=await resolve({request,...authInfo!==void 0&&{authInfo}});if(challenge!==void 0)return validateScopeChallenge(challenge)}}function scopeChallengeResourceMetadataUrl(authInfo){if(authInfo?.resourceMetadataUrl!==void 0)return authInfo.resourceMetadataUrl;if(authInfo?.resource?.protocol==="https:"||authInfo?.resource?.protocol==="http:")return getOAuthProtectedResourceMetadataUrl(authInfo.resource)}function createScopeChallengeResponse(challenge,resourceMetadataUrl){return bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InsufficientScope,challenge.errorDescription??"Insufficient scope"),{requiredScopes:[...challenge.scopes],resourceMetadataUrl})}function resolveLegacyShimOptions(options){if(options?.maxRounds!==void 0&&(!Number.isInteger(options.maxRounds)||options.maxRounds<1))throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`);if(options?.roundTimeoutMs!==void 0&&(!Number.isFinite(options.roundTimeoutMs)||options.roundTimeoutMs<=0))throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`);return{maxRounds:options?.maxRounds??DEFAULT_LEGACY_SHIM_MAX_ROUNDS,roundTimeoutMs:options?.roundTimeoutMs??DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS,legacyShim:options?.legacyShim??!0}}function coerceEmbeddedInputRequest(method,key,entry){if(entry===null||typeof entry!="object"||typeof entry.method!="string")throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let embedded=entry,required2=requiredClientCapabilitiesForInputRequest(embedded);if(required2===void 0)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded,required:required2}}function syntheticElicitationId(){let webCrypto=globalThis.crypto;if(webCrypto?.randomUUID!==void 0)return webCrypto.randomUUID();let bytes=new Uint8Array(16);webCrypto.getRandomValues(bytes),bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[...bytes].map(byte=>byte.toString(16).padStart(2,"0")).join("");return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function legacyShimFailure(method,message){if(method==="tools/call")return{content:[{type:"text",text:message}],isError:!0};throw new ProtocolError(ProtocolErrorCode.InternalError,message)}function seedClientIdentityFromEnvelope(server,identity2){writeClientIdentity(server,identity2)}function installModernOnlyHandlers(server,servedModernVersions){installDiscoverHandler(server,servedModernVersions)}function serverIdentityOf(server){return readServerIdentity(server)}function discoverAdvertisedCapabilities(capabilities){return{...capabilities}}function toolInputElementCount(value,max){let count=0,stack=[value];for(;stack.length>0;){let node2=stack.pop();if(!(node2===null||typeof node2!="object"))if(Array.isArray(node2))for(let child of node2){if(++count>max)return count;child!==null&&typeof child=="object"&&stack.push(child)}else for(let key in node2){if(!Object.prototype.hasOwnProperty.call(node2,key))continue;if(++count>max)return count;let child=node2[key];child!==null&&typeof child=="object"&&stack.push(child)}}return count}function resolveMaxToolInputElements(value){if(!(value===void 0||value===1/0)){if(typeof value!="number"||Number.isNaN(value)||value<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`);return value}}function createToolExecutor(inputSchema2,handler){if(inputSchema2){let callback$1=handler;return async(args,ctx)=>callback$1(args,ctx)}let callback=handler;return async(_args,ctx)=>callback(ctx)}function convertListedInputSchema(name,inputSchema2){let json=standardSchemaToJsonSchema(inputSchema2,"input"),scan=scanXMcpHeaderDeclarations(json);return scan.valid||console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`),json}function convertOutputSchemaJson(outputSchema2){if(outputSchema2!==void 0)try{return standardSchemaToJsonSchema(outputSchema2,"output")}catch{return}}function createPromptHandler(name,argsSchema,callback){if(argsSchema){let typedCallback=callback;return async(args,ctx)=>{let parseResult=await validateStandardSchema(argsSchema,args??{});if(!parseResult.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid arguments for prompt ${name}: ${parseResult.error}`);return typedCallback(parseResult.data,ctx)}}else{let typedCallback=callback;return async(_args,ctx)=>typedCallback(ctx)}}function createCompletionResult(suggestions){return{completion:{values:suggestions.map(String).slice(0,100),total:suggestions.length,hasMore:suggestions.length>100}}}function getSchemaShape(schema2){let candidate=schema2;if(candidate.shape&&typeof candidate.shape=="object")return candidate.shape}function isOptionalSchema(schema2){return schema2?.type==="optional"}function unwrapOptionalSchema(schema2){return isOptionalSchema(schema2)?schema2.def?.innerType??schema2:schema2}var COMPLETABLE_SYMBOL,DEFAULT_SSE_KEEP_ALIVE_MS,MAX_TIMER_DELAY_MS,InMemoryServerEventBus,DEFAULT_MAX_SUBSCRIPTIONS,ALLOWED_METHODS,DEFAULT_LEGACY_SHIM_MAX_ROUNDS,DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS,LegacyInputRequiredShim,INPUT_REQUIRED_CAPABLE_METHODS,writeClientIdentity,installDiscoverHandler,readServerIdentity,Server,McpServer,ResourceTemplate,EMPTY_OBJECT_JSON_SCHEMA,EMPTY_COMPLETION_RESULT,init_mcp_DIH4cS6P=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/mcp-DIH4cS6P.mjs"(){"use strict";init_src_Cqbh3MYc();init_shimsNode();COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");DEFAULT_SSE_KEEP_ALIVE_MS=15e3,MAX_TIMER_DELAY_MS=2**31-1;InMemoryServerEventBus=class{_listeners=new Set;constructor(onerror){this.onerror=onerror}publish(event){for(let listener of this._listeners)try{listener(event)}catch(error3){this.onerror?.(error3 instanceof Error?error3:new Error(String(error3)))}}subscribe(listener){this._listeners.add(listener);let live=!0;return()=>{live&&(live=!1,this._listeners.delete(listener))}}get listenerCount(){return this._listeners.size}};DEFAULT_MAX_SUBSCRIPTIONS=1024;ALLOWED_METHODS="GET, HEAD, OPTIONS";DEFAULT_LEGACY_SHIM_MAX_ROUNDS=8,DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS=6e5;LegacyInputRequiredShim=class{constructor(_host){this._host=_host}async fulfill(method,handler,request,ctx,firstResult){let{maxRounds,roundTimeoutMs}=this._host,outerSignal=ctx.mcpReq.signal,current=firstResult,round=0;for(;;){if(round+=1,round>maxRounds)return legacyShimFailure(method,inputRequiredRoundsExceededMessage(method,maxRounds));let inputRequests=current.inputRequests,hasInputRequests=inputRequests!=null&&Object.keys(inputRequests).length>0,requestState=typeof current.requestState=="string"?current.requestState:void 0;if(!hasInputRequests&&requestState===void 0)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let responses;if(hasInputRequests){let declared=this._host.resolvedClientCapabilities(ctx),coerced=[];for(let[key,entry]of Object.entries(inputRequests)){let{embedded,required:required2}=coerceEmbeddedInputRequest(method,key,entry);if(embedded.method!=="roots/list"&&embedded.params===void 0)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`);if(missingClientCapabilities(required2,declared)!==void 0)return legacyShimFailure(method,`Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared===void 0?" (no client capabilities are available on this connection \u2014 per-request legacy serving cannot receive server-to-client requests)":""}`);coerced.push([key,embedded])}let roundAbort=linkedRoundAbort(outerSignal);try{let legOptions={relatedRequestId:ctx.mcpReq.id,timeout:roundTimeoutMs,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:roundAbort.signal},fulfilled=await Promise.all(coerced.map(async([key,embedded])=>{try{return[key,await this._dispatchLeg(embedded,legOptions)]}catch(error3){throw roundAbort.abort(error3),error3}}));responses=Object.fromEntries(fulfilled)}catch(error3){if(outerSignal.aborted)throw error3;return legacyShimFailure(method,`Fulfilling input required by '${method}' failed: ${error3 instanceof Error?error3.message:String(error3)}`)}finally{roundAbort.dispose()}}else await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS,outerSignal);let ctxNext={...ctx,mcpReq:{...ctx.mcpReq,inputResponses:responses,droppedInputResponseKeys:void 0,requestState:requestStateAccessor(requestState)}};if(requestState!==void 0){let decoded=await this._host.verifyRequestState(requestState,ctxNext,method);decoded!==void 0&&(ctxNext=withRequestStateValue(ctxNext,decoded))}let next=await handler(request,ctxNext);if(!isInputRequiredResult(next))return next;current=next}}async _dispatchLeg(embedded,options){switch(embedded.method){case"elicitation/create":{let params=embedded.params;return params.mode==="url"&&params.elicitationId===void 0&&(params={...params,elicitationId:syntheticElicitationId()}),await this._host.sendElicitation(params,options)}case"sampling/createMessage":return await this._host.sendSampling(embedded.params,options);case"roots/list":return await this._host.listRoots(embedded.params,options)}}},INPUT_REQUIRED_CAPABLE_METHODS=new Set(["tools/call","prompts/get","resources/read"]);Server=class extends Protocol{_clientCapabilities;_clientVersion;static{writeClientIdentity=(server,identity2)=>{identity2.clientCapabilities!==void 0&&(server._clientCapabilities=identity2.clientCapabilities),identity2.clientInfo!==void 0&&(server._clientVersion=identity2.clientInfo)},installDiscoverHandler=(server,servedModernVersions)=>{let missing=servedModernVersions.filter(version2=>!server._supportedProtocolVersions.includes(version2));missing.length>0&&(server._supportedProtocolVersions=[...server._supportedProtocolVersions,...missing]),server.setRequestHandler("server/discover",()=>server._ondiscover())},readServerIdentity=server=>server._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new LegacyInputRequiredShim({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:ctx=>this._inputRequestCapabilityView(ctx),verifyRequestState:(state,ctx,method)=>this._verifyRequestState(state,ctx,method),sendElicitation:(params,options)=>this._sendElicitationLeg(params,options,{validateAcceptedContent:!1}),sendSampling:(params,options)=>this.createMessage(params,options),listRoots:(params,options)=>this.listRoots(params,options)})}oninitialized;constructor(_serverInfo,options){if(super(options),this._serverInfo=_serverInfo,this._capabilities=options?.capabilities?{...options.capabilities}:{},this._instructions=options?.instructions,this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this._requestStateVerify=options?.requestState?.verify,this._inputRequiredServing=resolveLegacyShimOptions(options?.inputRequired),options?.cacheHints!==void 0){for(let[operation,hint]of Object.entries(options.cacheHints))hint!==void 0&&assertValidCacheHint(hint,`cacheHints['${operation}']`);this._cacheHints=options.cacheHints}this.setRequestHandler("initialize",request=>this._oninitialize(request)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),modernProtocolVersions(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}async connect(transport){if(this.transport!==void 0)throw new SdkError(SdkErrorCode.AlreadyConnected,"Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.");await super.connect(transport)}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(request,ctx)=>{let transportSessionId=ctx.sessionId||ctx.http?.req?.headers.get("mcp-session-id")||void 0,{level}=request.params,parseResult=parseSchema(LoggingLevelSchema,level);return parseResult.success&&this._loggingLevels.set(transportSessionId,parseResult.data),{}})}buildContext(ctx,transportInfo){let hasHttpInfo=ctx.http||transportInfo?.request||transportInfo?.closeSSEStream||transportInfo?.closeStandaloneSSEStream;return{...ctx,mcpReq:{...ctx.mcpReq,log:(level,data,logger)=>{if(!this._capabilities.logging)return Promise.resolve();let threshold;if(this._servedModernEra()){if(threshold=ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY],threshold===void 0)return Promise.resolve()}else threshold=this._loggingLevels.get(ctx.sessionId)??this._loggingLevels.get(void 0);return threshold!==void 0&&this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(threshold)?Promise.resolve():ctx.mcpReq.notify({method:"notifications/message",params:{level,data,logger}})},elicitInput:(params,options)=>this.elicitInput(params,options),requestSampling:(params,options)=>this.createMessage(params,options)},http:hasHttpInfo?{...ctx.http,req:transportInfo?.request,closeSSE:transportInfo?.closeSSEStream,closeStandaloneSSE:transportInfo?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index)=>[level,index]));isMessageIgnored=(level,sessionId)=>{let currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):!1};registerCapabilities(capabilities){if(this.transport)throw new SdkError(SdkErrorCode.AlreadyConnected,"Cannot register capabilities after connecting to transport");let hadLogging=!!this._capabilities.logging;this._capabilities=mergeCapabilities(this._capabilities,capabilities),!hadLogging&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(method,handler){if(method!=="tools/call"){let cacheHint=this._cacheHints?.[method],isInputRequiredCapable=INPUT_REQUIRED_CAPABLE_METHODS.has(method);return cacheHint===void 0&&!isInputRequiredCapable?async(request,ctx)=>{let result=await handler(request,ctx);if(isInputRequiredResult(result))throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return result}:async(request,ctx)=>{let result=isInputRequiredCapable?await this._invokeInputRequiredCapableHandler(method,handler,request,ctx):await handler(request,ctx);if(isInputRequiredResult(result)){if(!isInputRequiredCapable)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return result}return cacheHint===void 0?result:attachCacheHintFallback(result,cacheHint)}}return async(request,ctx)=>{let codec=codecForVersion(this._negotiatedProtocolVersion),validatedRequest=codec.validateRequest("tools/call",request);if(!validatedRequest.ok)throw new ProtocolError(validatedRequest.reason==="not-in-era"?ProtocolErrorCode.InternalError:ProtocolErrorCode.InvalidParams,validatedRequest.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${validatedRequest.message}`);let result=await this._invokeInputRequiredCapableHandler("tools/call",handler,request,ctx);if(isInputRequiredResult(result))return result;let normalizedResult=normalizeContentlessToolResult(result),validationResult=codec.validateResult("tools/call",normalizedResult);if(!validationResult.ok)throw new ProtocolError(validationResult.reason==="not-in-era"?ProtocolErrorCode.InternalError:ProtocolErrorCode.InvalidParams,validationResult.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${validationResult.message}`);return validationResult.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&isModernProtocolVersion(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(method,handler,request,ctx){let servedModern=this._servedModernEra(),rawRequestState=ctx.mcpReq.requestState();if(rawRequestState!==void 0&&typeof rawRequestState!="string")throw new ProtocolError(ProtocolErrorCode.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let ctxForHandler=ctx;if(typeof rawRequestState=="string"){let decoded=await this._verifyRequestState(rawRequestState,ctx,method);decoded!==void 0&&(ctxForHandler=withRequestStateValue(ctx,decoded))}let result;try{result=await handler(request,ctxForHandler)}catch(error3){throw error3 instanceof ProtocolError&&error3.code===ProtocolErrorCode.UrlElicitationRequired&&servedModern?new ProtocolError(ProtocolErrorCode.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { \u2026: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):error3}if(!isInputRequiredResult(result))return result;if(!servedModern){if(!this._inputRequiredServing.legacyShim)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(method,handler,request,ctxForHandler,result)}let inputRequests=result.inputRequests,hasInputRequests=inputRequests!=null&&Object.keys(inputRequests).length>0,hasRequestState=typeof result.requestState=="string";if(!hasInputRequests&&!hasRequestState)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(hasInputRequests){let declared=this._inputRequestCapabilityView(ctx);for(let[key,entry]of Object.entries(inputRequests)){let{embedded,required:required2}=coerceEmbeddedInputRequest(method,key,entry),missing=missingClientCapabilities(required2,declared);if(missing!==void 0)throw new MissingRequiredClientCapabilityError({requiredCapabilities:missing},`Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`)}}return result}async _verifyRequestState(state,ctx,method){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(state,ctx)}catch(error3){throw this.onerror?.(new Error(`requestState verification rejected ${method}: ${error3 instanceof Error?error3.message:String(error3)}`)),new ProtocolError(ProtocolErrorCode.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(ctx){return this._servedModernEra()?ctx.mcpReq.envelope?.[CLIENT_CAPABILITIES_META_KEY]:this._clientCapabilities}_assertPushApiInServedEra(method){if(this._servedModernEra())throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead \u2014 the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method,era:"2026-07-28"})}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support sampling (required for ${method})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support elicitation (required for ${method})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support listing roots (required for ${method})`);break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support logging (required for ${method})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support notifying about resources (required for ${method})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${method})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${method})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support URL elicitation (required for ${method})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){switch(method){case"completion/complete":if(!this._capabilities.completions)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support completions (required for ${method})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support resources (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support tools (required for ${method})`);break;case"ping":case"initialize":break}}async _oninitialize(request){let requestedVersion=request.params.protocolVersion;this._clientCapabilities=request.params.capabilities,this._clientVersion=request.params.clientInfo;let legacyVersions=legacyProtocolVersions(this._supportedProtocolVersions),protocolVersion=legacyVersions.includes(requestedVersion)?requestedVersion:legacyVersions[0]??LATEST_PROTOCOL_VERSION;return this._negotiatedProtocolVersion=protocolVersion,this.transport?.setProtocolVersion?.(protocolVersion),{protocolVersion,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:modernProtocolVersions(this._supportedProtocolVersions),capabilities:discoverAdvertisedCapabilities(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(result,advertisedOutputSchema){return this._wireCodec().projectCallToolResult(result,advertisedOutputSchema)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(params,options){if(this._assertPushApiInServedEra("sampling/createMessage"),(params.tools||params.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages.at(-1),lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c=>c.type==="tool_result"),previousMessage=params.messages.length>1?params.messages.at(-2):void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c=>c.type==="tool_use");if(hasToolResults){if(lastContent.some(c=>c.type!=="tool_result"))throw new ProtocolError(ProtocolErrorCode.InvalidParams,"The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new ProtocolError(ProtocolErrorCode.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c=>c.type==="tool_use").map(c=>c.id)),toolResultIds=new Set(lastContent.filter(c=>c.type==="tool_result").map(c=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new ProtocolError(ProtocolErrorCode.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let hasTools=!!(params.tools||params.toolChoice),wide=await this.request({method:"sampling/createMessage",params},options),outcome=this._wireCodec().samplingResultVariant(hasTools,wide);if(!outcome.ok)throw new SdkError(SdkErrorCode.InvalidResult,`Invalid sampling/createMessage result: ${outcome.reason==="invalid"?outcome.message:outcome.reason}`);return outcome.value}async elicitInput(params,options){switch(this._assertPushApiInServedEra("elicitation/create"),params.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support form elicitation.");break}return this._sendElicitationLeg(params,options)}async _sendElicitationLeg(params,options,behavior){let mode=params.mode??"form",validateAcceptedContent=behavior?.validateAcceptedContent??!0;switch(mode){case"url":{let urlParams=params;return this.request({method:"elicitation/create",params:urlParams},options)}case"form":{let formParams=params.mode==="form"?params:{...params,mode:"form"},result=await this.request({method:"elicitation/create",params:formParams},options);if(validateAcceptedContent&&result.action==="accept"&&result.content&&formParams.requestedSchema)try{let validationResult=this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);if(!validationResult.valid)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}catch(error3){throw error3 instanceof ProtocolError?error3:new ProtocolError(ProtocolErrorCode.InternalError,`Error validating elicitation response: ${error3 instanceof Error?error3.message:String(error3)}`)}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params},options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging&&!this.isMessageIgnored(params.level,sessionId))return this.notification({method:"notifications/message",params})}async sendResourceUpdated(params){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"})}};McpServer=class{server;_maxToolInputElements;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(name){let tool=this._registeredTools[name];if(!(tool===void 0||!tool.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,name))return this._toolInputSchemaJson[name];if(tool.inputSchema===void 0)return EMPTY_OBJECT_JSON_SCHEMA;try{let json=standardSchemaToJsonSchema(tool.inputSchema,"input");return this._toolInputSchemaJson[name]=json,json}catch{return}}}constructor(serverInfo,options){this.server=new Server(serverInfo,options),this._maxToolInputElements=resolveMaxToolInputElements(options?.maxToolInputElements),options?.capabilities?.tools&&this.setToolRequestHandlers(),options?.capabilities?.resources&&this.setResourceRequestHandlers(),options?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(transport){return supportsScopeChallengeResolver(transport)&&transport.setScopeChallengeResolver(context=>this.resolveScopeChallenge(context)),await this.server.connect(transport)}async close(){await this.server.close()}resolveScopeChallenge=context=>{switch(context.request.method){case"tools/call":{let toolName=context.request.params?.name;if(typeof toolName!="string")return;let tool=this._registeredTools[toolName];return tool===void 0||!tool.enabled?void 0:tool.scopeChallenge?.(context)}case"resources/read":{let resourceUri=context.request.params?.uri;if(typeof resourceUri!="string")return;let uri;try{uri=new URL(resourceUri)}catch{return}let resource2=this._registeredResources[uri.toString()];if(resource2!==void 0)return resource2.enabled?resource2.scopeChallenge?.(context):void 0;for(let template of Object.values(this._registeredResourceTemplates))if(template.resourceTemplate.uriTemplate.match(uri.toString()))return template.enabled?template.scopeChallenge?.(context):void 0;return}case"prompts/get":{let promptName=context.request.params?.name;if(typeof promptName!="string")return;let prompt=this._registeredPrompts[promptName];return prompt===void 0||!prompt.enabled?void 0:prompt.scopeChallenge?.(context)}default:return}};_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,tool])=>tool.enabled).map(([name,tool])=>{let toolDefinition={name,title:tool.title,description:tool.description,inputSchema:tool.inputSchema?convertListedInputSchema(name,tool.inputSchema):EMPTY_OBJECT_JSON_SCHEMA,annotations:tool.annotations,icons:tool.icons,execution:tool.execution,_meta:tool._meta};return tool.outputSchema&&(toolDefinition.outputSchema=standardSchemaToJsonSchema(tool.outputSchema,"output")),toolDefinition})})),this.server.setRequestHandler("tools/call",async(request,ctx)=>{let tool=this._registeredTools[request.params.name];if(!tool)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Tool ${request.params.name} not found`);if(!tool.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Tool ${request.params.name} disabled`);try{let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),result=await this.executeToolHandler(tool,args,ctx);return await this.validateToolOutput(tool,result,request.params.name),isInputRequiredResult(result)?result:this.server.projectCallToolResult(result,tool.outputSchemaJson)}catch(error3){if(error3 instanceof ProtocolError&&error3.code===ProtocolErrorCode.UrlElicitationRequired)throw error3;return this.createToolError(error3 instanceof Error?error3.message:String(error3))}}),this._toolHandlersInitialized=!0)}createToolError(errorMessage){return{content:[{type:"text",text:errorMessage}],isError:!0}}async validateToolInput(tool,args,toolName){if(this._maxToolInputElements!==void 0&&toolInputElementCount(args,this._maxToolInputElements)>this._maxToolInputElements)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!tool.inputSchema)return;let parseResult=await validateStandardSchema(tool.inputSchema,args??{});if(!parseResult.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`);return parseResult.data}async validateToolOutput(tool,result,toolName){if(!tool.outputSchema||isInputRequiredResult(result)||result.isError)return;if(result.structuredContent===void 0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);let parseResult=await validateStandardSchema(tool.outputSchema,result.structuredContent);if(!parseResult.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`)}async executeToolHandler(tool,args,ctx){return tool.executor(args,ctx)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async request=>{switch(request.params.ref.type){case"ref/prompt":return assertCompleteRequestPrompt(request),this.handlePromptCompletion(request,request.params.ref);case"ref/resource":return assertCompleteRequestResourceTemplate(request),this.handleResourceCompletion(request,request.params.ref);default:throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid completion reference: ${request.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(request,ref){let prompt=this._registeredPrompts[ref.name];if(!prompt)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${ref.name} not found`);if(!prompt.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${ref.name} disabled`);if(!prompt.argsSchema)return EMPTY_COMPLETION_RESULT;let field=unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]);if(!isCompletable(field))return EMPTY_COMPLETION_RESULT;let completer=getCompleter(field);return completer?createCompletionResult(await completer(request.params.argument.value,request.params.context)):EMPTY_COMPLETION_RESULT}async handleResourceCompletion(request,ref){let template=Object.values(this._registeredResourceTemplates).find(t=>t.resourceTemplate.uriTemplate.toString()===ref.uri);if(!template){if(this._registeredResources[ref.uri])return EMPTY_COMPLETION_RESULT;throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource template ${request.params.ref.uri} not found`)}let completer=template.resourceTemplate.completeCallback(request.params.argument.name);return completer?createCompletionResult(await completer(request.params.argument.value,request.params.context)):EMPTY_COMPLETION_RESULT}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler("resources/list",async(_request,ctx)=>{let resources=Object.entries(this._registeredResources).filter(([_,resource2])=>resource2.enabled).map(([uri,resource2])=>({uri,name:resource2.name,...resource2.metadata})),templateResources=[];for(let template of Object.values(this._registeredResourceTemplates)){if(!template.resourceTemplate.listCallback)continue;let result=await template.resourceTemplate.listCallback(ctx);for(let resource2 of result.resources)templateResources.push({...template.metadata,...resource2})}return{resources:[...resources,...templateResources]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([name,template])=>({name,uriTemplate:template.resourceTemplate.uriTemplate.toString(),...template.metadata}))})),this.server.setRequestHandler("resources/read",async(request,ctx)=>{let uri;try{uri=new URL(request.params.uri)}catch{throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource URI ${request.params.uri} is invalid`,{uri:request.params.uri,reason:"invalid_uri"})}let resource2=this._registeredResources[uri.toString()];if(resource2){if(!resource2.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource ${uri} disabled`);return attachCacheHintFallback(await resource2.readCallback(uri,ctx),resource2.cacheHint)}for(let template of Object.values(this._registeredResourceTemplates)){let variables=template.resourceTemplate.uriTemplate.match(uri.toString());if(variables){if(!template.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource template ${template.resourceTemplate.uriTemplate} disabled`);return attachCacheHintFallback(await template.readCallback(uri,variables,ctx),template.cacheHint)}}throw new ResourceNotFoundError(request.params.uri)}),this._resourceHandlersInitialized=!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,prompt])=>prompt.enabled).map(([name,prompt])=>({name,title:prompt.title,description:prompt.description,arguments:prompt.argsSchema?promptArgumentsFromStandardSchema(prompt.argsSchema):void 0,icons:prompt.icons,_meta:prompt._meta}))})),this.server.setRequestHandler("prompts/get",async(request,ctx)=>{let prompt=this._registeredPrompts[request.params.name];if(!prompt)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${request.params.name} not found`);if(!prompt.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${request.params.name} disabled`);return prompt.handler(request.params.arguments,ctx)}),this._promptHandlersInitialized=!0)}registerResource(name,uriOrTemplate,config2,readCallback){let{cacheHint,scopeChallenge,...resourceMetadata}=config2,metadata=resourceMetadata;if(cacheHint!==void 0&&assertValidCacheHint(cacheHint,`resource ${name}`),typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,config2.title,uriOrTemplate,metadata,scopeChallenge,readCallback);return cacheHint!==void 0&&(registeredResource.cacheHint=cacheHint),this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,config2.title,uriOrTemplate,metadata,scopeChallenge,readCallback);return cacheHint!==void 0&&(registeredResourceTemplate.cacheHint=cacheHint),this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}_createRegisteredResource(name,title,uri,metadata,scopeChallenge,readCallback){let registeredResource={name,title,metadata,readCallback,scopeChallenge,enabled:!0,disable:()=>registeredResource.update({enabled:!1}),enable:()=>registeredResource.update({enabled:!0}),remove:()=>registeredResource.update({uri:null}),update:updates=>{updates.uri!==void 0&&updates.uri!==uri&&(delete this._registeredResources[uri],updates.uri&&(this._registeredResources[updates.uri]=registeredResource)),updates.name!==void 0&&(registeredResource.name=updates.name),updates.title!==void 0&&(registeredResource.title=updates.title),updates.metadata!==void 0&&(registeredResource.metadata=updates.metadata),updates.callback!==void 0&&(registeredResource.readCallback=updates.callback),updates.scopeChallenge!==void 0&&(registeredResource.scopeChallenge=updates.scopeChallenge===null?void 0:updates.scopeChallenge),updates.enabled!==void 0&&(registeredResource.enabled=updates.enabled),this.sendResourceListChanged()}};return this._registeredResources[uri]=registeredResource,registeredResource}_createRegisteredResourceTemplate(name,title,template,metadata,scopeChallenge,readCallback){let registeredResourceTemplate={resourceTemplate:template,title,metadata,readCallback,scopeChallenge,enabled:!0,disable:()=>registeredResourceTemplate.update({enabled:!1}),enable:()=>registeredResourceTemplate.update({enabled:!0}),remove:()=>registeredResourceTemplate.update({name:null}),update:updates=>{updates.name!==void 0&&updates.name!==name&&(delete this._registeredResourceTemplates[name],updates.name&&(this._registeredResourceTemplates[updates.name]=registeredResourceTemplate)),updates.title!==void 0&&(registeredResourceTemplate.title=updates.title),updates.template!==void 0&&(registeredResourceTemplate.resourceTemplate=updates.template),updates.metadata!==void 0&&(registeredResourceTemplate.metadata=updates.metadata),updates.callback!==void 0&&(registeredResourceTemplate.readCallback=updates.callback),updates.scopeChallenge!==void 0&&(registeredResourceTemplate.scopeChallenge=updates.scopeChallenge===null?void 0:updates.scopeChallenge),updates.enabled!==void 0&&(registeredResourceTemplate.enabled=updates.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[name]=registeredResourceTemplate;let variableNames=template.uriTemplate.variableNames;return Array.isArray(variableNames)&&variableNames.some(v=>!!template.completeCallback(v))&&this.setCompletionRequestHandler(),registeredResourceTemplate}_createRegisteredPrompt(name,title,description,argsSchema,callback,icons,scopeChallenge,_meta){let currentArgsSchema=argsSchema,currentCallback=callback,registeredPrompt={title,description,argsSchema,icons,scopeChallenge,_meta,handler:createPromptHandler(name,argsSchema,callback),enabled:!0,disable:()=>registeredPrompt.update({enabled:!1}),enable:()=>registeredPrompt.update({enabled:!0}),remove:()=>registeredPrompt.update({name:null}),update:updates=>{updates.name!==void 0&&updates.name!==name&&(delete this._registeredPrompts[name],updates.name&&(this._registeredPrompts[updates.name]=registeredPrompt)),updates.title!==void 0&&(registeredPrompt.title=updates.title),updates.description!==void 0&&(registeredPrompt.description=updates.description),updates.icons!==void 0&&(registeredPrompt.icons=updates.icons),updates.scopeChallenge!==void 0&&(registeredPrompt.scopeChallenge=updates.scopeChallenge===null?void 0:updates.scopeChallenge),updates._meta!==void 0&&(registeredPrompt._meta=updates._meta);let needsHandlerRegen=!1;updates.argsSchema!==void 0&&(registeredPrompt.argsSchema=updates.argsSchema,currentArgsSchema=updates.argsSchema,needsHandlerRegen=!0),updates.callback!==void 0&&(currentCallback=updates.callback,needsHandlerRegen=!0),needsHandlerRegen&&(registeredPrompt.handler=createPromptHandler(name,currentArgsSchema,currentCallback)),updates.enabled!==void 0&&(registeredPrompt.enabled=updates.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[name]=registeredPrompt,argsSchema){let shape=getSchemaShape(argsSchema);shape&&Object.values(shape).some(field=>isCompletable(unwrapOptionalSchema(field)))&&this.setCompletionRequestHandler()}return registeredPrompt}_createRegisteredTool(name,title,description,inputSchema2,outputSchema2,annotations,icons,execution,scopeChallenge,_meta,handler){validateAndWarnToolName(name);let currentHandler=handler,outputSchemaJson,registeredTool={title,description,inputSchema:inputSchema2,outputSchema:outputSchema2,get outputSchemaJson(){return outputSchemaJson??=convertOutputSchemaJson(registeredTool.outputSchema)},set outputSchemaJson(value){outputSchemaJson=value},annotations,icons,execution,scopeChallenge,_meta,handler,executor:createToolExecutor(inputSchema2,handler),enabled:!0,disable:()=>registeredTool.update({enabled:!1}),enable:()=>registeredTool.update({enabled:!0}),remove:()=>registeredTool.update({name:null}),update:updates=>{updates.name!==void 0&&updates.name!==name&&(typeof updates.name=="string"&&validateAndWarnToolName(updates.name),delete this._registeredTools[name],delete this._toolInputSchemaJson[name],updates.name&&(delete this._toolInputSchemaJson[updates.name],this._registeredTools[updates.name]=registeredTool,name=updates.name)),updates.title!==void 0&&(registeredTool.title=updates.title),updates.description!==void 0&&(registeredTool.description=updates.description);let needsExecutorRegen=!1;updates.paramsSchema!==void 0&&(registeredTool.inputSchema=updates.paramsSchema,delete this._toolInputSchemaJson[name],needsExecutorRegen=!0),updates.callback!==void 0&&(registeredTool.handler=updates.callback,currentHandler=updates.callback,needsExecutorRegen=!0),needsExecutorRegen&&(registeredTool.executor=createToolExecutor(registeredTool.inputSchema,currentHandler)),updates.outputSchema!==void 0&&(registeredTool.outputSchema=updates.outputSchema,registeredTool.outputSchemaJson=convertOutputSchemaJson(updates.outputSchema)),updates.annotations!==void 0&&(registeredTool.annotations=updates.annotations),updates.icons!==void 0&&(registeredTool.icons=updates.icons),updates.scopeChallenge!==void 0&&(registeredTool.scopeChallenge=updates.scopeChallenge===null?void 0:updates.scopeChallenge),updates._meta!==void 0&&(registeredTool._meta=updates._meta),updates.enabled!==void 0&&(registeredTool.enabled=updates.enabled),this.sendToolListChanged()}};return this._registeredTools[name]=registeredTool,this.setToolRequestHandlers(),this.sendToolListChanged(),registeredTool}registerTool(name,config2,cb){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let{title,description,inputSchema:inputSchema2,outputSchema:outputSchema2,annotations,icons,scopeChallenge,_meta}=config2;return this._createRegisteredTool(name,title,description,normalizeRawShapeSchema(inputSchema2),normalizeRawShapeSchema(outputSchema2),annotations,icons,void 0,scopeChallenge,_meta,cb)}registerPrompt(name,config2,cb){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let{title,description,argsSchema,icons,scopeChallenge,_meta}=config2,registeredPrompt=this._createRegisteredPrompt(name,title,description,normalizeRawShapeSchema(argsSchema),cb,icons,scopeChallenge,_meta);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(params,sessionId){return this.server.sendLoggingMessage(params,sessionId)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},ResourceTemplate=class{_uriTemplate;constructor(uriTemplate,_callbacks){this._callbacks=_callbacks,this._uriTemplate=typeof uriTemplate=="string"?new UriTemplate(uriTemplate):uriTemplate}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(variable){return this._callbacks.complete?.[variable]}};EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}}}});async function invoke(server,message,ctx){let transport=new PerRequestHTTPServerTransport({classification:ctx.classification,...ctx.responseMode!==void 0&&{responseMode:ctx.responseMode},...ctx.keepAliveMs!==void 0&&{keepAliveMs:ctx.keepAliveMs}});return await server.connect(transport),transport.handleMessage(message,{...ctx.request!==void 0&&{request:ctx.request},...ctx.authInfo!==void 0&&{authInfo:ctx.authInfo}})}function requestBodyTooLargeMessage(maxBytes){return`Payload Too Large: Request body must not exceed ${maxBytes} bytes`}function resolveMaxRequestBodySize(value){if(value===void 0)return DEFAULT_MAX_REQUEST_BODY_SIZE;if(typeof value!="number"||!Number.isFinite(value)||value<=0)throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(value)}`);return value}async function readRequestBody(request,maxBytes=DEFAULT_MAX_REQUEST_BODY_SIZE){if(Number(request.headers.get("content-length"))>maxBytes)return{tooLarge:!0};if(request.body===null)return{tooLarge:!1,text:""};let reader=request.body.getReader(),decoder=new TextDecoder,received=0,text2="";try{for(;;){let{done,value}=await reader.read();if(done)break;if(received+=value.byteLength,received>maxBytes)return{tooLarge:!0};text2+=decoder.decode(value,{stream:!0})}}finally{reader.releaseLock()}return{tooLarge:!1,text:text2+decoder.decode()}}function echoableRequestId(body){if(body===null||typeof body!="object"||Array.isArray(body))return null;let{method,id}=body;return typeof method!="string"?null:typeof id=="string"||typeof id=="number"?id:null}function jsonRpcErrorResponse(httpStatus,code,message,data,id=null){return Response.json({jsonrpc:"2.0",error:{code,message,...data!==void 0&&{data}},id},{status:httpStatus})}function rejectionResponse(rejection2,id=null){return jsonRpcErrorResponse(rejection2.httpStatus,rejection2.code,rejection2.message,rejection2.data,id)}function toError(value){return value instanceof Error?value:new Error(String(value))}function internalServerErrorResponse(id=null){return jsonRpcErrorResponse(500,-32603,"Internal server error",void 0,id)}function assertNotServing(server){if(server.transport!==void 0)throw new Error("The factory returned an instance that is still serving another request. Return a new instance for each request.")}function createLegacyStatelessFallback(factory,onerror,keepAliveMs,maxRequestBodySize){return async(request,options)=>{if(request.method.toUpperCase()!=="POST")return jsonRpcErrorResponse(405,-32e3,"Method not allowed.");try{let product=await factory({era:"legacy",...options?.authInfo!==void 0&&{authInfo:options.authInfo},requestInfo:request}),transport=new WebStandardStreamableHTTPServerTransport({sessionIdGenerator:void 0,...keepAliveMs!==void 0&&{keepAliveMs},...maxRequestBodySize!==void 0&&{maxRequestBodySize}});await product.connect(transport);let teardown=()=>{transport.close().catch(()=>{}),product.close().catch(()=>{})};request.signal?.addEventListener("abort",teardown,{once:!0});let response=await transport.handleRequest(request,{...options?.authInfo!==void 0&&{authInfo:options.authInfo},...options?.parsedBody!==void 0&&{parsedBody:options.parsedBody}});if(response.body===null||mediaTypeEssence(response.headers.get("content-type"))!=="text/event-stream")return teardown(),response;let reader=response.body.getReader(),toreDown=!1,completeExchange=()=>{toreDown||(toreDown=!0,teardown())},monitoredBody=new ReadableStream({pull:async controller=>{try{let{done,value}=await reader.read();if(done){completeExchange(),controller.close();return}value!==void 0&&controller.enqueue(value)}catch(error3){completeExchange(),controller.error(error3)}},cancel:reason=>(completeExchange(),reader.cancel(reason).catch(()=>{}))});return new Response(monitoredBody,{status:response.status,statusText:response.statusText,headers:response.headers})}catch(error3){try{onerror?.(toError(error3))}catch{}return internalServerErrorResponse(echoableRequestId(options?.parsedBody))}}}function standardHeadersOf(request){return{protocolVersionHeader:request.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:request.headers.get("mcp-method")??void 0,mcpNameHeader:request.headers.get("mcp-name")??void 0}}async function classifyEntryRequest(request,providedParsedBody,needsForward=!0,maxRequestBodySize=DEFAULT_MAX_REQUEST_BODY_SIZE){let httpMethod=request.method.toUpperCase(),body,parsedBody=providedParsedBody,forwardRequest=request,unparseable=!1;if(httpMethod==="POST"){if(parsedBody===void 0){needsForward&&(forwardRequest=request.clone());let bodyText;try{let read=await readRequestBody(request,maxRequestBodySize);if(read.tooLarge)return{step:"body-too-large"};bodyText=read.text}catch{return{step:"unreadable-body"}}try{body=bodyText.length===0?void 0:JSON.parse(bodyText)}catch{unparseable=!0}!unparseable&&body!==void 0&&(parsedBody=body)}else body=parsedBody;if(unparseable||body===void 0)return{step:"no-json-body",forwardRequest}}return{step:"classified",outcome:classifyInboundRequest({httpMethod,...standardHeadersOf(request),...body!==void 0&&{body}}),body,parsedBody,forwardRequest}}function createMcpHandler(factory,options={}){let{legacy,onerror,responseMode}=options,maxRequestBodySize=resolveMaxRequestBodySize(options.maxRequestBodySize);if(typeof legacy=="function")throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let inflight=new Set,closed=!1,reportError=error3=>{try{onerror?.(error3)}catch{}},bus=options.bus??new InMemoryServerEventBus(reportError),notify=createServerNotifier(bus),listenRouter=createListenRouter({bus,maxSubscriptions:options.maxSubscriptions??DEFAULT_MAX_SUBSCRIPTIONS,keepAliveMs:options.keepAliveMs??DEFAULT_SSE_KEEP_ALIVE_MS,onerror:reportError});responseMode==="json"&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let legacyHandler=legacy==="reject"?void 0:createLegacyStatelessFallback(factory,reportError,options.keepAliveMs,maxRequestBodySize);async function serveModern(route,request,authInfo){let claimedRevision=route.classification.revision;if(claimedRevision===void 0||!SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)){let error3=new UnsupportedProtocolVersionError({supported:[...SUPPORTED_MODERN_PROTOCOL_VERSIONS],requested:claimedRevision??"unknown"});return reportError(error3),jsonRpcErrorResponse(400,error3.code,error3.message,error3.data,echoableRequestId(route.message))}let stdHeaderRejection=validateStandardRequestHeaders({httpMethod:request.method,...standardHeadersOf(request)},route);if(stdHeaderRejection!==void 0)return reportError(new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)),rejectionResponse(stdHeaderRejection,echoableRequestId(route.message));let meta2=route.messageKind==="request"?requestMetaOf(route.message.params):void 0,declaredClientCapabilities=meta2?.[CLIENT_CAPABILITIES_META_KEY];if(route.messageKind==="request"){let required2=requiredClientCapabilitiesForRequest(route.message.method);if(required2!==void 0){let missing=missingClientCapabilities(required2,declaredClientCapabilities);if(missing!==void 0){let error3=new MissingRequiredClientCapabilityError({requiredCapabilities:missing});return reportError(error3),jsonRpcErrorResponse(httpStatusForErrorCode(error3.code,"ladder"),error3.code,error3.message,error3.data,route.message.id)}}}let product=await factory({era:"modern",...authInfo!==void 0&&{authInfo},requestInfo:request}),server=product instanceof McpServer?product.server:product;if(assertNotServing(server),route.messageKind==="request"&&route.message.method==="subscriptions/listen"){let capabilities=server.getCapabilities(),serverInfo=serverIdentityOf(server);return product.close().catch(reportError),listenRouter.serve(route.message,request.signal,capabilities,serverInfo)}if(route.messageKind==="request"&&route.message.method==="tools/call"&&product instanceof McpServer){let callParams=route.message.params,toolName=typeof callParams?.name=="string"?callParams.name:void 0,inputSchema2=toolName===void 0?void 0:product.toolInputSchemaJson(toolName);if(inputSchema2!==void 0){let scan=scanXMcpHeaderDeclarations(inputSchema2);if(scan.valid&&scan.declarations.length>0){let rejection2=validateMcpParamHeaders(scan.declarations,callParams?.arguments,request.headers);if(rejection2!==void 0)return product.close().catch(reportError),reportError(new Error(`Rejected inbound request (${rejection2.cell}): ${rejection2.message}`)),rejectionResponse(rejection2,route.message.id)}}}if(route.messageKind==="request"&&product instanceof McpServer)try{let challenge=await findScopeChallenge([route.message],authInfo,context=>product.resolveScopeChallenge(context));if(challenge!==void 0)return product.close().catch(reportError),createScopeChallengeResponse(challenge,scopeChallengeResourceMetadataUrl(authInfo))}catch(error3){return product.close().catch(reportError),reportError(toError(error3)),internalServerErrorResponse(route.message.id)}assertNotServing(server),setNegotiatedProtocolVersion(server,claimedRevision),installModernOnlyHandlers(server,SUPPORTED_MODERN_PROTOCOL_VERSIONS),meta2!==void 0&&seedClientIdentityFromEnvelope(server,{clientInfo:meta2[CLIENT_INFO_META_KEY],clientCapabilities:declaredClientCapabilities});let previousOnClose=server.onclose;inflight.add(server);let onExchangeClose=()=>{inflight.delete(server),server.onclose===onExchangeClose&&(server.onclose=previousOnClose),previousOnClose?.()};server.onclose=onExchangeClose;try{let response=await invoke(product,route.message,{classification:route.classification,request,...authInfo!==void 0&&{authInfo},...responseMode!==void 0&&{responseMode},...options.keepAliveMs!==void 0&&{keepAliveMs:options.keepAliveMs}});return route.messageKind==="notification"&&queueMicrotask(()=>{server.close().catch(()=>{})}),response}catch(error3){return error3 instanceof SdkError&&error3.code===SdkErrorCode.ConnectionClosed?new Response(null,{status:499}):(await server.close().catch(()=>{}),inflight.delete(server),reportError(toError(error3)),internalServerErrorResponse(echoableRequestId(route.message)))}}async function serveLegacyRoute(route,forwardRequest,authInfo,parsedBody){if(legacyHandler!==void 0)return legacyHandler(forwardRequest,{...authInfo!==void 0&&{authInfo},...parsedBody!==void 0&&{parsedBody}});let strict=modernOnlyStrictRejection(route,SUPPORTED_MODERN_PROTOCOL_VERSIONS);return strict===void 0?new Response(null,{status:202}):(reportError(new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)),rejectionResponse(strict,echoableRequestId(parsedBody)))}async function handle(request,requestOptions){let authInfo=requestOptions?.authInfo;if(request.method.toUpperCase()==="POST"&&!isJsonContentType(request.headers.get("content-type")))return reportError(new Error("Unsupported Media Type: Content-Type must be application/json")),jsonRpcErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let classified=await classifyEntryRequest(request,requestOptions?.parsedBody,!0,maxRequestBodySize);if(classified.step==="unreadable-body")return jsonRpcErrorResponse(400,-32700,"Parse error: the request body could not be read");if(classified.step==="body-too-large")return jsonRpcErrorResponse(413,-32e3,requestBodyTooLargeMessage(maxRequestBodySize));if(classified.step==="no-json-body")return legacyHandler!==void 0?legacyHandler(classified.forwardRequest,{...authInfo!==void 0&&{authInfo}}):jsonRpcErrorResponse(400,-32700,"Parse error: the request body is not valid JSON");let{outcome,body,parsedBody,forwardRequest}=classified;try{switch(outcome.kind){case"reject":return reportError(new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)),rejectionResponse(outcome,echoableRequestId(body));case"modern":return await serveModern(outcome,request,authInfo);case"legacy":return await serveLegacyRoute(outcome,forwardRequest,authInfo,parsedBody)}}catch(error3){return reportError(toError(error3)),internalServerErrorResponse(echoableRequestId(body))}}return{fetch:async(request,requestOptions)=>{if(closed)throw new Error("This MCP handler has been closed");try{return await handle(request,requestOptions)}catch(error3){return reportError(toError(error3)),internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody))}},notify,bus,close:async()=>{closed=!0,listenRouter.closeAll();let closing=[...inflight].map(server=>server.close().catch(()=>{}));inflight.clear(),await Promise.all(closing)}}}function validateHostHeader(hostHeader,allowedHostnames){if(!hostHeader)return{ok:!1,errorCode:"missing_host",message:"Missing Host header"};let hostname;try{hostname=new URL(`http://${hostHeader}`).hostname}catch{return{ok:!1,errorCode:"invalid_host_header",message:`Invalid Host header: ${hostHeader}`,hostHeader}}return allowedHostnames.includes(hostname)?{ok:!0,hostname}:{ok:!1,errorCode:"invalid_host",message:`Invalid Host: ${hostname}`,hostHeader,hostname}}function localhostAllowedHostnames(){return["localhost","127.0.0.1","[::1]"]}function hostHeaderValidationResponse(req,allowedHostnames){let result=validateHostHeader(req.headers.get("host"),allowedHostnames);if(!result.ok)return Response.json({jsonrpc:"2.0",error:{code:-32e3,message:result.message},id:null},{status:403,headers:{"Content-Type":"application/json"}})}function validateOriginHeader(originHeader,allowedOriginHostnames){if(originHeader==null||originHeader==="")return{ok:!0};let hostname,scheme;try{let url2=new URL(originHeader);hostname=url2.hostname,scheme=url2.protocol}catch{return{ok:!1,errorCode:"invalid_origin_header",message:`Invalid Origin header: ${originHeader}`,originHeader}}return hostname===""?{ok:!1,errorCode:"invalid_origin_header",message:`Invalid Origin header: ${originHeader}`,originHeader}:!(scheme!=="http:"&&scheme!=="https:"&&allowedOriginHostnames.includes(`${scheme}//*`))&&!allowedOriginHostnames.includes(hostname)?{ok:!1,errorCode:"invalid_origin",message:`Invalid Origin: ${hostname}`,originHeader,hostname}:{ok:!0,origin:originHeader,hostname}}function localhostAllowedOrigins(){return["localhost","127.0.0.1","[::1]"]}function originValidationResponse(req,allowedOriginHostnames){let result=validateOriginHeader(req.headers.get("origin"),allowedOriginHostnames);if(!result.ok)return Response.json({jsonrpc:"2.0",error:{code:-32e3,message:result.message},id:null},{status:403,headers:{"Content-Type":"application/json"}})}function bytesToBase64Url(bytes){let bin="";for(let b of bytes)bin+=String.fromCodePoint(b);return btoa(bin).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function constantTimeTagEqual(a,b){if(a.length!==b.length)return!1;let r=0;for(let i=0;i<a.length;i++)r|=a.codePointAt(i)^b.codePointAt(i);return r===0}function base64UrlToBytes(s){let b64=s.replaceAll("-","+").replaceAll("_","/"),bin=atob(b64),bytes=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)bytes[i]=bin.codePointAt(i);return bytes}function createRequestStateCodec(options){let subtle=globalThis.crypto?.subtle;if(subtle===void 0)throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions");let keyBytes=typeof options.key=="string"?new TextEncoder().encode(options.key):Uint8Array.from(options.key);if(keyBytes.byteLength<32)throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`);let ttlSeconds=options.ttlSeconds??600;if(!Number.isFinite(ttlSeconds))throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number");let bind=options.bind,cryptoKey,importedKey=()=>cryptoKey??=subtle.importKey("raw",keyBytes,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"]),utf8=new TextEncoder,BIND_LABEL="mcp.requestState.bind:",bindTag=async value=>bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC",await importedKey(),utf8.encode(BIND_LABEL+value))).slice(0,16));return{async mint(payload,ctx){let envelope={p:payload,exp:Math.floor(Date.now()/1e3)+ttlSeconds};if(bind!==void 0){if(ctx===void 0)throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured");envelope.b=await bindTag(bind(ctx))}let body=bytesToBase64Url(utf8.encode(JSON.stringify(envelope)));return`${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC",await importedKey(),utf8.encode(PREFIX+body))))}`},async verify(state,ctx){let dot=state.lastIndexOf(".");if(!state.startsWith(PREFIX)||dot<=3)throw new Error("malformed");let body=state.slice(3,dot),macBytes;try{macBytes=base64UrlToBytes(state.slice(dot+1))}catch{throw new Error("malformed")}if(!await subtle.verify("HMAC",await importedKey(),macBytes,utf8.encode(PREFIX+body)))throw new Error("mac");let envelope;try{envelope=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(base64UrlToBytes(body)))}catch{throw new Error("malformed")}if(typeof envelope.exp!="number"||envelope.exp<Math.floor(Date.now()/1e3))throw new Error("expired");if(bind!==void 0){let expected=await bindTag(bind(ctx));if(envelope.b===void 0||!constantTimeTagEqual(envelope.b,expected))throw new Error("bind")}else if(envelope.b!==void 0)throw new Error("bind");return envelope.p}}}function fromJsonSchema2(schema2,validator){return fromJsonSchema(schema2,validator??(_defaultValidator??=new AjvJsonSchemaValidator))}var PerRequestHTTPServerTransport,DEFAULT_MAX_REQUEST_BODY_SIZE,MAX_BATCH_SIZE,WebStandardStreamableHTTPServerTransport,PREFIX,_defaultValidator,init_dist=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1_patch_hash=d174dcbb0cda204a05fc1a7fdc58b88afcdc342605224bfd8c802bcc4096fed6/node_modules/@modelcontextprotocol/server/dist/index.mjs"(){"use strict";init_mcp_DIH4cS6P();init_src_Cqbh3MYc();init_shimsNode();PerRequestHTTPServerTransport=class{onclose;onerror;onmessage;_classification;_responseMode;_started=!1;_used=!1;_closed=!1;_terminalDelivered=!1;_dispatchWindowOpen=!1;_requestId;_deferredResponse;_sse;_abortCleanup;_keepAliveMs;constructor(options){this._classification=options.classification,this._responseMode=options.responseMode??"auto",this._keepAliveMs=options.keepAliveMs??DEFAULT_SSE_KEEP_ALIVE_MS}async start(){if(this._started)throw new Error("PerRequestHTTPServerTransport is already started");this._started=!0}async handleMessage(message,extra){if(this._used)throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request");if(!this._started||this.onmessage===void 0)throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message");if(this._closed)throw new Error("PerRequestHTTPServerTransport is closed");this._used=!0;let signal=extra?.request?.signal;if(signal?.aborted)throw await this.close(),new SdkError(SdkErrorCode.ConnectionClosed,"The request was aborted before it could be handled");let messageExtra={classification:this._classification,...extra?.request!==void 0&&{request:extra.request},...extra?.authInfo!==void 0&&{authInfo:extra.authInfo}};if(isJSONRPCRequest(message)){this._requestId=message.id;let resolve,reject,promise=new Promise((promiseResolve,promiseReject)=>{resolve=promiseResolve,reject=promiseReject});if(this._deferredResponse={promise,resolve,reject,settled:!1},signal!==void 0){let onAbort=()=>{this.close()};signal.addEventListener("abort",onAbort,{once:!0}),this._abortCleanup=()=>signal.removeEventListener("abort",onAbort)}this._dispatchWindowOpen=!0;try{this.onmessage(message,messageExtra)}finally{this._dispatchWindowOpen=!1}return this._responseMode==="sse"&&!this._closed&&!this._deferredResponse.settled&&this.upgradeToSse(),promise}return this.onmessage(message,messageExtra),new Response(null,{status:202})}async send(message,options){if(this._closed)return;let isResponse=isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message),relatedId=isResponse?message.id:options?.relatedRequestId;if(this._requestId===void 0||relatedId===void 0||relatedId!==this._requestId){isResponse&&this.onerror?.(new Error(`Received a response for an unknown request id: ${String(message.id)}`));return}if(isResponse){if(this._terminalDelivered)return;this._terminalDelivered=!0;let errorCode=isJSONRPCErrorResponse(message)?message.error.code:void 0,ladderStatus=errorCode!==void 0&&(this._dispatchWindowOpen||errorCode===ProtocolErrorCode.MissingRequiredClientCapability)?LADDER_ERROR_HTTP_STATUS[errorCode]:void 0;if(ladderStatus!==void 0&&this._sse===void 0){this.settleResponse(Response.json(message,{status:ladderStatus,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>{this.close()});return}if(this._sse!==void 0||this._responseMode==="sse"){this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(message),this.finalizeStream();return}this.settleResponse(Response.json(message,{status:200,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>{this.close()});return}this._responseMode!=="json"&&(this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(message))}writeCommentFrame(comment){if(this._closed||this._sse===void 0||this._sse.closed)return;let frame=comment.split(`
80
73
  `).map(line=>`: ${line}`).join(`
81
74
  `);this.writeFrame(`${frame}
82
75
 
@@ -97,7 +90,7 @@ data:
97
90
  `),eventData+=`data: ${JSON.stringify(message)}
98
91
 
99
92
  `,controller.enqueue(encoder.encode(eventData)),!0}catch(error3){return this.onerror?.(error3),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(req,options){try{let acceptHeader=req.headers.get("accept");if(!acceptHeader?.includes("application/json")||!acceptHeader.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!isJsonContentType(req.headers.get("content-type")))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let request=req,rawMessage;if(options?.parsedBody===void 0)try{let body=await readRequestBody(req,this._maxRequestBodySize);if(body.tooLarge){let message=requestBodyTooLargeMessage(this._maxRequestBodySize);return this.onerror?.(new Error(message)),this.createJsonErrorResponse(413,-32e3,message)}rawMessage=JSON.parse(body.text)}catch(error3){return this.onerror?.(error3),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else rawMessage=options.parsedBody;if(Array.isArray(rawMessage)&&rawMessage.length>MAX_BATCH_SIZE)return this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${MAX_BATCH_SIZE} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${MAX_BATCH_SIZE} messages`);let messages;try{messages=Array.isArray(rawMessage)?rawMessage.map(msg=>JSONRPCMessageSchema.parse(msg)):[JSONRPCMessageSchema.parse(rawMessage)]}catch(error3){return this.onerror?.(error3),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let isInitializationRequest=messages.some(element=>isInitializeRequest(element));if(isInitializationRequest){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(messages.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!isInitializationRequest){let sessionError=this.validateSession(req);if(sessionError)return sessionError;let protocolError=this.validateProtocolVersion(req);if(protocolError)return protocolError}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let scopeChallengeResponse;try{scopeChallengeResponse=await this._checkScopeChallenge(messages,options?.authInfo)}catch(error3){return this.onerror?.(error3),this.createJsonErrorResponse(500,-32603,"Internal server error")}if(scopeChallengeResponse)return scopeChallengeResponse;if(!messages.some(element=>isJSONRPCRequest(element))){for(let message of messages)this.onmessage?.(message,{authInfo:options?.authInfo,request});return new Response(null,{status:202})}let streamId=crypto.randomUUID(),initRequest=messages.find(m=>isInitializeRequest(m)),clientProtocolVersion=initRequest?initRequest.params.protocolVersion:req.headers.get("mcp-protocol-version")??DEFAULT_NEGOTIATED_PROTOCOL_VERSION;if(this._enableJsonResponse)return new Promise(resolve=>{this._streamMapping.set(streamId,{resolveJson:resolve,cleanup:()=>{this._streamMapping.delete(streamId)}});for(let message of messages)isJSONRPCRequest(message)&&this._requestToStreamMapping.set(message.id,streamId);for(let message of messages)this.onmessage?.(message,{authInfo:options?.authInfo,request})});let encoder=new TextEncoder,streamController,keepAliveTimer,readable=new ReadableStream({start:controller=>{streamController=controller},cancel:()=>{keepAliveTimer!==void 0&&clearInterval(keepAliveTimer),this._streamMapping.get(streamId)?.controller===streamController&&this._streamMapping.delete(streamId)}}),headers={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(headers["mcp-session-id"]=this.sessionId);for(let message of messages)isJSONRPCRequest(message)&&(this._streamMapping.set(streamId,{controller:streamController,encoder,cleanup:()=>{keepAliveTimer!==void 0&&clearInterval(keepAliveTimer),this._streamMapping.delete(streamId);try{streamController.close()}catch{}}}),this._requestToStreamMapping.set(message.id,streamId));await this.writePrimingEvent(streamController,encoder,streamId,clientProtocolVersion);for(let message of messages){let closeSSEStream,closeStandaloneSSEStream;isJSONRPCRequest(message)&&this._eventStore&&this.supportsEmptySSEData(clientProtocolVersion)&&(closeSSEStream=()=>{this.closeSSEStream(message.id)},closeStandaloneSSEStream=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(message,{authInfo:options?.authInfo,request,closeSSEStream,closeStandaloneSSEStream})}return this._streamMapping.get(streamId)?.controller===streamController&&(keepAliveTimer=this.startKeepAlive(streamController,encoder)),new Response(readable,{status:200,headers})}catch(error3){return this.onerror?.(error3),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(error3)})}}async handleDeleteRequest(req){let sessionError=this.validateSession(req);if(sessionError)return sessionError;let protocolError=this.validateProtocolVersion(req);if(protocolError)return protocolError;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(req){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let sessionId=req.headers.get("mcp-session-id");if(!sessionId)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(sessionId!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(req){let protocolVersion=req.headers.get("mcp-protocol-version");if(protocolVersion!==null&&!this._supportedProtocolVersions.includes(protocolVersion)){let error3=`Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(new Error(error3)),this.createJsonErrorResponse(400,-32e3,error3)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup}of this._streamMapping.values())cleanup();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(requestId){let streamId=this._requestToStreamMapping.get(requestId);if(!streamId)return;let stream=this._streamMapping.get(streamId);stream&&stream.cleanup()}closeStandaloneSSEStream(){let stream=this._streamMapping.get(this._standaloneSseStreamId);stream&&stream.cleanup()}async send(message,options){let requestId=options?.relatedRequestId;if((isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message))&&(requestId=message.id),requestId===void 0){if(isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let eventId;this._eventStore&&(eventId=await this._eventStore.storeEvent(this._standaloneSseStreamId,message));let standaloneSse=this._streamMapping.get(this._standaloneSseStreamId);if(standaloneSse===void 0)return;standaloneSse.controller&&standaloneSse.encoder&&(eventId===void 0||!standaloneSse.replayedEventIds?.has(eventId))&&this.writeSSEEvent(standaloneSse.controller,standaloneSse.encoder,message,eventId);return}let streamId=this._requestToStreamMapping.get(requestId);if(!streamId)throw new Error(`No connection established for request ID: ${String(requestId)}`);let stream=this._streamMapping.get(streamId);if(!this._enableJsonResponse){let eventId;this._eventStore&&(eventId=await this._eventStore.storeEvent(streamId,message),stream=this._streamMapping.get(streamId)),stream?.controller&&stream?.encoder&&(eventId===void 0||!stream.replayedEventIds?.has(eventId))&&this.writeSSEEvent(stream.controller,stream.encoder,message,eventId)}if(isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)){this._requestResponseMap.set(requestId,message);let relatedIds=[...this._requestToStreamMapping.entries()].filter(([_,sid])=>sid===streamId).map(([id])=>id);if(relatedIds.every(id=>this._requestResponseMap.has(id))){if(!stream){if(this._enableJsonResponse)throw new Error(`No connection established for request ID: ${String(requestId)}`);if(!this._eventStore){this.onerror?.(new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let id of relatedIds)this._requestResponseMap.delete(id),this._requestToStreamMapping.delete(id);return}for(let id of relatedIds)this._requestResponseMap.delete(id),this._requestToStreamMapping.delete(id);return}if(this._enableJsonResponse&&stream.resolveJson){let headers={"Content-Type":"application/json"};this.sessionId!==void 0&&(headers["mcp-session-id"]=this.sessionId);let responses=relatedIds.map(id=>this._requestResponseMap.get(id));responses.length===1?stream.resolveJson(Response.json(responses[0],{status:200,headers})):stream.resolveJson(Response.json(responses,{status:200,headers})),stream.cleanup()}else stream.cleanup();for(let id of relatedIds)this._requestResponseMap.delete(id),this._requestToStreamMapping.delete(id)}}}};PREFIX="v1."}});function stripTrailingSlashes(value){return value.replace(/\/+$/,"")}function readEnv(name){if(typeof process>"u")return;let value=process.env[name];return value!==void 0&&value!==""?value:void 0}function parseForwardedHeader(header){for(let part of header.split(",")){let params=new Map;for(let token of part.split(";")){let[key,...rest]=token.trim().split("=");key===void 0||rest.length===0||params.set(key.toLowerCase(),rest.join("=").replace(/^"|"$/g,""))}let proto=params.get("proto"),host=params.get("host");if(proto!==void 0&&host!==void 0)return`${proto}://${host}`}}function resolveRequestOriginFromHeaders(request){let forwarded=request.headers.get("forwarded");if(forwarded!==null){let fromForwarded=parseForwardedHeader(forwarded);if(fromForwarded!==void 0)return fromForwarded}let proto=request.headers.get("x-forwarded-proto"),host=request.headers.get("x-forwarded-host");if(proto!==null&&host!==null){let firstHost=host.split(",")[0]?.trim(),firstProto=proto.split(",")[0]?.trim();if(firstHost!==void 0&&firstProto!==void 0&&firstHost!=="")return`${firstProto}://${firstHost}`}return new URL(request.url).origin}function resolveServerOrigin(request){let mcpUrl=readEnv("MCP_URL");if(mcpUrl!==void 0)try{return new URL(mcpUrl).origin}catch{}return resolveRequestOriginFromHeaders(request)}function resolveMcpEndpoint(request,basePath){let mcpUrl=readEnv("MCP_URL");if(mcpUrl!==void 0)try{let url3=new URL(mcpUrl);if(url3.protocol==="https:"||url3.protocol==="http:")return url3.pathname!=="/"||url3.search!==""?mcpUrl:`${stripTrailingSlashes(mcpUrl)}${basePath}`}catch{}if(request===void 0)return;let url2=new URL(request.url);return`${resolveRequestOriginFromHeaders(request)}${url2.pathname}${url2.search}`}function normalizeViewDomain(domain){try{let url2=new URL(domain);if(url2.protocol==="https:"||url2.protocol==="http:")return url2.origin}catch{}return domain}function originFromAssetsBase(assetsBase){try{return new URL(assetsBase).origin}catch{return assetsBase}}function normalizeAssetsBaseUrl(value){return stripTrailingSlashes(value)}function resolveAssetsBase(request){let assetsUrl=readEnv("MCP_ASSETS_URL");if(assetsUrl!==void 0)try{return normalizeAssetsBaseUrl(new URL(assetsUrl).href.replace(/\/$/,""))}catch{}return resolveServerOrigin(request)}function hasExplicitAssetsBase(){let assetsUrl=readEnv("MCP_ASSETS_URL");if(assetsUrl===void 0)return!1;try{return new URL(assetsUrl),!0}catch{return!1}}var init_origin=__esm({"src/views/origin.ts"(){"use strict"}});var public_route_exports={};__export(public_route_exports,{publicContentType:()=>publicContentType,resolvePublicFilePath:()=>resolvePublicFilePath,servePublicFile:()=>servePublicFile});function publicContentType(filename){let extension=filename.slice(filename.lastIndexOf(".")).toLowerCase();return PUBLIC_CONTENT_TYPES[extension]??"application/octet-stream"}async function resolvePublicFilePath(publicRoot,subpath){let{stat}=await import("fs/promises"),{resolve,sep}=await import("path");if(subpath===""||subpath.includes("\\")||subpath.split("/").some(segment=>segment===".."))return null;let clean2=subpath.replace(/^\/+/,"");if(clean2===""||clean2.endsWith("/"))return null;let root=resolve(publicRoot),abs=resolve(root,clean2);if(abs!==root&&!abs.startsWith(root+sep))return null;try{if(!(await stat(abs)).isFile())return null}catch{return null}return abs}async function servePublicFile(diskPath,options={}){let{readFile}=await import("fs/promises"),contentType=publicContentType(diskPath),body=options.head===!0?null:new Uint8Array(await readFile(diskPath));return new Response(body,{status:200,headers:{"Content-Type":contentType,"Cache-Control":"public, max-age=0, must-revalidate",...options.deferCors!==!0&&{"Access-Control-Allow-Origin":"*"}}})}var PUBLIC_CONTENT_TYPES,init_public_route=__esm({"src/views/public-route.ts"(){"use strict";PUBLIC_CONTENT_TYPES={".css":"text/css",".gif":"image/gif",".html":"text/html",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".map":"application/json",".png":"image/png",".svg":"image/svg+xml",".txt":"text/plain",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2"}}});function getRequestBag(request){let bag=requestBags.get(request);return bag===void 0&&(bag={},requestBags.set(request,bag)),bag}function composeFetch(terminal,...middlewares){return async request=>{let index=0,dispatch=async()=>{if(index<middlewares.length){let middleware=middlewares[index];return index+=1,middleware(request,dispatch)}return terminal(request)};return dispatch()}}function pathnameOf(request){return new URL(request.url).pathname}function matchesPath(request,path){return pathnameOf(request)===path}function matchesPathPrefix(request,prefix){let pathname=pathnameOf(request);return pathname===prefix||pathname.startsWith(`${prefix}/`)}function pathUnderBase(basePath,childPath){let child=childPath.replace(/^\/+/,"");return basePath==="/"?`/${child}`:`${basePath}/${child}`}function isHtmlNavigationRequest(request){if(request.method!=="GET"&&request.method!=="HEAD")return!1;let accept=request.headers.get("accept");return accept===null?!1:accept.split(",").some(range=>{let[mediaType,...parameters]=range.split(";");return mediaType?.trim().toLowerCase()!=="text/html"?!1:!parameters.some(parameter=>{let[name,value]=parameter.trim().toLowerCase().split("=");return name==="q"&&Number(value)===0})})}function jsonBodyMiddleware(){return async(request,next)=>{let bag=getRequestBag(request);if(bag.parsedBody!==void 0||!(request.headers.get("content-type")??"").includes("application/json"))return next();try{bag.parsedBody=await request.clone().json()}catch{return new Response("Invalid JSON",{status:400})}return next()}}function hostValidationMiddleware(hosts){return async(request,next)=>hostHeaderValidationResponse(request,hosts)??next()}function originValidationMiddleware(origins,skipSafeMethods=!0,exempt){return async(request,next)=>skipSafeMethods&&(request.method==="GET"||request.method==="HEAD")||exempt?.(request)===!0?next():originValidationResponse(request,origins)??next()}var requestBags,init_fetch_app=__esm({"src/fetch-app.ts"(){"use strict";init_dist();requestBags=new WeakMap}});function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function unionScopes(baseline,extra){return[...new Set([...baseline,...extra])]}function resolveSecuritySchemes(name,declared,options){let fail=detail=>{throw new TypeError(`Tool "${name}": ${detail}`)};if(declared===void 0)return[{type:"oauth2",scopes:[...options.baselineScopes]}];(!Array.isArray(declared)||declared.length===0)&&fail("securitySchemes must be a non-empty array; omit it to require sign-in with the provider's requiredScopes");let noAuth=!1,oauth2Scopes;for(let scheme of declared){isRecord2(scheme)||fail(SCHEME_SHAPE);let{type}=scheme,allowed=type==="oauth2"?["type","scopes"]:["type"];for(let key of Object.keys(scheme))allowed.includes(key)||fail(`unknown security scheme field ${JSON.stringify(key)}; ${SCHEME_SHAPE}`);if(type==="noauth")noAuth&&fail("declares more than one noauth scheme"),noAuth=!0;else if(type==="oauth2"){oauth2Scopes!==void 0&&fail("declares more than one oauth2 scheme; a sign-in challenge can only ask for one scope set");let{scopes}=scheme;Array.isArray(scopes)||fail("oauth2 scopes must be an array of scope strings");for(let scope of scopes)(typeof scope!="string"||!SCOPE_TOKEN.test(scope))&&fail(`invalid oauth2 scope ${JSON.stringify(scope)}; each scope must be one non-empty token without whitespace, ", or \\`);oauth2Scopes=scopes}else fail(`unsupported security scheme type ${JSON.stringify(type)}; use "noauth" or "oauth2"`)}noAuth&&!options.mixedAuth&&fail(options.hasOAuth?"noauth requires mixedAuth: true on the server. Without it, every request needs a token, so signed-out callers could never use it":"noauth requires an OAuth provider with mixedAuth: true. A server without OAuth serves every tool signed out, so remove securitySchemes"),oauth2Scopes!==void 0&&!options.hasOAuth&&fail("oauth2 requires an OAuth provider to verify tokens"),oauth2Scopes!==void 0&&oauth2Scopes.length===0&&options.baselineScopes.length===0&&fail("oauth2 scopes are empty and the OAuth provider has no requiredScopes. ChatGPT ignores an oauth2 scheme without scopes and would never offer sign-in; list at least one scope");let resolved=[];return noAuth&&resolved.push({type:"noauth"}),oauth2Scopes!==void 0&&resolved.push({type:"oauth2",scopes:unionScopes(options.baselineScopes,oauth2Scopes)}),resolved}function requiresSignIn(schemes){return!schemes.some(scheme=>scheme.type==="noauth")}function schemeScopes(schemes){for(let scheme of schemes)if(scheme.type==="oauth2")return scheme.scopes;return[]}function handWrittenSecuritySchemesWarning(name,definition,options){let handWritten=definition._meta?.[SECURITY_SCHEMES_META_KEY];if(handWritten!==void 0){if(definition.securitySchemes!==void 0)return JSON.stringify(handWritten)===JSON.stringify(definition.securitySchemes)?void 0:`[mcp-use] Tool "${name}": _meta.securitySchemes is replaced by the top-level securitySchemes. Remove the _meta entry.`;if(options.mixedAuth)return`[mcp-use] Tool "${name}": _meta.securitySchemes is advertised but not enforced, so the tool requires sign-in. Move it to the top-level securitySchemes field.`}}var SECURITY_SCHEMES_META_KEY,SCHEME_SHAPE,SCOPE_TOKEN,init_policy=__esm({"src/oauth/policy.ts"(){"use strict";SECURITY_SCHEMES_META_KEY="securitySchemes",SCHEME_SHAPE='each security scheme must be { type: "noauth" } or { type: "oauth2", scopes: string[] }',SCOPE_TOKEN=/^[\x21\x23-\x5B\x5D-\x7E]+$/}});var mcp_proxy_exports={};__export(mcp_proxy_exports,{isProxyConnection:()=>isProxyConnection,mountProxyConnection:()=>mountProxyConnection,mountProxyServers:()=>mountProxyServers,proxyClientInstallError:()=>proxyClientInstallError});function passthroughJsonSchema(schema2){return{"~standard":{version:1,vendor:"mcp-use-proxy",validate(value){return{value}},jsonSchema:{input:()=>schema2,output:()=>schema2}}}}function promptArgsToJsonSchema(args){let properties=Object.create(null),required2=[];for(let arg of args??[])properties[arg.name]={type:"string",...arg.description!==void 0&&{description:arg.description}},arg.required===!0&&required2.push(arg.name);return{type:"object",properties,...required2.length>0&&{required:required2}}}function prefixedName(namespace,name){return`${namespace}_${name}`}function proxiedResourceUri(namespace,uri){return`mcp-use-proxy:///${encodeURIComponent(namespace)}/${encodeURIComponent(uri)}`}function isConnection(value){if(value===null||typeof value!="object")return!1;let candidate=value;return typeof candidate.listTools=="function"&&typeof candidate.callTool=="function"&&typeof candidate.readResource=="function"&&typeof candidate.listPrompts=="function"&&typeof candidate.getPrompt=="function"}function isClientPackageMissing(error3){if(!(error3 instanceof Error))return!1;let code=error3.code;return(code==="ERR_MODULE_NOT_FOUND"||code==="MODULE_NOT_FOUND")&&error3.message.includes("@mcp-use/client")}function proxyDiagnostic(message,error3){if(error3===void 0){console.error(`[mcp-use] ${message}`);return}let detail=error3 instanceof Error?error3.message:String(error3);console.error(`[mcp-use] ${message}: ${detail}`)}function proxyClientInstallError(error3){return isClientPackageMissing(error3)?new Error(PROXY_CLIENT_INSTALL_HINT,{cause:error3}):void 0}async function loadProxyClient(importer=()=>import("@mcp-use/client")){try{return await importer()}catch(error3){let installError=proxyClientInstallError(error3);throw installError!==void 0?installError:error3}}function supports(connection,capability){return connection.supports?.(capability)!==!1}async function introspect(namespace,connection){let tools=[];if(supports(connection,"tools"))try{tools=await connection.listTools()}catch(error3){proxyDiagnostic(`Failed to introspect tools from upstream MCP server "${namespace}"`,error3)}let resources=[];if(supports(connection,"resources"))try{connection.listAllResources!==void 0?resources=(await connection.listAllResources()).resources:connection.listResources!==void 0&&(resources=(await connection.listResources()).resources)}catch(error3){proxyDiagnostic(`Failed to introspect resources from upstream MCP server "${namespace}"`,error3)}let prompts=[];if(supports(connection,"prompts"))try{prompts=(await connection.listPrompts()).prompts}catch(error3){proxyDiagnostic(`Failed to introspect prompts from upstream MCP server "${namespace}"`,error3)}return{namespace,connection,tools,resources,prompts}}function mountPlan(host,plan){host.trackNamespace?.({tools:plan.tools.length,resources:plan.resources.length,prompts:plan.prompts.length});for(let tool of plan.tools){let name=prefixedName(plan.namespace,tool.name);if(host.hasTool(name)){proxyDiagnostic(`Skipping proxied tool "${name}" from upstream "${plan.namespace}" because that name is already registered`);continue}let definition={name,...tool.title!==void 0&&{title:tool.title},...tool.icons!==void 0&&{icons:tool.icons},...tool.description!==void 0&&{description:tool.description},...tool.annotations!==void 0&&{annotations:tool.annotations},...tool.inputSchema!==void 0&&{inputSchema:passthroughJsonSchema(tool.inputSchema)},...tool.outputSchema!==void 0&&{outputSchema:passthroughJsonSchema(tool.outputSchema)}},upstreamName=tool.name,callback=async(params,ctx)=>{let progressForwarding=Promise.resolve();try{return await plan.connection.callTool(upstreamName,params,{signal:ctx.signal,onprogress:progress=>{progressForwarding=progressForwarding.then(async()=>{try{await ctx.reportProgress(progress.progress,progress.total,progress.message)}catch(error3){proxyDiagnostic(`Failed to forward progress for proxied tool "${definition.name}"`,error3)}})}})}finally{await progressForwarding}};host.registerTool(definition,callback)}for(let resource2 of plan.resources){let name=prefixedName(plan.namespace,resource2.name);if(host.hasResource(name)){proxyDiagnostic(`Skipping proxied resource "${name}" from upstream "${plan.namespace}" because that name is already registered`);continue}let upstreamUri=resource2.uri;host.registerResource({name,uri:proxiedResourceUri(plan.namespace,upstreamUri),...resource2.title!==void 0&&{title:resource2.title},...resource2.description!==void 0&&{description:resource2.description},...resource2.mimeType!==void 0&&{mimeType:resource2.mimeType},...resource2.annotations!==void 0&&{annotations:resource2.annotations},...resource2._meta!==void 0&&{_meta:resource2._meta}},async(_uri,ctx)=>plan.connection.readResource(upstreamUri,{signal:ctx.signal}))}for(let prompt of plan.prompts){let name=prefixedName(plan.namespace,prompt.name);if(host.hasPrompt(name)){proxyDiagnostic(`Skipping proxied prompt "${name}" from upstream "${plan.namespace}" because that name is already registered`);continue}let upstreamName=prompt.name;host.registerPrompt({name,...prompt.title!==void 0&&{title:prompt.title},...prompt.description!==void 0&&{description:prompt.description},schema:passthroughJsonSchema(promptArgsToJsonSchema(prompt.arguments))},async(params,ctx)=>plan.connection.getPrompt(upstreamName,params,{signal:ctx.signal}))}}async function mountProxyConnection(host,connection){if(host.isStarted())throw new Error("Cannot call proxy() after the server has started: register upstream servers before listen()/server.fetch.");let namespace=connection.info.server?.name;if(!namespace)throw new Error("Cannot proxy an anonymous MCP connection directly: the upstream server did not report a name for namespace generation.");let plan=await introspect(namespace,connection);mountPlan(host,plan)}function toClientConfig(config2){return{url:config2.url,...config2.headers!==void 0&&{headers:config2.headers},...config2.authToken!==void 0&&{authToken:config2.authToken},...config2.timeout!==void 0&&{timeout:config2.timeout},...config2.fetch!==void 0&&{fetch:config2.fetch},...config2.protocolNegotiation!==void 0&&{protocolNegotiation:config2.protocolNegotiation},oauth:!1}}async function mountProxyServers(host,servers){if(host.isStarted())throw new Error("Cannot call proxy() after the server has started: register upstream servers before listen()/server.fetch.");let{MCPClient}=await loadProxyClient(),clientServers=Object.fromEntries(Object.entries(servers).map(([name,config2])=>[name,toClientConfig(config2)])),owner=new MCPClient({mcpServers:clientServers});try{let plans=[];for(let namespace of Object.keys(clientServers)){let connection;try{connection=await owner.connect(namespace)}catch(error3){proxyDiagnostic(`Failed to connect to upstream MCP server "${namespace}"`,error3);continue}plans.push(await introspect(namespace,connection))}for(let plan of plans)mountPlan(host,plan);host.trackOwner(owner)}catch(error3){throw await owner.close().catch(()=>{}),error3}}function isProxyConnection(value){return isConnection(value)}var PROXY_CLIENT_INSTALL_HINT,init_mcp_proxy=__esm({"src/mcp-proxy.ts"(){"use strict";PROXY_CLIENT_INSTALL_HINT=["[mcp-use] server.proxy() requires the optional @mcp-use/client package.","Install it in your project:",""," npm install @mcp-use/client"].join(`
100
- `)}});function defaultDescription(reason,missingScopes){return reason==="missing_token"?"Authentication is required for this request.":reason==="invalid_token"?"The access token is invalid or expired.":missingScopes.length>0?`Additional permissions are required: ${missingScopes.join(" ")}.`:"Additional permissions are required."}function createAuthChallenge(options){return{reason:options.reason,description:options.description??defaultDescription(options.reason,options.missingScopes??[]),scopes:[...options.scopes],resourceMetadataUrl:options.resourceMetadataUrl}}function authChallengeHttpResponse(challenge){return bearerAuthChallengeResponse(new OAuthError(challenge.reason==="insufficient_scope"?OAuthErrorCode.InsufficientScope:OAuthErrorCode.InvalidToken,challenge.description),{requiredScopes:[...challenge.scopes],resourceMetadataUrl:challenge.resourceMetadataUrl})}function authChallengeToolResult(challenge){let header=authChallengeHttpResponse(challenge).headers.get("WWW-Authenticate");return{content:[{type:"text",text:challenge.description}],isError:!0,_meta:{[WWW_AUTHENTICATE_META_KEY]:header===null?[]:[header]}}}function prefersToolResultChallenge(request){return TOOL_RESULT_CHALLENGE_USER_AGENT.test(request.headers.get("user-agent")??"")}var WWW_AUTHENTICATE_META_KEY,TOOL_RESULT_CHALLENGE_USER_AGENT,init_challenge=__esm({"src/oauth/challenge.ts"(){"use strict";init_dist();WWW_AUTHENTICATE_META_KEY="mcp/www_authenticate",TOOL_RESULT_CHALLENGE_USER_AGENT=/chatgpt|openai/i}});var gate_exports={};__export(gate_exports,{createOAuthGate:()=>createOAuthGate});function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseMessage(body){if(!isRecord3(body)||typeof body.method!="string")return;let id=body.id,params=body.params;return{method:body.method,id:typeof id=="string"||typeof id=="number"?id:void 0,params:isRecord3(params)?params:void 0}}function isModernEnvelope(message){let meta2=message.params?._meta;return isRecord3(meta2)&&meta2[PROTOCOL_VERSION_META_KEY]!==void 0}function normalizeResourceUri(uri){try{return new URL(uri).toString()}catch{return uri}}function stringParam(params,key){let value=params?.[key];return typeof value=="string"?value:void 0}function isSignInMethod(message){if(SIGNED_OUT_METHODS.has(message.method)||message.id===void 0&&message.method.startsWith("notifications/"))return!1;if(message.method==="subscriptions/listen"){let filter=message.params?.notifications,uris=isRecord3(filter)?filter.resourceSubscriptions:void 0;return uris!==void 0&&(!Array.isArray(uris)||uris.length>0)}return!0}function createOAuthGate(options){let{verifier,resourceMetadataUrl,baselineScopes,mixedAuth,toolSchemes}=options,openResources=new Set([...options.openResourceUris].map(normalizeResourceUri)),open={required:!1,scopes:[]},signIn=(extra=[])=>({required:!0,scopes:[...new Set([...baselineScopes,...extra])]}),requirementFor=message=>{if(message===void 0)return mixedAuth?open:signIn();if(message.method==="tools/call"){let name=stringParam(message.params,"name"),schemes=name===void 0?void 0:toolSchemes(name);return schemes===void 0?signIn():mixedAuth&&!requiresSignIn(schemes)?open:signIn(schemeScopes(schemes))}if(!mixedAuth)return signIn();if(message.method==="resources/read"){let uri=stringParam(message.params,"uri");if(uri!==void 0&&openResources.has(normalizeResourceUri(uri)))return open}return isSignInMethod(message)?signIn():open},requirementForBody=body=>{if(!Array.isArray(body))return requirementFor(parseMessage(body));let scopes=new Set,required2=!1;for(let element of body){let requirement=requirementFor(parseMessage(element));if(requirement.required){required2=!0;for(let scope of requirement.scopes)scopes.add(scope)}}return{required:required2,scopes:[...scopes]}},refuse=(request,message,reason,requirement,details={})=>{let challenge=createAuthChallenge({reason,scopes:requirement.required?requirement.scopes:baselineScopes,resourceMetadataUrl,...details});return message===void 0||message.method!=="tools/call"||message.id===void 0||!prefersToolResultChallenge(request)?authChallengeHttpResponse(challenge):Response.json({jsonrpc:"2.0",id:message.id,result:{...isModernEnvelope(message)&&{resultType:"complete"},...authChallengeToolResult(challenge)}})};return async(request,next)=>{let bag=getRequestBag(request),body=bag.parsedBody;if(body===void 0&&request.method.toUpperCase()==="POST")try{body=await request.clone().json()}catch{}let message=Array.isArray(body)?void 0:parseMessage(body),requirement=requirementForBody(body),authInfo,authorization=request.headers.get("authorization");if(authorization!==null||requirement.required)try{authInfo=await verifyBearerToken(authorization,{verifier})}catch(error3){return!(error3 instanceof OAuthError)||error3.code!==OAuthErrorCode.InvalidToken&&error3.code!==OAuthErrorCode.InsufficientScope?bearerAuthChallengeResponse(error3,{resourceMetadataUrl}):error3.code===OAuthErrorCode.InsufficientScope?refuse(request,message,"insufficient_scope",requirement,{description:error3.message}):authorization===null?refuse(request,message,"missing_token",requirement):refuse(request,message,"invalid_token",requirement,{description:error3.message})}if(requirement.required&&authInfo!==void 0){let granted=new Set(authInfo.scopes),missingScopes=requirement.scopes.filter(scope=>!granted.has(scope));if(missingScopes.length>0)return refuse(request,message,"insufficient_scope",requirement,{missingScopes})}return authInfo!==void 0&&(bag.authInfo=authInfo),next()}}var SIGNED_OUT_METHODS,init_gate=__esm({"src/oauth/gate.ts"(){"use strict";init_dist();init_fetch_app();init_challenge();init_policy();SIGNED_OUT_METHODS=new Set(["initialize","server/discover","ping","tools/list","resources/list","resources/templates/list","prompts/list","logging/setLevel"])}});function sanitizeServerName(name){return name.replace(/[^a-zA-Z0-9-_]/g,"_").toLowerCase()}function utf8ToBase64(text2){let binary2="";for(let byte of new TextEncoder().encode(text2))binary2+=String.fromCharCode(byte);return btoa(binary2)}function generateCursorDeepLink(url2,name){let base64Config=utf8ToBase64(JSON.stringify({url:url2})),sanitizedName=sanitizeServerName(name);return`cursor://anysphere.cursor-deeplink/mcp/install?config=${encodeURIComponent(base64Config)}&name=${encodeURIComponent(sanitizedName)}`}function generateVSCodeDeepLink(url2,name){let config2={url:url2,name:sanitizeServerName(name),type:"http"},configJson=JSON.stringify(config2);return`vscode:mcp/install?${encodeURIComponent(configJson)}`}function generateVSCodeInsidersDeepLink(url2,name){let config2={url:url2,name:sanitizeServerName(name),type:"http"},configJson=JSON.stringify(config2);return`vscode-insiders:mcp/install?${encodeURIComponent(configJson)}`}function generateClaudeCommand(url2,name){let sanitizedName=sanitizeServerName(name),quotedUrl=`'${url2.replace(/'/g,"'\\''")}'`;return`claude mcp add --transport http "${sanitizedName}" ${quotedUrl}`}function getManufactInspectorUrl(serverUrl){let params=new URLSearchParams({autoConnect:serverUrl,tab:"chat"});return`${MANUFACT_INSPECTOR_ORIGIN}/inspector?${params.toString()}`}function getChatGPTSteps(url2){return["Open Plugins: In ChatGPT, go to Plugins and click Add",`Add this MCP server: Choose Add Custom MCP Server and enter ${url2}`,"Use in conversations: Choose the MCP server from the Plus menu"]}function getInstallTargets(server){let{url:url2,name}=server;return{claudeCode:{label:"Claude Code",command:generateClaudeCommand(url2,name)},cursor:{label:"Cursor",deeplink:generateCursorDeepLink(url2,name)},vscode:{label:"VS Code",deeplink:generateVSCodeDeepLink(url2,name)},vscodeInsiders:{label:"VS Code Insiders",deeplink:generateVSCodeInsidersDeepLink(url2,name)},chatgpt:{label:"ChatGPT",steps:getChatGPTSteps(url2)},inspector:{label:"Manufact Inspector",url:getManufactInspectorUrl(url2)}}}var MANUFACT_INSPECTOR_ORIGIN,init_install_targets=__esm({"src/install-targets.ts"(){"use strict";MANUFACT_INSPECTOR_ORIGIN="https://inspector.manufact.com"}});var init_landing_data=__esm({"src/landing-data.ts"(){"use strict";init_install_targets()}});function escapeHtml2(text2){return text2.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function serializeScriptJson(value){return JSON.stringify(value).replace(/</g,"\\u003c").replace(/>/g,"\\u003e")}function getPublicChatUrls(serverUrl){let origin=new URL(serverUrl).origin;return{chatUrl:new URL("/chat",origin).href,readyUrl:new URL("/chat/ready",origin).href}}function getMeshGradientScript(){return`(function(){
93
+ `)}});function defaultDescription(reason,missingScopes){return reason==="missing_token"?"Authentication is required for this request.":reason==="invalid_token"?"The access token is invalid or expired.":missingScopes.length>0?`Additional permissions are required: ${missingScopes.join(" ")}.`:"Additional permissions are required."}function createAuthChallenge(options){return{reason:options.reason,description:options.description??defaultDescription(options.reason,options.missingScopes??[]),scopes:[...options.scopes],resourceMetadataUrl:options.resourceMetadataUrl}}function authChallengeHttpResponse(challenge){return bearerAuthChallengeResponse(new OAuthError(challenge.reason==="insufficient_scope"?OAuthErrorCode.InsufficientScope:OAuthErrorCode.InvalidToken,challenge.description),{requiredScopes:[...challenge.scopes],resourceMetadataUrl:challenge.resourceMetadataUrl})}function authChallengeToolResult(challenge){let header=authChallengeHttpResponse(challenge).headers.get("WWW-Authenticate");return{content:[{type:"text",text:challenge.description}],isError:!0,_meta:{[WWW_AUTHENTICATE_META_KEY]:header===null?[]:[header]}}}function prefersToolResultChallenge(request){return TOOL_RESULT_CHALLENGE_USER_AGENT.test(request.headers.get("user-agent")??"")}var WWW_AUTHENTICATE_META_KEY,TOOL_RESULT_CHALLENGE_USER_AGENT,init_challenge=__esm({"src/oauth/challenge.ts"(){"use strict";init_dist();WWW_AUTHENTICATE_META_KEY="mcp/www_authenticate",TOOL_RESULT_CHALLENGE_USER_AGENT=/chatgpt|openai/i}});var gate_exports={};__export(gate_exports,{createOAuthGate:()=>createOAuthGate});function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseMessage(body){if(!isRecord3(body)||typeof body.method!="string")return;let id=body.id,params=body.params;return{method:body.method,id:typeof id=="string"||typeof id=="number"?id:void 0,params:isRecord3(params)?params:void 0}}function isModernEnvelope(message){let meta2=message.params?._meta;return isRecord3(meta2)&&meta2[PROTOCOL_VERSION_META_KEY]!==void 0}function normalizeResourceUri(uri){try{return new URL(uri).toString()}catch{return uri}}function stringParam(params,key){let value=params?.[key];return typeof value=="string"?value:void 0}function isSignInMethod(message){if(SIGNED_OUT_METHODS.has(message.method)||message.id===void 0&&message.method.startsWith("notifications/"))return!1;if(message.method==="subscriptions/listen"){let filter=message.params?.notifications,uris=isRecord3(filter)?filter.resourceSubscriptions:void 0;return uris!==void 0&&(!Array.isArray(uris)||uris.length>0)}return!0}function createOAuthGate(options){let{verifier,resourceMetadataUrl,baselineScopes,mixedAuth,toolSchemes}=options,openResources=new Set([...options.openResourceUris].map(normalizeResourceUri)),open2={required:!1,scopes:[]},signIn=(extra=[])=>({required:!0,scopes:[...new Set([...baselineScopes,...extra])]}),requirementFor=message=>{if(message===void 0)return mixedAuth?open2:signIn();if(message.method==="tools/call"){let name=stringParam(message.params,"name"),schemes=name===void 0?void 0:toolSchemes(name);return schemes===void 0?signIn():mixedAuth&&!requiresSignIn(schemes)?open2:signIn(schemeScopes(schemes))}if(!mixedAuth)return signIn();if(message.method==="resources/read"){let uri=stringParam(message.params,"uri");if(uri!==void 0&&openResources.has(normalizeResourceUri(uri)))return open2}return isSignInMethod(message)?signIn():open2},requirementForBody=body=>{if(!Array.isArray(body))return requirementFor(parseMessage(body));let scopes=new Set,required2=!1;for(let element of body){let requirement=requirementFor(parseMessage(element));if(requirement.required){required2=!0;for(let scope of requirement.scopes)scopes.add(scope)}}return{required:required2,scopes:[...scopes]}},refuse=(request,message,reason,requirement,details={})=>{let challenge=createAuthChallenge({reason,scopes:requirement.required?requirement.scopes:baselineScopes,resourceMetadataUrl,...details});return message===void 0||message.method!=="tools/call"||message.id===void 0||!prefersToolResultChallenge(request)?authChallengeHttpResponse(challenge):Response.json({jsonrpc:"2.0",id:message.id,result:{...isModernEnvelope(message)&&{resultType:"complete"},...authChallengeToolResult(challenge)}})};return async(request,next)=>{let bag=getRequestBag(request),body=bag.parsedBody;if(body===void 0&&request.method.toUpperCase()==="POST")try{body=await request.clone().json()}catch{}let message=Array.isArray(body)?void 0:parseMessage(body),requirement=requirementForBody(body),authInfo,authorization=request.headers.get("authorization");if(authorization!==null||requirement.required)try{authInfo=await verifyBearerToken(authorization,{verifier})}catch(error3){return!(error3 instanceof OAuthError)||error3.code!==OAuthErrorCode.InvalidToken&&error3.code!==OAuthErrorCode.InsufficientScope?bearerAuthChallengeResponse(error3,{resourceMetadataUrl}):error3.code===OAuthErrorCode.InsufficientScope?refuse(request,message,"insufficient_scope",requirement,{description:error3.message}):authorization===null?refuse(request,message,"missing_token",requirement):refuse(request,message,"invalid_token",requirement,{description:error3.message})}if(requirement.required&&authInfo!==void 0){let granted=new Set(authInfo.scopes),missingScopes=requirement.scopes.filter(scope=>!granted.has(scope));if(missingScopes.length>0)return refuse(request,message,"insufficient_scope",requirement,{missingScopes})}return authInfo!==void 0&&(bag.authInfo=authInfo),next()}}var SIGNED_OUT_METHODS,init_gate=__esm({"src/oauth/gate.ts"(){"use strict";init_dist();init_fetch_app();init_challenge();init_policy();SIGNED_OUT_METHODS=new Set(["initialize","server/discover","ping","tools/list","resources/list","resources/templates/list","prompts/list","logging/setLevel"])}});function sanitizeServerName(name){return name.replace(/[^a-zA-Z0-9-_]/g,"_").toLowerCase()}function utf8ToBase64(text2){let binary2="";for(let byte of new TextEncoder().encode(text2))binary2+=String.fromCharCode(byte);return btoa(binary2)}function generateCursorDeepLink(url2,name){let base64Config=utf8ToBase64(JSON.stringify({url:url2})),sanitizedName=sanitizeServerName(name);return`cursor://anysphere.cursor-deeplink/mcp/install?config=${encodeURIComponent(base64Config)}&name=${encodeURIComponent(sanitizedName)}`}function generateVSCodeDeepLink(url2,name){let config2={url:url2,name:sanitizeServerName(name),type:"http"},configJson=JSON.stringify(config2);return`vscode:mcp/install?${encodeURIComponent(configJson)}`}function generateVSCodeInsidersDeepLink(url2,name){let config2={url:url2,name:sanitizeServerName(name),type:"http"},configJson=JSON.stringify(config2);return`vscode-insiders:mcp/install?${encodeURIComponent(configJson)}`}function generateClaudeCommand(url2,name){let sanitizedName=sanitizeServerName(name),quotedUrl=`'${url2.replace(/'/g,"'\\''")}'`;return`claude mcp add --transport http "${sanitizedName}" ${quotedUrl}`}function getManufactInspectorUrl(serverUrl){let params=new URLSearchParams({autoConnect:serverUrl,tab:"chat"});return`${MANUFACT_INSPECTOR_ORIGIN}/inspector?${params.toString()}`}function getChatGPTSteps(url2){return["Open Plugins: In ChatGPT, go to Plugins and click Add",`Add this MCP server: Choose Add Custom MCP Server and enter ${url2}`,"Use in conversations: Choose the MCP server from the Plus menu"]}function getInstallTargets(server){let{url:url2,name}=server;return{claudeCode:{label:"Claude Code",command:generateClaudeCommand(url2,name)},cursor:{label:"Cursor",deeplink:generateCursorDeepLink(url2,name)},vscode:{label:"VS Code",deeplink:generateVSCodeDeepLink(url2,name)},vscodeInsiders:{label:"VS Code Insiders",deeplink:generateVSCodeInsidersDeepLink(url2,name)},chatgpt:{label:"ChatGPT",steps:getChatGPTSteps(url2)},inspector:{label:"Manufact Inspector",url:getManufactInspectorUrl(url2)}}}var MANUFACT_INSPECTOR_ORIGIN,init_install_targets=__esm({"src/install-targets.ts"(){"use strict";MANUFACT_INSPECTOR_ORIGIN="https://inspector.manufact.com"}});var init_landing_data=__esm({"src/landing-data.ts"(){"use strict";init_install_targets()}});function escapeHtml2(text2){return text2.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function serializeScriptJson(value){return JSON.stringify(value).replace(/</g,"\\u003c").replace(/>/g,"\\u003e")}function getPublicChatUrls(serverUrl){let origin=new URL(serverUrl).origin;return{chatUrl:new URL("/chat",origin).href,readyUrl:new URL("/chat/ready",origin).href}}function getMeshGradientScript(){return`(function(){
101
94
  var c=document.getElementById('mesh-bg');
102
95
  if(!c)return;
103
96
  var wrap=c.parentElement;
@@ -788,13 +781,13 @@ ${stylesheets}
788
781
  <script id="mcp-use-landing-data" type="application/json">${serializeScriptJson2(data)}</script>
789
782
  ${scripts}
790
783
  </body>
791
- </html>`}async function createLandingPageResponse(request,basePath,config2,branding,tools,prompts,resources,registration,cache){let origin=resolveServerOrigin(request),url2=new URL(basePath,`${origin}/`).href,assetsBase=resolveAssetsBase(request),basePrefix=basePath==="/"?"":basePath,server={name:config2.name,...config2.title!==void 0&&{title:config2.title},version:config2.version,...config2.description!==void 0&&{description:config2.description},url:url2,...branding.websiteUrl!==void 0&&{websiteUrl:branding.websiteUrl},...branding.favicon!==void 0&&{iconUrl:new URL("/favicon.ico",`${origin}/`).href,...branding.faviconMimeType!==void 0&&{iconType:branding.faviconMimeType}},publicBaseUrl:`${assetsBase}${basePrefix}/_mcp-use/public/`},listTools=()=>Array.from(tools,({definition})=>({name:definition.name,...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description}})),listPrompts=()=>Array.from(prompts,({definition})=>({name:definition.name,...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description}})),listResources=()=>Array.from(resources,({definition})=>({uri:definition.uri,...definition.name!==void 0&&{name:definition.name},...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description}})),landingData=keys2=>{let dataKeys=new Set(keys2);return{server,...dataKeys.has("tools")&&{tools:listTools()},...dataKeys.has("prompts")&&{prompts:listPrompts()},...dataKeys.has("resources")&&{resources:listResources()}}},html2=registration===void 0?generateLandingPage({...server,tools:listTools(),prompts:listPrompts(),resources:listResources()}):request.method==="HEAD"?void 0:await(async()=>{let key=`${url2}\0${assetsBase}`,cached2=registration.dev===!0?void 0:cache?.get(key);if(cached2!==void 0)return cached2;let rendering=(async()=>{let{render,dataKeys,metadata,importedCss}="load"in registration?await registration.load():registration,data=landingData(dataKeys);return renderDocument(data,await render(data),registration,importedCss??[],readLandingMetadata(metadata),origin,assetsBase,basePath)})();if(registration.dev!==!0&&cache!==void 0){if(cache.size>=MAX_CACHED_DOCUMENTS){let oldest=cache.keys().next().value;oldest!==void 0&&cache.delete(oldest)}cache.set(key,rendering),rendering.catch(()=>{cache.get(key)===rendering&&cache.delete(key)})}return rendering})();return new Response(request.method==="HEAD"?null:html2,{status:200,headers:{"cache-control":"no-store","content-type":"text/html; charset=utf-8","x-content-type-options":"nosniff"}})}var MAX_CACHED_DOCUMENTS,THEME_SCRIPT,METADATA_FIELDS,reportedMetadataWarnings,init_landing_handler=__esm({"src/landing-handler.ts"(){"use strict";init_landing();init_origin();MAX_CACHED_DOCUMENTS=32,THEME_SCRIPT='<script>(()=>{const d=document.documentElement,q=matchMedia("(prefers-color-scheme: dark)");let s;const a=()=>{if(d.dataset.theme!==s)return;s=q.matches?"dark":"light";d.dataset.theme=s};a();q.addEventListener("change",a)})()</script>';METADATA_FIELDS=["title","description","icon","image"],reportedMetadataWarnings=new Set}});var DEFAULT_DISPLAY_MODES=["inline","fullscreen","pip"],VALID_DISPLAY_MODES=new Set(["inline","fullscreen","pip"]);function normalizeViewConfig(config2){let autoResize=config2?.autoResize??!0,modes=config2?.displayModes===void 0?DEFAULT_DISPLAY_MODES:config2.displayModes;if(!Array.isArray(modes)||modes.length===0)throw new Error('viewConfig.displayModes must be a non-empty array that includes "inline"');let seen=new Set,normalizedModes=[];for(let mode of modes){if(typeof mode!="string"||!VALID_DISPLAY_MODES.has(mode))throw new Error(`viewConfig.displayModes contains invalid mode ${JSON.stringify(mode)}; expected "inline", "fullscreen", or "pip"`);if(seen.has(mode))throw new Error(`viewConfig.displayModes contains duplicate mode "${mode}"`);seen.add(mode),normalizedModes.push(mode)}if(!seen.has("inline"))throw new Error('viewConfig.displayModes must include "inline"');let preferred=config2?.preferredDisplayMode;if(preferred!==void 0&&preferred!=="inline"&&preferred!=="fullscreen")throw new Error('viewConfig.preferredDisplayMode must be "inline" or "fullscreen"');if(preferred!==void 0&&!seen.has(preferred))throw new Error("viewConfig.preferredDisplayMode must belong to displayModes");return{...preferred!==void 0&&{preferredDisplayMode:preferred},autoResize,displayModes:normalizedModes}}init_dist();import{createServer as createNodeHttpServer}from"node:http";var GET_MATCH_RESULT=Symbol();var bufferToFormData=(arrayBuffer,contentType)=>new Response(arrayBuffer,{headers:{"Content-Type":contentType.replace(/^[^;]+/,mediaType=>mediaType.toLowerCase())}}).formData();var MAX_NESTED_OBJECTS=1e4,isRawRequest=request=>"headers"in request,parseBody=async(request,options=Object.create(null))=>{let{all=!1,dot=!1}=options,mediaType=(isRawRequest(request)?request.headers:request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return mediaType==="multipart/form-data"||mediaType==="application/x-www-form-urlencoded"?parseFormData(request,{all,dot}):{}};async function parseFormData(request,options){if(!isRawRequest(request)&&request.bodyCache.formData)return convertFormDataToBodyData(await request.bodyCache.formData,options);let headers=isRawRequest(request)?request.headers:request.raw.headers,arrayBuffer=await request.arrayBuffer(),formDataPromise=bufferToFormData(arrayBuffer,headers.get("Content-Type")||"");isRawRequest(request)||(request.bodyCache.formData=formDataPromise);let formData=await formDataPromise;return formData?convertFormDataToBodyData(formData,options):{}}function convertFormDataToBodyData(formData,options){let form=Object.create(null),nestingState={count:0};return formData.forEach((value,key)=>{options.all||key.endsWith("[]")?handleParsingAllValues(form,key,value):form[key]=value}),options.dot&&Object.entries(form).forEach(([key,value])=>{key.includes(".")&&(handleParsingNestedValues(form,key,value,nestingState),delete form[key])}),form}var handleParsingAllValues=(form,key,value)=>{form[key]!==void 0?Array.isArray(form[key])?form[key].push(value):form[key]=[form[key],value]:key.endsWith("[]")?form[key]=[value]:form[key]=value},handleParsingNestedValues=(form,key,value,state)=>{if(/(?:^|\.)__proto__\./.test(key))return;let nestedForm=form,keys2=key.split(".",34);keys2.length>33&&throwNestingLimitExceeded(),keys2.forEach((key2,index)=>{index===keys2.length-1?nestedForm[key2]=value:((!nestedForm[key2]||typeof nestedForm[key2]!="object"||Array.isArray(nestedForm[key2])||nestedForm[key2]instanceof File)&&(state.count++>=MAX_NESTED_OBJECTS&&throwNestingLimitExceeded(),nestedForm[key2]=Object.create(null)),nestedForm=nestedForm[key2])})},throwNestingLimitExceeded=()=>{throw new Error("Nesting limit exceeded")};var splitPath=path=>{let paths=path.split("/");return paths[0]===""&&paths.shift(),paths},splitRoutingPath=routePath=>{let{groups,path}=extractGroupsFromPath(routePath),paths=splitPath(path);return replaceGroupMarks(paths,groups)},extractGroupsFromPath=path=>{let groups=[];return path=path.replace(/\{[^}]+\}/g,(match2,index)=>{let mark=`@${index}`;return groups.push([mark,match2]),mark}),{groups,path}},replaceGroupMarks=(paths,groups)=>{for(let i=groups.length-1;i>=0;i--){let[mark]=groups[i];for(let j=paths.length-1;j>=0;j--)if(paths[j].includes(mark)){paths[j]=paths[j].replace(mark,groups[i][1]);break}}return paths},patternCache={},getPattern=(label,next)=>{if(label==="*")return"*";let match2=label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(match2){let cacheKey=`${label}#${next}`;return patternCache[cacheKey]||(match2[2]?patternCache[cacheKey]=next&&next[0]!==":"&&next[0]!=="*"?[cacheKey,match2[1],new RegExp(`^${match2[2]}(?=/${next})`)]:[label,match2[1],new RegExp(`^${match2[2]}$`)]:patternCache[cacheKey]=[label,match2[1],!0]),patternCache[cacheKey]}return null},tryDecode=(str,decoder)=>{try{return decoder(str)}catch{return str.replace(/(?:%[0-9A-Fa-f]{2})+/g,match2=>{try{return decoder(match2)}catch{return match2}})}},tryDecodeURI=str=>tryDecode(str,decodeURI),getPath=request=>{let url2=request.url,start=url2.indexOf("/",url2.indexOf(":")+4),i=start;for(;i<url2.length;i++){let charCode=url2.charCodeAt(i);if(charCode===37){let queryIndex=url2.indexOf("?",i),hashIndex=url2.indexOf("#",i),end=queryIndex===-1?hashIndex===-1?void 0:hashIndex:hashIndex===-1?queryIndex:Math.min(queryIndex,hashIndex),path=url2.slice(start,end);return tryDecodeURI(path.includes("%25")?path.replace(/%25/g,"%2525"):path)}else if(charCode===63||charCode===35)break}return url2.slice(start,i)};var getPathNoStrict=request=>{let result=getPath(request);return result.length>1&&result.at(-1)==="/"?result.slice(0,-1):result},mergePath=(base,sub,...rest)=>(rest.length&&(sub=mergePath(sub,...rest)),`${base?.[0]==="/"?"":"/"}${base}${sub==="/"?"":`${base?.at(-1)==="/"?"":"/"}${sub?.[0]==="/"?sub.slice(1):sub}`}`),checkOptionalParameter=path=>{if(path.charCodeAt(path.length-1)!==63||!path.includes(":"))return null;let segments=path.split("/"),results=[],basePath="";return segments.forEach(segment=>{if(segment!==""&&!/\:/.test(segment))basePath+="/"+segment;else if(/\:/.test(segment))if(segment.charCodeAt(segment.length-1)===63){results.length===0&&basePath===""?results.push("/"):results.push(basePath);let optionalSegment=segment.slice(0,-1);basePath+="/"+optionalSegment,results.push(basePath)}else basePath+="/"+segment}),results.filter((v,i,a)=>a.indexOf(v)===i)},tryDecodeURIComponent=str=>str.indexOf("%")!==-1?tryDecode(str,decodeURIComponent_):str,_decodeURI=value=>(value.indexOf("+")!==-1&&(value=value.replace(/\+/g," ")),tryDecodeURIComponent(value)),_getQueryParam=(url2,key,multiple)=>{let hashIndex=url2.indexOf("#",8);hashIndex!==-1&&(url2=url2.slice(0,hashIndex));let encoded;if(!multiple&&key&&key.indexOf("%")===-1&&key.indexOf("+")===-1){let keyIndex2=url2.indexOf("?",8);if(keyIndex2===-1)return;for(url2.startsWith(key,keyIndex2+1)||(keyIndex2=url2.indexOf(`&${key}`,keyIndex2+1));keyIndex2!==-1;){let trailingKeyCode=url2.charCodeAt(keyIndex2+key.length+1);if(trailingKeyCode===61){let valueIndex=keyIndex2+key.length+2,endIndex=url2.indexOf("&",valueIndex);return _decodeURI(url2.slice(valueIndex,endIndex===-1?void 0:endIndex))}else if(trailingKeyCode==38||isNaN(trailingKeyCode))return"";keyIndex2=url2.indexOf(`&${key}`,keyIndex2+1)}if(encoded=/[%+]/.test(url2),!encoded)return}let results=Object.create(null);encoded??=/[%+]/.test(url2);let keyIndex=url2.indexOf("?",8);for(;keyIndex!==-1;){let nextKeyIndex=url2.indexOf("&",keyIndex+1),valueIndex=url2.indexOf("=",keyIndex);valueIndex>nextKeyIndex&&nextKeyIndex!==-1&&(valueIndex=-1);let name=url2.slice(keyIndex+1,valueIndex===-1?nextKeyIndex===-1?void 0:nextKeyIndex:valueIndex);if(encoded&&(name=_decodeURI(name)),keyIndex=nextKeyIndex,name==="")continue;let value;valueIndex===-1?value="":(value=url2.slice(valueIndex+1,nextKeyIndex===-1?void 0:nextKeyIndex),encoded&&(value=_decodeURI(value))),multiple?(results[name]&&Array.isArray(results[name])||(results[name]=[]),results[name].push(value)):results[name]??=value}return key?results[key]:results},getQueryParam=_getQueryParam,getQueryParams=(url2,key)=>_getQueryParam(url2,key,!0),decodeURIComponent_=decodeURIComponent;var HonoRequest=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(request,path="/",matchResult=[[]]){this.raw=request,this.path=path,this.#matchResult=matchResult}param(key){return key?this.#getDecodedParam(key):this.#getAllDecodedParams()}#getDecodedParam(key){let paramKey=this.#matchResult[0][this.routeIndex]?.[1][key],param=this.#getParamValue(paramKey);return param&&tryDecodeURIComponent(param)}#getAllDecodedParams(){let decoded={},keys2=Object.keys(this.#matchResult[0][this.routeIndex]?.[1]??{});for(let key of keys2){let value=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);value!==void 0&&(decoded[key]=tryDecodeURIComponent(value))}return decoded}#getParamValue(paramKey){return this.#matchResult[1]?this.#matchResult[1][paramKey]:paramKey}query(key){return getQueryParam(this.url,key)}queries(key){return getQueryParams(this.url,key)}header(name){if(name)return this.raw.headers.get(name)??void 0;let headerData=Object.create(null);return this.raw.headers.forEach((value,key)=>{headerData[key]=value}),headerData}async parseBody(options){return parseBody(this,options)}#cachedBody=key=>{let{bodyCache,raw:raw2}=this,cachedBody=bodyCache[key];if(cachedBody)return cachedBody;for(let anyCachedKey in bodyCache)return bodyCache[anyCachedKey].then(body=>{anyCachedKey==="json"&&(body=JSON.stringify(body));let contentType=anyCachedKey==="formData"?void 0:raw2.headers.get("content-type");return new Response(body,{headers:contentType?{"Content-Type":contentType}:void 0})[key]()});return bodyCache[key]=raw2[key]()};json(){return this.#cachedBody("text").then(text2=>JSON.parse(text2))}text(){return this.#cachedBody("text")}arrayBuffer(){return this.#cachedBody("arrayBuffer")}bytes(){return this.#cachedBody("arrayBuffer").then(buffer=>new Uint8Array(buffer))}blob(){return this.#cachedBody("blob")}formData(){return this.#cachedBody("formData")}addValidatedData(target,data){(this.#validatedData??={})[target]=data}valid(target){return this.#validatedData?.[target]}get url(){return this.raw.url}get method(){return this.raw.method}get[GET_MATCH_RESULT](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,route]])=>route)}get routePath(){return this.#matchResult[0].map(([[,route]])=>route)[this.routeIndex].path}};var HtmlEscapedCallbackPhase={Stringify:1,BeforeStream:2,Stream:3},raw=(value,callbacks)=>{let escapedString=new String(value);return escapedString.isEscaped=!0,escapedString.callbacks=callbacks,escapedString};var resolveCallback=async(str,phase,preserveCallbacks,context,buffer)=>{typeof str=="object"&&!(str instanceof String)&&(str instanceof Promise||(str=str.toString()),str instanceof Promise&&(str=await str));let callbacks=str.callbacks;if(!callbacks?.length)return Promise.resolve(str);buffer?buffer[0]+=str:buffer=[str];let resStr=Promise.all(callbacks.map(c=>c({phase,buffer,context}))).then(res=>Promise.all(res.filter(Boolean).map(str2=>resolveCallback(str2,phase,!1,context,buffer))).then(()=>buffer[0]));return preserveCallbacks?raw(await resStr,callbacks):resStr};var TEXT_PLAIN="text/plain; charset=UTF-8",setDefaultContentType=(contentType,headers)=>({"Content-Type":contentType,...headers}),createResponseInstance=(body,init)=>new Response(body,init),Context=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(req,options){this.#rawRequest=req,options&&(this.#executionCtx=options.executionCtx,this.env=options.env,this.#notFoundHandler=options.notFoundHandler,this.#path=options.path,this.#matchResult=options.matchResult)}get req(){return this.#req??=new HonoRequest(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&"respondWith"in this.#executionCtx)return this.#executionCtx;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error("This context has no ExecutionContext")}get res(){return this.#res||=createResponseInstance(null,{headers:this.#preparedHeaders??=new Headers})}set res(_res){if(this.#res&&_res){_res=createResponseInstance(_res.body,_res);for(let[k,v]of this.#res.headers.entries())if(k!=="content-type")if(k==="set-cookie"){let cookies=this.#res.headers.getSetCookie();_res.headers.delete("set-cookie");for(let cookie of cookies)_res.headers.append("set-cookie",cookie)}else _res.headers.set(k,v)}this.#res=_res,this.finalized=!0}render=(...args)=>(this.#renderer??=content=>this.html(content),this.#renderer(...args));setLayout=layout=>this.#layout=layout;getLayout=()=>this.#layout;setRenderer=renderer=>{this.#renderer=renderer};header=(name,value,options)=>{this.finalized&&(this.#res=createResponseInstance(this.#res.body,this.#res));let headers=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;value===void 0?headers.delete(name):options?.append?headers.append(name,value):headers.set(name,value)};status=status=>{this.#status=status};set=(key,value)=>{this.#var??=new Map,this.#var.set(key,value)};get=key=>this.#var?this.#var.get(key):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(data,arg,headers){let responseHeaders=this.#res?new Headers(this.#res.headers):this.#preparedHeaders;if(typeof arg=="object"&&arg.headers){responseHeaders??=new Headers;for(let[key,value]of new Headers(arg.headers))key==="set-cookie"?responseHeaders.append(key,value):responseHeaders.set(key,value)}if(headers){if(!responseHeaders){let count=0;for(let k in headers)if(++count>1||typeof headers[k]!="string"){responseHeaders=new Headers;break}}if(responseHeaders)for(let k in headers){let v=headers[k];if(typeof v=="string")responseHeaders.set(k,v);else{responseHeaders.delete(k);for(let v2 of v)responseHeaders.append(k,v2)}}}let status=typeof arg=="number"?arg:arg?.status??this.#status;return createResponseInstance(data,{status,headers:responseHeaders??headers})}newResponse=(...args)=>this.#newResponse(...args);body=(data,arg,headers)=>this.#newResponse(data,arg,headers);text=(text2,arg,headers)=>!this.#preparedHeaders&&!this.#status&&!arg&&!headers&&!this.finalized?new Response(text2):this.#newResponse(text2,arg,setDefaultContentType(TEXT_PLAIN,headers));json=(object5,arg,headers)=>this.#newResponse(JSON.stringify(object5),arg,setDefaultContentType("application/json",headers));html=(html2,arg,headers)=>{let res=html3=>this.#newResponse(html3,arg,setDefaultContentType("text/html; charset=UTF-8",headers));return typeof html2=="object"?resolveCallback(html2,HtmlEscapedCallbackPhase.Stringify,!1,{}).then(res):res(html2)};redirect=(location,status)=>{let locationString=String(location);return this.header("Location",/[^\x00-\xFF]/.test(locationString)?encodeURI(locationString):locationString),this.newResponse(null,status??302)};notFound=()=>(this.#notFoundHandler??=()=>createResponseInstance(),this.#notFoundHandler(this))};var compose=(middleware,onError,onNotFound)=>(context,next)=>{let index=-1;return dispatch(0);async function dispatch(i){if(i<=index)throw new Error("next() called multiple times");index=i;let res,isError=!1,handler;if(middleware[i]?(handler=middleware[i][0][0],context.req.routeIndex=i):handler=i===middleware.length&&next||void 0,handler)try{res=await handler(context,()=>dispatch(i+1))}catch(err){if(err instanceof Error&&onError)context.error=err,res=await onError(err,context),isError=!0;else throw err}else context.finalized===!1&&onNotFound&&(res=await onNotFound(context));return res&&(context.finalized===!1||isError)&&(context.res=res),context}};var METHODS=["get","post","put","delete","options","patch","query"],MESSAGE_MATCHER_IS_ALREADY_BUILT="Can not add a route since the matcher is already built.",UnsupportedPathError=class extends Error{};var COMPOSED_HANDLER="__COMPOSED_HANDLER";var notFoundHandler=c=>c.text("404 Not Found",404),errorHandler=(err,c)=>{if("getResponse"in err){let res=err.getResponse();return c.newResponse(res.body,res)}return console.error(err),c.text("Internal Server Error",500)},Hono=class Hono2{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#path="/";routes=[];constructor(options={}){[...METHODS,"all"].forEach(method=>{this[method]=(args1,...args)=>{let methodName=method.toUpperCase();return typeof args1=="string"?this.#path=args1:this.#addRoute(methodName,this.#path,args1),args.forEach(handler=>{this.#addRoute(methodName,this.#path,handler)}),this}}),this.on=(method,path,...handlers)=>{for(let p of[path].flat()){this.#path=p;for(let m of[method].flat()){let methodName=m.toUpperCase();for(let handler of handlers)this.#addRoute(methodName,this.#path,handler)}}return this},this.use=(arg1,...handlers)=>(typeof arg1=="string"?this.#path=arg1:(this.#path="*",handlers.unshift(arg1)),handlers.forEach(handler=>{this.#addRoute("ALL",this.#path,handler)}),this);let{strict,...optionsWithoutStrict}=options;Object.assign(this,optionsWithoutStrict),this.getPath=strict??!0?options.getPath??getPath:getPathNoStrict}#clone(){let clone2=new Hono2({router:this.router,getPath:this.getPath});return clone2.errorHandler=this.errorHandler,clone2.#notFoundHandler=this.#notFoundHandler,clone2.routes=this.routes,clone2}#notFoundHandler=notFoundHandler;errorHandler=errorHandler;route(path,app){let subApp=this.basePath(path);return app.routes.map(r=>{let handler;app.errorHandler===errorHandler?handler=r.handler:(handler=async(c,next)=>(await compose([],app.errorHandler)(c,()=>r.handler(c,next))).res,handler[COMPOSED_HANDLER]=r.handler),subApp.#addRoute(r.method,r.path,handler,r.basePath)}),this}basePath(path){let subApp=this.#clone();return subApp._basePath=mergePath(this._basePath,path),subApp}onError=handler=>(this.errorHandler=handler,this);notFound=handler=>(this.#notFoundHandler=handler,this);mount(path,applicationHandler,options){let replaceRequest,optionHandler;options&&(typeof options=="function"?optionHandler=options:(optionHandler=options.optionHandler,options.replaceRequest===!1?replaceRequest=request=>request:replaceRequest=options.replaceRequest));let getOptions=optionHandler?c=>{let options2=optionHandler(c);return Array.isArray(options2)?options2:[options2]}:c=>{let executionContext;try{executionContext=c.executionCtx}catch{}return[c.env,executionContext]};replaceRequest||=(()=>{let mergedPath=mergePath(this._basePath,path),pathPrefixLength=mergedPath==="/"?0:mergedPath.length;return request=>{let url2=new URL(request.url);return url2.pathname=this.getPath(request).slice(pathPrefixLength)||"/",new Request(url2,request)}})();let handler=async(c,next)=>{let res=await applicationHandler(replaceRequest(c.req.raw),...getOptions(c));if(res)return res;await next()};return this.#addRoute("ALL",mergePath(path,"*"),handler),this}#addRoute(method,path,handler,baseRoutePath){path=mergePath(this._basePath,path);let r={basePath:baseRoutePath!==void 0?mergePath(this._basePath,baseRoutePath):this._basePath,path,method,handler};this.router.add(method,path,[handler,r]),this.routes.push(r)}#handleError(err,c){if(err instanceof Error)return this.errorHandler(err,c);throw err}#dispatch(request,executionCtx,env2,method){if(method==="HEAD")return(async()=>new Response(null,await this.#dispatch(request,executionCtx,env2,"GET")))();let path=this.getPath(request,{env:env2}),matchResult=this.router.match(method,path),c=new Context(request,{path,matchResult,env:env2,executionCtx,notFoundHandler:this.#notFoundHandler});if(matchResult[0].length===1){let res;try{res=matchResult[0][0][0][0](c,async()=>{c.res=await this.#notFoundHandler(c)})}catch(err){return this.#handleError(err,c)}return res instanceof Promise?res.then(resolved=>resolved||(c.finalized?c.res:this.#notFoundHandler(c))).catch(err=>this.#handleError(err,c)):res??this.#notFoundHandler(c)}let composed=compose(matchResult[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let context=await composed(c);if(!context.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return context.res}catch(err){return this.#handleError(err,c)}})()}fetch=(request,...rest)=>this.#dispatch(request,rest[1],rest[0],request.method);request=(input,requestInit,Env,executionCtx)=>input instanceof Request?this.fetch(requestInit?new Request(input,requestInit):input,Env,executionCtx):(input=input.toString(),this.fetch(new Request(/^https?:\/\//.test(input)?input:`http://localhost${mergePath("/",input)}`,requestInit),Env,executionCtx));fire=()=>{addEventListener("fetch",event=>{event.respondWith(this.#dispatch(event.request,event,void 0,event.request.method))})}};var createNullObject=()=>Object.create(null);var emptyParam=[];function match(method,path){let matchers=this.buildAllMatchers(),match2=((method2,path2)=>{let matcher=matchers[method2]||matchers.ALL,staticMatch=matcher[2][path2];if(staticMatch)return staticMatch;let match3=path2.match(matcher[0]);if(!match3)return[[],emptyParam];let index=match3.indexOf("",1);return[matcher[1][index],match3]});return this.match=match2,match2(method,path)}var LABEL_REG_EXP_STR="[^/]+";var TAIL_WILDCARD_REG_EXP_STR="(?:|/.*)",PATH_ERROR=Symbol(),regExpMetaChars=new Set(".\\+*[^]$()");function compareKey(a,b){return a.length===1?b.length===1?a<b?-1:1:-1:b.length===1?1:a===".*"||a==="(?:|/.*)"?b==="(?:|/.*)"?-1:1:b===".*"||b==="(?:|/.*)"?-1:a==="[^/]+"?1:b==="[^/]+"?-1:a.length===b.length?a<b?-1:1:b.length-a.length}var Node=class Node2{#index;#varIndex;#children=createNullObject();insert(tokens,index,paramMap,context,isStatic){let node=this;for(let i=0,len=tokens.length;i<len;i++){let token=tokens[i],pattern=token.length===1?token==="*"?i===len-1?["","",".*"]:["","",LABEL_REG_EXP_STR]:null:token==="/*"?["","",TAIL_WILDCARD_REG_EXP_STR]:token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),nextNode;if(pattern){let name=pattern[1],regexpStr=pattern[2]||"[^/]+";if(name&&pattern[2]&&(regexpStr===".*"||(regexpStr=regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(regexpStr))||regexpStr.length===1&&regExpMetaChars.has(regexpStr)))throw PATH_ERROR;if(nextNode=node.#children[regexpStr],!nextNode){if(regexpStr!==".*"&&regexpStr!=="(?:|/.*)"){for(let k in node.#children)if((regexpStr.length>1||k.length>1)&&k!==".*"&&k!=="(?:|/.*)")throw PATH_ERROR}nextNode=node.#children[regexpStr]=new Node2}name!==""&&(nextNode.#varIndex??=context.varIndex++,paramMap.push([name,nextNode.#varIndex]))}else if(nextNode=node.#children[token],!nextNode){for(let k in node.#children)if(k.length>1&&k!==".*"&&k!=="(?:|/.*)")throw PATH_ERROR;nextNode=node.#children[token]=new Node2}node=nextNode}if(node.#index!==void 0)throw PATH_ERROR;node.#index=isStatic?-1:index}buildRegExpStr(){let strList=Object.keys(this.#children).sort(compareKey).map(k=>{let c=this.#children[k],childStr=c.buildRegExpStr();return childStr===""?"":(typeof c.#varIndex=="number"?`(${k})@${c.#varIndex}`:regExpMetaChars.has(k)?`\\${k}`:k)+childStr}).filter(Boolean);return typeof this.#index=="number"&&this.#index!==-1&&strList.unshift(`#${this.#index}`),strList.length===0?"":strList.length===1?strList[0]:"(?:"+strList.join("|")+")"}};var Trie=class{#context={varIndex:0};#root=new Node;#index=0;paths=createNullObject();insert(path,isStatic){if(isStatic){this.#root.insert(path.split(""),0,[],this.#context,!0);return}let paramAssoc=[],groups=[],markedPath=path;for(let i=0;;){let replaced=!1;if(markedPath=markedPath.replace(/\{[^}]+\}/g,m=>{let mark=`@\\${i}`;return groups[i]=[mark,m],i++,replaced=!0,mark}),!replaced)break}let tokens=markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=groups.length-1;i>=0;i--){let[mark]=groups[i];for(let j=tokens.length-1;j>=0;j--)if(tokens[j].indexOf(mark)!==-1){tokens[j]=tokens[j].replace(mark,groups[i][1]);break}}this.#root.insert(tokens,this.#index,paramAssoc,this.#context,!1),this.paths[path]=[this.#index++,paramAssoc]}buildRegExp(){let regexp=this.#root.buildRegExpStr();if(regexp==="")return[/^$/,[],[]];let captureIndex=0,indexReplacementMap=[],paramReplacementMap=[];return regexp=regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g,(_,handlerIndex,paramIndex)=>handlerIndex!==void 0?(indexReplacementMap[++captureIndex]=Number(handlerIndex),"$()"):(paramIndex!==void 0&&(paramReplacementMap[Number(paramIndex)]=++captureIndex),"")),[new RegExp(`^${regexp}`),indexReplacementMap,paramReplacementMap]}};var wildcardRegExpCache=createNullObject();function buildWildcardRegExp(path){return wildcardRegExpCache[path]??=new RegExp(`^${path.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(match2,metaChar)=>metaChar?`\\${metaChar}`:match2==="/*"?TAIL_WILDCARD_REG_EXP_STR:match2==="*"?".*":`/:${LABEL_REG_EXP_STR}`)}$`)}function findMiddleware(middleware,path){for(let k of Object.keys(middleware).sort((a,b)=>b.length-a.length))if(buildWildcardRegExp(k).test(path))return[...middleware[k]]}var RegExpRouter=class{name="RegExpRouter";#middleware;#routes;#tries;constructor(){this.#middleware={ALL:createNullObject()},this.#routes={ALL:createNullObject()},this.#tries={ALL:new Trie}}#insertPath(method,path){try{this.#tries[method].insert(path,!/\*|\/:/.test(path))}catch(e){throw e===PATH_ERROR?new UnsupportedPathError(path):e}}add(method,path,handler){let middleware=this.#middleware,routes=this.#routes;if(!middleware)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);if(!middleware[method]){this.#tries[method]=new Trie;for(let handlerMap of[middleware,routes]){handlerMap[method]=createNullObject();for(let p in handlerMap.ALL)handlerMap[method][p]=[...handlerMap.ALL[p]],this.#insertPath(method,p)}}path==="/*"&&(path="*");let methods=method==="ALL"?Object.keys(middleware):[method];if(/\*$/.test(path)){let re=buildWildcardRegExp(path);for(let m of methods)middleware[m][path]||(this.#insertPath(m,path),middleware[m][path]=findMiddleware(middleware[m],path)||findMiddleware(middleware.ALL,path)||[]);for(let handlerMap of[middleware,routes])for(let m of methods)for(let p in handlerMap[m])re.test(p)&&handlerMap[m][p].push([handler,path]);return}let paths=checkOptionalParameter(path)||[path];for(let path2 of paths)for(let m of methods)routes[m][path2]||(this.#insertPath(m,path2),routes[m][path2]=findMiddleware(middleware[m],path2)||findMiddleware(middleware.ALL,path2)||[]),routes[m][path2].push([handler,path2])}match=match;buildAllMatchers(){let matchers=createNullObject();for(let method of Object.keys(this.#routes))matchers[method]=this.#buildMatcher(method);return this.#middleware=this.#routes=this.#tries=void 0,wildcardRegExpCache=createNullObject(),matchers}#buildMatcher(method){let middleware=this.#middleware[method],routes=this.#routes[method],trie=this.#tries[method],staticMap=createNullObject(),handlerData=[],[regexp,indexReplacementMap,paramReplacementMap]=trie.buildRegExp();for(let r of[middleware,routes])for(let path in r){let handlers=r[path],pathData=trie.paths[path];if(!pathData){staticMap[path]=[handlers.map(([h])=>[h,createNullObject()]),emptyParam];continue}handlerData[pathData[0]]=handlers.map(([h,handlerPath])=>[h,trie.paths[handlerPath][1].reduceRight((map,[key],i)=>(map[key]=paramReplacementMap[pathData[1][i][1]],map),createNullObject())])}return[regexp,indexReplacementMap.map(i=>handlerData[i]),staticMap]}};var SmartRouter=class{name="SmartRouter";#routers=[];#routes=[];constructor(init){this.#routers=init.routers}add(method,path,handler){if(!this.#routes)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);this.#routes.push([method,path,handler])}match(method,path){if(!this.#routes)throw new Error("Fatal error");let routers=this.#routers,routes=this.#routes,len=routers.length,i=0,res;for(;i<len;i++){let router=routers[i];try{for(let i2=0,len2=routes.length;i2<len2;i2++)router.add(...routes[i2]);res=router.match(method,path)}catch(e){if(e instanceof UnsupportedPathError)continue;throw e}this.match=router.match.bind(router),this.#routers=[router],this.#routes=void 0;break}if(i===len)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,res}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw new Error("No active router has been determined yet.");return this.#routers[0]}};var emptyParams=createNullObject(),order=0,Node3=class Node4{#methods=[];#children=createNullObject();#patterns=[];#pattern;#params=emptyParams;insert(method,path,handler){let curNode=this,parts=splitRoutingPath(path),possibleKeys=new Set,i=0;for(let p of parts){let nextP=parts[++i],pattern=getPattern(p,nextP)||(nextP===void 0&&p&&p.indexOf("*")===p.length-1?p:null),isParam=Array.isArray(pattern),key=isParam?pattern[0]:pattern||p,child=curNode.#children[key]||=new Node4;pattern&&!child.#pattern&&(child.#pattern=pattern,curNode.#patterns.push(child)),curNode=child,isParam&&possibleKeys.add(pattern[1])}curNode.#methods.push({[method]:{handler,possibleKeys:[...possibleKeys],score:++order}})}#pushHandlerSets(handlerSets,node,method,nodeParams,params){for(let i=0,len=node.#methods.length;i<len;i++){let m=node.#methods[i],handlerSet=m[method]||m.ALL;if(handlerSet){handlerSet.params=createNullObject(),handlerSets.push(handlerSet);for(let i2=0,len2=handlerSet.possibleKeys.length;i2<len2;i2++){let key=handlerSet.possibleKeys[i2];handlerSet.params[key]=params?.[key]&&!i2?params[key]:nodeParams[key]??params?.[key]}}}}search(method,path){let handlerSets=[];this.#params=emptyParams;let curNodes=[this],parts=splitPath(path),curNodesQueue=[],len=parts.length,partOffsets=null;for(let i=0;i<len;i++){let part=parts[i],isLast=i===len-1,tempNodes=[];for(let j=0,len2=curNodes.length;j<len2;j++){let node=curNodes[j],nextNode=node.#children[part];nextNode&&(nextNode.#params=node.#params,isLast?(nextNode.#children["*"]&&this.#pushHandlerSets(handlerSets,nextNode.#children["*"],method,node.#params),this.#pushHandlerSets(handlerSets,nextNode,method,node.#params)):tempNodes.push(nextNode));for(let child of node.#patterns){let pattern=child.#pattern,params=node.#params===emptyParams?{}:{...node.#params};if(typeof pattern=="string"){(pattern==="*"||part.startsWith(pattern.slice(0,-1)))&&(this.#pushHandlerSets(handlerSets,child,method,node.#params),pattern==="*"&&(child.#params=params,tempNodes.push(child)));continue}let[,name,matcher]=pattern;if(!(!part&&matcher===!0)){if(matcher!==!0){if(!partOffsets){partOffsets=[];let offset=path[0]==="/"?1:0;for(let p=0;p<len;p++)partOffsets[p]=offset,offset+=parts[p].length+1}let restPathString=path.slice(partOffsets[i]),m=matcher.exec(restPathString);if(m){params[name]=m[0],this.#pushHandlerSets(handlerSets,child,method,node.#params,params),m[0].length===restPathString.length&&child.#children["*"]&&this.#pushHandlerSets(handlerSets,child.#children["*"],method,node.#params,params);for(let _ in child.#children){child.#params=params;let componentCount=m[0].match(/\//g)?.length??0;(curNodesQueue[componentCount]||=[]).push(child);break}continue}}(matcher===!0||matcher.test(part))&&(params[name]=part,isLast?(this.#pushHandlerSets(handlerSets,child,method,params,node.#params),child.#children["*"]&&this.#pushHandlerSets(handlerSets,child.#children["*"],method,params,node.#params)):(child.#params=params,tempNodes.push(child)))}}}let shifted=curNodesQueue.shift();curNodes=shifted?tempNodes.concat(shifted):tempNodes}return handlerSets[1]&&handlerSets.sort((a,b)=>a.score-b.score),[handlerSets.map(({handler,params})=>[handler,params])]}};var TrieRouter=class{name="TrieRouter";#node=new Node3;add(method,path,handler){for(let result of checkOptionalParameter(path)||[path])this.#node.insert(method,result,handler)}match(method,path){return this.#node.search(method,path)}};var Hono3=class extends Hono{constructor(options={}){super(options),this.router=options.router??new SmartRouter({routers:[new RegExpRouter,new TrieRouter]})}};init_origin();init_public_route();var FAVICON_CACHE_CONTROL="public, max-age=31536000, immutable",FAVICON_REDIRECT_CACHE_CONTROL="public, max-age=300";function protocolOf(value){return/^([a-z][a-z\d+.-]*):/i.exec(value)?.[1]?.toLowerCase()}function publicAssetPath(basePath,source){return`${basePath==="/"?"":basePath}/_mcp-use/public/${source.split("/").map(segment=>encodeURIComponent(segment)).join("/")}`}function isLocalPublicSource(source){return protocolOf(source)===void 0}function selectFaviconFromIcons(icons){return icons[0]}function assertLocalPublicSource(source,field){if(source.startsWith("/")||source.includes("\\")||source.includes("?")||source.includes("#")||source.split("/").some(segment=>segment===""||segment===".."))throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`)}function parseDataImage(source,field){let comma=source.indexOf(",");if(comma<0)throw new TypeError(`${field} must be a valid image data URL`);let metadata=source.slice(5,comma),payload=source.slice(comma+1),parts=metadata.split(";"),mimeType=parts[0]?.toLowerCase()??"";if(!mimeType.startsWith("image/"))throw new TypeError(`${field} data URL must use an image MIME type`);try{if(parts.includes("base64")){let binary2=atob(payload);return{mimeType,bytes:Uint8Array.from(binary2,character=>character.charCodeAt(0))}}return{mimeType,bytes:new TextEncoder().encode(decodeURIComponent(payload))}}catch{throw new TypeError(`${field} must be a valid image data URL`)}}function assertBrandingSource(source,field){if(typeof source!="string"||source.length===0)throw new TypeError(`${field} must be a non-empty string`);let protocol=protocolOf(source);if(protocol===void 0)return assertLocalPublicSource(source,field),source;if(protocol==="data")return parseDataImage(source,field),source;if(protocol!=="http"&&protocol!=="https")throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(source)}catch{throw new TypeError(`${field} must be a valid absolute http(s) URL`)}return source}function normalizeServerBranding(config2){let websiteUrl;if(config2.websiteUrl!==void 0){if(typeof config2.websiteUrl!="string"||config2.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let parsed;try{parsed=new URL(config2.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");websiteUrl=config2.websiteUrl}let icons;if(config2.icons!==void 0){if(!Array.isArray(config2.icons))throw new TypeError("icons must be an array of MCP Icon objects");icons=Object.freeze(config2.icons.map((value,index)=>{if(typeof value!="object"||value===null)throw new TypeError(`icons[${index}] must be an MCP Icon object`);let icon=value,src=assertBrandingSource(icon.src,`icons[${index}].src`),mimeType=icon.mimeType;if(mimeType!==void 0&&(typeof mimeType!="string"||!mimeType.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${index}].mimeType must be an image MIME type when provided`);let sizes=icon.sizes;if(sizes!==void 0&&(!Array.isArray(sizes)||sizes.some(size=>typeof size!="string"||size.length===0)))throw new TypeError(`icons[${index}].sizes must be an array of non-empty strings when provided`);let normalizedSizes=sizes===void 0?void 0:sizes.map(size=>size),theme=icon.theme;if(theme!==void 0&&theme!=="light"&&theme!=="dark")throw new TypeError(`icons[${index}].theme must be "light" or "dark" when provided`);return Object.freeze({src,...mimeType!==void 0&&{mimeType},...normalizedSizes!==void 0&&{sizes:Object.freeze(normalizedSizes)},...theme!==void 0&&{theme}})}))}let explicitFavicon=config2.favicon===void 0?void 0:assertBrandingSource(config2.favicon,"favicon"),inferred=explicitFavicon===void 0?selectFaviconFromIcons(icons??[]):void 0,favicon=explicitFavicon??inferred?.src,faviconMimeType=inferred?.mimeType??icons?.find(icon=>icon.src===explicitFavicon)?.mimeType;return Object.freeze({...favicon!==void 0&&{favicon},...faviconMimeType!==void 0&&{faviconMimeType},...icons!==void 0&&{icons},...websiteUrl!==void 0&&{websiteUrl}})}function resolveImplementationIcons(icons,request,basePath){return icons.map(icon=>({...icon,src:request!==void 0&&isLocalPublicSource(icon.src)?`${resolveAssetsBase(request)}${publicAssetPath(basePath,icon.src)}`:icon.src,...icon.sizes!==void 0&&{sizes:[...icon.sizes]}}))}function hasLocalBrandingAsset(branding){return branding.favicon!==void 0&&isLocalPublicSource(branding.favicon)||branding.icons?.some(icon=>isLocalPublicSource(icon.src))===!0}function createFaviconHandler(branding,options){let source=branding.favicon;if(source!==void 0)return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(request.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let protocol=protocolOf(source);if(protocol==="http"||protocol==="https")return new Response(null,{status:307,headers:{Location:source,"Cache-Control":FAVICON_REDIRECT_CACHE_CONTROL}});if(protocol==="data"){let data=parseDataImage(source,"favicon");return new Response(request.method==="HEAD"?null:data.bytes.buffer,{status:200,headers:{"Content-Type":branding.faviconMimeType??data.mimeType,"Cache-Control":FAVICON_CACHE_CONTROL,"X-Content-Type-Options":"nosniff"}})}let{join}=await import("path"),publicRoot=options.dev?join(options.projectRoot,"public"):join(options.projectRoot,".mcp-use/build/views/public"),diskPath=await resolvePublicFilePath(publicRoot,source);if(diskPath===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let response=await servePublicFile(diskPath,{...options.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}});return response.headers.set("Cache-Control",FAVICON_CACHE_CONTROL),response.headers.set("X-Content-Type-Options","nosniff"),branding.faviconMimeType!==void 0&&response.headers.set("Content-Type",branding.faviconMimeType),response}}function isOAuthProviderLike(value){if(typeof value!="object"||value===null)return!1;let provider=value;return typeof provider.createTokenVerifier=="function"&&typeof provider.mapAuthInfo=="function"&&(typeof provider.oauthMetadata=="object"&&provider.oauthMetadata!==null||typeof provider.oauthMetadata=="function")}function assertServerConfig(config2){if(config2.mixedAuth!==void 0&&typeof config2.mixedAuth!="boolean")throw new TypeError("mixedAuth must be a boolean");if(config2.mixedAuth===!0&&!isOAuthProviderLike(config2.oauth))throw new TypeError("mixedAuth requires an OAuth provider; set oauth on the server");if(config2.basePath!==void 0){if(typeof config2.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath}=config2;if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#")||/\s/.test(basePath)||basePath.includes("//")||basePath.length>1&&basePath.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(config2.port!==void 0&&(typeof config2.port!="number"||!Number.isInteger(config2.port)||config2.port<0||config2.port>65535))throw new TypeError("port must be an integer between 0 and 65535");if(config2.skills!==void 0&&typeof config2.skills!="boolean"){if(typeof config2.skills!="object"||config2.skills===null||Array.isArray(config2.skills))throw new TypeError("skills must be a boolean or configuration object");let directory=config2.skills.directory;if(directory!==void 0&&typeof directory!="string")throw new TypeError("skills.directory must be a string when provided")}}var DEFAULT_LISTEN_HOST="127.0.0.1";function resolveListenHost(explicitHost,configuredHost,env2=process.env){if(explicitHost!==void 0)return explicitHost;let envHost=env2.HOST?.trim();return envHost!==void 0&&envHost!==""?envHost:configuredHost??DEFAULT_LISTEN_HOST}function resolveListenPort(explicitPort,configuredPort,env2=process.env){if(explicitPort!==void 0)return explicitPort;let envPort=parsePort(env2.PORT);return envPort!==void 0?envPort:configuredPort??3e3}function parsePort(value){if(value===void 0||value.trim()==="")return;let port=Number(value);return Number.isInteger(port)&&port>=0&&port<=65535?port:void 0}import{isBufferedResponse}from"#mcp-use-buffered-response";function toNodeHandler(handler,opts){return async(req,res,parsedBody)=>{typeof parsedBody=="function"&&(parsedBody=void 0);let finished=!1,abort=new AbortController;res.on("close",()=>{finished||abort.abort()}),res.destroyed===!0&&abort.abort();let request,response;try{request=await toWebRequest(req,parsedBody,{signal:abort.signal}),response=await handler.fetch(request,{...req.auth!==void 0&&{authInfo:req.auth},...parsedBody!==void 0&&{parsedBody}})}catch(error3){try{opts?.onerror?.(error3 instanceof Error?error3:new Error(String(error3)))}catch{}response=internalServerErrorResponse2(echoableRequestId2(parsedBody))}let headers={},setCookies=response.headers.getSetCookie?.();for(let[name,value]of response.headers){if(name==="set-cookie"&&setCookies?.length){headers[name]=setCookies;continue}headers[name]=value}if(res.writeHead(response.status,headers),response.body===null){finished=!0,res.end();return}if(isBufferedResponse(response,request)){try{let bytes=new Uint8Array(await response.arrayBuffer());finished=!0,res.end(bytes)}catch{finished=!0,res.end()}return}let drainResolve,releaseDrainWait=()=>{drainResolve?.(),drainResolve=void 0},waitForDrain=()=>new Promise(resolve=>{drainResolve=resolve});res.on("drain",releaseDrainWait);let closed=new Promise(resolve=>{abort.signal.addEventListener("abort",()=>resolve(),{once:!0})});try{for await(let chunk of response.body){if(abort.signal.aborted)break;let bytes=chunk instanceof Uint8Array?chunk:new Uint8Array(chunk);res.write(bytes)===!1&&await Promise.race([waitForDrain(),closed])}}catch{}finished=!0,res.end()}}async function toWebRequest(req,parsedBody,options){let method=(req.method??"GET").toUpperCase(),url2=`http://${singleHeaderValue(req.headers.host)??singleHeaderValue(req.headers[":authority"])??"localhost"}${req.url??"/"}`,headers=new Headers;for(let[name,value]of Object.entries(req.headers))if(!(value===void 0||name.startsWith(":")))if(Array.isArray(value))for(let item of value)headers.append(name,item);else headers.set(name,value);let body;if(method!=="GET"&&method!=="HEAD")if(parsedBody===void 0){let decoder=new TextDecoder,collected="";for await(let chunk of req)collected+=typeof chunk=="string"?chunk:decoder.decode(chunk,{stream:!0});collected+=decoder.decode(),collected.length>0&&(body=collected)}else{let serialized=JSON.stringify(parsedBody);headers.delete("content-encoding"),headers.delete("transfer-encoding"),serialized===void 0?headers.delete("content-length"):(body=serialized,headers.set("content-length",String(new TextEncoder().encode(serialized).byteLength)))}return new Request(url2,{method,headers,...options?.signal!==void 0&&{signal:options.signal},...body!==void 0&&{body}})}function singleHeaderValue(value){return Array.isArray(value)?value[0]:value}function echoableRequestId2(body){if(body===null||typeof body!="object"||Array.isArray(body))return null;let{method,id}=body;return typeof method!="string"?null:typeof id=="string"||typeof id=="number"?id:null}function internalServerErrorResponse2(id){return Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id},{status:500})}init_dist();init_fetch_app();init_dist();var UI_EXTENSION_ID="io.modelcontextprotocol/ui",UI_MIME_TYPE="text/html;profile=mcp-app",UI_RESOURCE_URI_PREFIX="ui://views/";var UI_RESOURCE_URI_META_KEY="ui/resourceUri";function viewResourceUri(viewName){return`${UI_RESOURCE_URI_PREFIX}${viewName}.html`}var clientCapabilitiesByRequest=new WeakMap;function stashClientCapabilities(request,capabilities){clientCapabilitiesByRequest.set(request,capabilities)}function extractClientCapabilitiesFromBody(body){if(typeof body!="object"||body===null)return;let params=body.params;if(typeof params!="object"||params===null)return;let meta2=params._meta;if(typeof meta2!="object"||meta2===null)return;let capabilities=meta2[CLIENT_CAPABILITIES_META_KEY];if(!(typeof capabilities!="object"||capabilities===null))return capabilities}function supportsViews(capabilities){let extensions=capabilities?.extensions;if(extensions===void 0)return!1;let uiExtension=extensions[UI_EXTENSION_ID];if(typeof uiExtension!="object"||uiExtension===null)return!1;let mimeTypes=uiExtension.mimeTypes;return Array.isArray(mimeTypes)?mimeTypes.includes(UI_MIME_TYPE):!1}function requireOAuthAuthInfo(authInfo){if(authInfo===void 0||authInfo.extra===void 0||authInfo.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function stringValue(value){return typeof value=="string"?value:void 0}function coordinateValue(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)?value:void 0}function normalizeUserContext(meta2){if(meta2===void 0)return;let locale=stringValue(meta2["openai/locale"])??stringValue(meta2["webplus/i18n"]),userAgent=stringValue(meta2["openai/userAgent"]),subject=stringValue(meta2["openai/subject"]),conversationId=stringValue(meta2["openai/session"]),organizationId=stringValue(meta2["openai/organization"]),rawLocation=meta2["openai/userLocation"],location;if(typeof rawLocation=="object"&&rawLocation!==null&&!Array.isArray(rawLocation)){let values=rawLocation,normalized={city:stringValue(values.city),region:stringValue(values.region),country:stringValue(values.country),timezone:stringValue(values.timezone),latitude:coordinateValue(values.latitude),longitude:coordinateValue(values.longitude)},entries=Object.entries(normalized).filter(entry=>entry[1]!==void 0);entries.length>0&&(location=Object.fromEntries(entries))}if(!(locale===void 0&&userAgent===void 0&&location===void 0&&subject===void 0&&conversationId===void 0&&organizationId===void 0))return{...locale!==void 0&&{locale},...userAgent!==void 0&&{userAgent},...location!==void 0&&{location},...subject!==void 0&&{subject},...conversationId!==void 0&&{conversationId},...organizationId!==void 0&&{organizationId}}}function requestEnvelope(ctx){return ctx.mcpReq.envelope}function requestClientInfo(ctx){return{...requestEnvelope(ctx)?.[CLIENT_INFO_META_KEY]??{}}}function toClientContext(ctx){let capabilities={...requestEnvelope(ctx)?.[CLIENT_CAPABILITIES_META_KEY]??{}},info=requestClientInfo(ctx),user=normalizeUserContext(ctx.mcpReq._meta);return{can(capability){return Object.hasOwn(capabilities,capability)},capabilities(){return{...capabilities}},extension(id){let settings=capabilities.extensions?.[id];return settings===void 0?void 0:{...settings}},info(){return{...info}},user(){return user===void 0?void 0:{...user,...user.location!==void 0&&{location:{...user.location}}}},supportsViews(){return supportsViews(capabilities)}}}function toRequestContext(ctx){let rawRequest=ctx.http?.req,http=rawRequest===void 0?void 0:getRequestBag(rawRequest).honoContext,request=http?.req??(rawRequest===void 0?void 0:new HonoRequest(rawRequest)),additions={signal:ctx.mcpReq.signal,...request!==void 0&&{request},...ctx.mcpReq.inputResponses!==void 0&&{inputResponses:ctx.mcpReq.inputResponses},client:toClientContext(ctx),requestState:()=>ctx.mcpReq.requestState(),async sendNotification(method,params){await ctx.mcpReq.notify({method,...params!==void 0&&{params}})},async reportProgress(progress,total,message){let progressToken=ctx.mcpReq._meta?.progressToken;return progressToken===void 0?!1:(await ctx.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}}}),!0)},async sendLog(level,data,logger){await ctx.mcpReq.notify({method:"notifications/message",params:{level,data,...logger!==void 0&&{logger}}})}};return http!==void 0?Object.assign(http,additions):{...additions,...request!==void 0&&{req:request}}}function isOAuthUpstreamToken(value){if(value===null||typeof value!="object")return!1;let token=value;return typeof token.accessToken=="string"&&Array.isArray(token.scopes)&&token.scopes.every(scope=>typeof scope=="string")&&(token.expiresAt===void 0||typeof token.expiresAt=="number")}function toAuthenticatedRequestContext(ctx){let authInfo=ctx.http?.authInfo;return requireOAuthAuthInfo(authInfo),Object.assign(toRequestContext(ctx),{auth:{user:authInfo.extra.user,payload:authInfo.extra.payload,accessToken:authInfo.token,scopes:[...authInfo.scopes],permissions:[...authInfo.extra.permissions],...authInfo.clientId.length>0&&{clientId:authInfo.clientId},expiresAt:authInfo.expiresAt,...authInfo.resource!==void 0&&{resource:authInfo.resource},...isOAuthUpstreamToken(authInfo.extra.upstream)&&{upstream:{accessToken:authInfo.extra.upstream.accessToken,scopes:[...authInfo.extra.upstream.scopes],...authInfo.extra.upstream.expiresAt!==void 0&&{expiresAt:authInfo.extra.upstream.expiresAt}}}}})}init_dist();function isReadResourceResult(result){return"contents"in result&&Array.isArray(result.contents)}function isGetPromptResult(result){return"messages"in result&&Array.isArray(result.messages)}function toResourceResult(result,uri){if(isReadResourceResult(result))return result;let mime=result._meta&&typeof result._meta=="object"&&typeof result._meta.mimeType=="string"?result._meta.mimeType:void 0,contents=[];for(let block of result.content??[]){let mapped=contentBlockToResourceContents(block,uri,mime);mapped!==void 0&&contents.push(mapped)}return contents.length===0&&result.structuredContent!==void 0&&contents.push({uri,mimeType:"application/json",text:JSON.stringify(result.structuredContent)}),contents.length===0&&contents.push({uri,mimeType:"text/plain",text:""}),{contents}}function contentBlockToResourceContents(block,uri,mimeHint){if(block.type==="text")return{uri,mimeType:mimeHint??"text/plain",text:block.text};if(block.type==="image"||block.type==="audio")return{uri,mimeType:block.mimeType,blob:block.data};if(block.type==="resource")return{...block.resource}}function toPromptResult(result){if(isInputRequiredResult(result)||isGetPromptResult(result))return result;let messages=(result.content??[]).map(content=>({role:"user",content}));return messages.length===0&&result.structuredContent!==void 0&&messages.push({role:"user",content:{type:"text",text:JSON.stringify(result.structuredContent)}}),messages.length===0&&messages.push({role:"user",content:{type:"text",text:""}}),{messages}}init_fetch_app();import{inheritBufferedResponse}from"#mcp-use-buffered-response";var DEFAULT_METHODS=["GET","HEAD","POST","OPTIONS"],DEFAULT_ALLOWED_HEADERS=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function resolveAllowedOrigin(origin,requestOrigin){return origin===void 0?requestOrigin:typeof origin=="function"?origin(requestOrigin):origin==="*"?"*":Array.isArray(origin)?requestOrigin!==null&&origin.includes(requestOrigin)?requestOrigin:null:origin}function corsHeaders(options,request){if(request.headers.has("Access-Control-Allow-Origin"))return;let requestOrigin=request.headers.get("Origin"),allowedOrigin=resolveAllowedOrigin(options.origin,requestOrigin);if(allowedOrigin===null)return;let headers={"Access-Control-Allow-Origin":allowedOrigin,"Access-Control-Allow-Methods":options.methods.join(", "),"Access-Control-Allow-Headers":options.allowedHeaders.join(", ")};return options.credentials&&(headers["Access-Control-Allow-Credentials"]="true"),allowedOrigin!=="*"&&(headers.Vary="Origin"),headers}function mergeCorsHeaders(response,headers){if(response.headers.has("Access-Control-Allow-Origin"))return response;let merged=new Headers(response.headers);return new Headers(headers).forEach((value,key)=>{merged.set(key,value)}),inheritBufferedResponse(response,new Response(response.body,{status:response.status,statusText:response.statusText,headers:merged}))}function corsFetchMiddleware(options){if(!(options.enabled!==!1))return async(_request,next)=>next();let resolved={...options.origin!==void 0&&{origin:options.origin},methods:options.methods??DEFAULT_METHODS,allowedHeaders:options.allowedHeaders??DEFAULT_ALLOWED_HEADERS,credentials:options.credentials??!1};return async(request,next)=>{let headers=corsHeaders(resolved,request);if(headers===void 0)return next();if(request.method==="OPTIONS")return new Response(null,{status:204,headers});let response=await next();return mergeCorsHeaders(response,headers)}}function isGlobalCorsEnabled(cors){return cors!==void 0&&cors.enabled!==!1}init_auth_BNDyLTqp();init_dist();var MCP_MIDDLEWARE_METHODS=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function withMcpMiddlewareParams(request,params){if(typeof request!="object"||request===null||Array.isArray(request))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...request,params}}function createMcpMiddlewareEntry(pattern,handler){let normalizedPattern=normalizeMcpMiddlewarePattern(pattern),invoke2=handler;if(normalizedPattern!=="*"&&!isMcpMiddlewareMethod(normalizedPattern))throw new TypeError(`Unsupported MCP middleware pattern "${pattern}". Use an exact MCP method or "mcp:*".`);return normalizedPattern==="*"?{pattern:normalizedPattern,handler:async(ctx,next)=>{let downstreamCalled=!1,downstreamResult;if(await invoke2(ctx,async()=>{downstreamResult=await next(),downstreamCalled=!0}),!downstreamCalled)throw new Error(`Wildcard MCP middleware "${normalizedPattern}" must call next()`);return downstreamResult}}:{pattern:normalizedPattern,handler:(ctx,next)=>invoke2(ctx,next)}}function createMcpEventListenerEntry(pattern,handler){let{pattern:normalizedPattern,phase}=parseMcpPattern(pattern),invoke2=handler;return{pattern:normalizedPattern,phase,handler:(ctx,result)=>invoke2(ctx,result)}}function matchesPattern(pattern,method){if(pattern==="*")return!0;if(pattern.endsWith("/*")){let prefix=pattern.slice(0,-1);return method.startsWith(prefix)}return pattern===method}function isMcpMiddlewareMethod(value){return MCP_MIDDLEWARE_METHODS.some(method=>method===value)}function composeMiddleware(entries,method,innerFn){let matching=entries.filter(entry=>matchesPattern(entry.pattern,method));return matching.length===0?_ctx=>innerFn():ctx=>{let index=-1,dispatch=i=>i<=index?Promise.reject(new Error("next() called multiple times")):(index=i,i===matching.length?innerFn():matching[i].handler(ctx,()=>dispatch(i+1)));return dispatch(0)}}function freezeMiddlewareContext(ctx){return Object.freeze({method:ctx.method,params:Object.freeze({...ctx.params}),...ctx.request!==void 0&&{request:ctx.request},...ctx.req!==void 0&&{req:ctx.req},...ctx.session!==void 0&&{session:Object.freeze({...ctx.session})},...ctx.auth!==void 0&&{auth:ctx.auth},state:new Map(ctx.state)})}async function runMcpOperation(middlewares,events,method,ctx,innerFn){dispatchMcpEvents(events,method,"before",ctx);let result=await composeMiddleware(middlewares,method,innerFn)(ctx);return assertValidMiddlewareResult(method,result),dispatchMcpEvents(events,method,"complete",ctx,result),result}function assertValidMiddlewareResult(method,result){if((method==="tools/call"||method==="resources/read"||method==="prompts/get")&&isInputRequiredResult(result))return;let validation=(()=>{switch(method){case"tools/call":return assertArrayProperty(method,result,"content"),CallToolResultSchema.safeParse(result);case"tools/list":return assertArrayResult(method,result),ListToolsResultSchema.safeParse({tools:result});case"resources/read":return assertArrayProperty(method,result,"contents"),ReadResourceResultSchema.safeParse(result);case"resources/list":return assertArrayResult(method,result),ListResourcesResultSchema.safeParse({resources:result});case"prompts/get":return assertArrayProperty(method,result,"messages"),GetPromptResultSchema.safeParse(result);case"prompts/list":return assertArrayResult(method,result),ListPromptsResultSchema.safeParse({prompts:result});default:throw new TypeError(`Unsupported MCP middleware method "${method}"`)}})();if(!validation.success)throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: ${validation.error.message}`)}function assertArrayResult(method,result){if(!Array.isArray(result))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected an array`)}function assertArrayProperty(method,result,property){if(typeof result!="object"||result===null||!Array.isArray(result[property]))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected a ${property} array`)}function dispatchMcpEvents(events,method,phase,ctx,result){let frozen=freezeMiddlewareContext(ctx);for(let entry of events)if(!(entry.phase!==phase||!matchesPattern(entry.pattern,method)))try{entry.handler(frozen,result)}catch(error3){console.error(`[mcp-use] MCP event listener for "${entry.pattern}" (${phase}) threw:`,error3)}}function parseMcpPattern(raw2){let pattern=raw2.startsWith("mcp:")?raw2.slice(4):raw2;return pattern.endsWith(":complete")?{pattern:pattern.slice(0,-9),phase:"complete"}:{pattern,phase:"before"}}function normalizeMcpMiddlewarePattern(raw2){return raw2.startsWith("mcp:")?raw2.slice(4):raw2}init_dist();init_fetch_app();import{isBufferedResponse as isBufferedResponse2,trackBufferedResponse}from"#mcp-use-buffered-response";function colorsEnabled(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function ansi(open,close){return text2=>colorsEnabled()?`\x1B[${open}m${text2}\x1B[${close}m`:text2}var bold=ansi(1,22),dim=ansi(2,22),red=ansi(31,39),green=ansi(32,39),yellow=ansi(33,39),blue=ansi(34,39),magenta=ansi(35,39),cyan=ansi(36,39),gray=ansi(90,39);function resolveLogLevel(configured){let raw2=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return raw2==="info"||raw2==="debug"||raw2==="trace"?raw2:configured??"info"}function formatClientInfo(info){if(!(info===void 0||typeof info.name!="string"))return typeof info.version=="string"&&info.version!==""?`${info.name}/${info.version}`:info.name}var detailFormatters={initialize:p=>({subject:formatClientInfo(p.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":p=>({subject:p.ref.type==="ref/prompt"?p.ref.name:p.ref.uri,input:p.argument}),"logging/setLevel":p=>({subject:p.level}),"prompts/get":p=>({subject:p.name,input:p.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":p=>({subject:p.uri}),"resources/subscribe":p=>({subject:p.uri}),"resources/unsubscribe":p=>({subject:p.uri}),"subscriptions/listen":()=>({}),"tools/call":p=>({subject:p.name,input:p.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function isKnownMethod(method){return Object.prototype.hasOwnProperty.call(detailFormatters,method)}function formatDetail(message){if(!isKnownMethod(message.method))return{};try{let formatter=detailFormatters[message.method],detail=formatter(message.params);return typeof detail.subject=="string"||detail.subject===void 0?detail:{}}catch{return{}}}var INLINE_JSON_MAX_LENGTH=80;function inlineJson(value){let text2;try{text2=JSON.stringify(value)??String(value)}catch{text2=String(value)}return text2.length>INLINE_JSON_MAX_LENGTH?`${text2.slice(0,INLINE_JSON_MAX_LENGTH)}...`:text2}function formatClientIdentity(message){let meta2=message.params?._meta;if(meta2===void 0)return;let info=meta2[CLIENT_INFO_META_KEY];if(!(typeof info!="object"||info===null||typeof info.name!="string"))return formatClientInfo(info)}function formatMcpClient(message){let modern=formatClientIdentity(message);if(modern!==void 0)return modern;if(message.method==="initialize")try{return formatClientInfo(message.params.clientInfo)}catch{return}}function sanitize(text2){return text2.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function methodStyle(method){return method.startsWith("tools/")?cyan:method.startsWith("resources/")?green:method.startsWith("prompts/")?magenta:method==="initialize"||method==="ping"?gray:blue}function describeRequest(httpMethod,pathname,mcpPath,body){if(pathname!==mcpPath)return{method:httpMethod,client:void 0,mcpRequest:void 0,streaming:!1};let requests=Array.isArray(body)?body.filter(isJSONRPCRequest):isJSONRPCRequest(body)?[body]:[],mcpRequest=requests[0];return mcpRequest===void 0?{method:httpMethod,client:void 0,mcpRequest:void 0,streaming:!1}:{method:requests.length===1?sanitize(mcpRequest.method):`batch(${requests.map(request=>sanitize(request.method)).join(",")})`,client:formatMcpClient(mcpRequest)??"unknown",mcpRequest,streaming:mcpRequest.method==="subscriptions/listen"}}var REDACTED_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function redactHeaders(headers){return Object.fromEntries(Object.entries(headers).map(([name,value])=>[name,REDACTED_HEADERS.has(name.toLowerCase())?"[REDACTED]":value]))}async function extractResponseOutcome(res,request){if(!res.body)return{errorMessage:null};let text2;try{let wasBuffered=isBufferedResponse2(res,request),clone2=res.clone();wasBuffered&&trackBufferedResponse(request,res),text2=await clone2.text()}catch{return{errorMessage:null}}if(!text2)return{errorMessage:null};let isSse=(res.headers.get("content-type")??"").includes("text/event-stream"),payloads=[],tryParse=raw2=>{try{payloads.push(JSON.parse(raw2))}catch{}};if(isSse){for(let line of text2.split(/\r?\n/))if(line.startsWith("data:")){let data=line.slice(5).trim();data&&tryParse(data)}}else tryParse(text2);let result;for(let payload of payloads){if(payload===null||typeof payload!="object")continue;let message=payload;if(typeof message.error?.message=="string")return{errorMessage:message.error.message};if(message.result?.isError===!0){let textBlock=(Array.isArray(message.result.content)?message.result.content:[]).find(b=>b?.type==="text"&&typeof b.text=="string");return{errorMessage:textBlock?String(textBlock.text):"tool error"}}"result"in message&&(result=message.result)}return{errorMessage:null,result}}function compactToolResult(result){if(result===null||typeof result!="object")return result;let{structuredContent,content}=result;if(structuredContent!==void 0)return structuredContent;if(Array.isArray(content)){let[block]=content;if(content.length===1&&block?.type==="text")return block.text}return content}function formatForDump(value){function truncate(val){return typeof val=="string"&&val.length>100?`${val.slice(0,100)}...`:Array.isArray(val)?val.map(truncate):val!==null&&typeof val=="object"?Object.fromEntries(Object.entries(val).map(([k,v])=>[k,truncate(v)])):val}try{return JSON.stringify(truncate(value),null,2)}catch{return String(value)}}var DUMP_BODY_MAX_LENGTH=1e4;async function printTraceDump(response,requestHeaders,requestBody,readResponseBody){console.log(`
784
+ </html>`}async function createLandingPageResponse(request,basePath,config2,branding,tools,prompts,resources,registration,cache){let origin=resolveServerOrigin(request),url2=new URL(basePath,`${origin}/`).href,assetsBase=resolveAssetsBase(request),basePrefix=basePath==="/"?"":basePath,server={name:config2.name,...config2.title!==void 0&&{title:config2.title},version:config2.version,...config2.description!==void 0&&{description:config2.description},url:url2,...branding.websiteUrl!==void 0&&{websiteUrl:branding.websiteUrl},...branding.favicon!==void 0&&{iconUrl:new URL("/favicon.ico",`${origin}/`).href,...branding.faviconMimeType!==void 0&&{iconType:branding.faviconMimeType}},publicBaseUrl:`${assetsBase}${basePrefix}/_mcp-use/public/`},listTools=()=>Array.from(tools,({definition})=>({name:definition.name,...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description}})),listPrompts=()=>Array.from(prompts,({definition})=>({name:definition.name,...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description}})),listResources=()=>Array.from(resources,({definition})=>({uri:definition.uri,...definition.name!==void 0&&{name:definition.name},...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description}})),landingData=keys2=>{let dataKeys=new Set(keys2);return{server,...dataKeys.has("tools")&&{tools:listTools()},...dataKeys.has("prompts")&&{prompts:listPrompts()},...dataKeys.has("resources")&&{resources:listResources()}}},html2=registration===void 0?generateLandingPage({...server,tools:listTools(),prompts:listPrompts(),resources:listResources()}):request.method==="HEAD"?void 0:await(async()=>{let key=`${url2}\0${assetsBase}`,cached2=registration.dev===!0?void 0:cache?.get(key);if(cached2!==void 0)return cached2;let rendering=(async()=>{let{render,dataKeys,metadata,importedCss}="load"in registration?await registration.load():registration,data=landingData(dataKeys);return renderDocument(data,await render(data),registration,importedCss??[],readLandingMetadata(metadata),origin,assetsBase,basePath)})();if(registration.dev!==!0&&cache!==void 0){if(cache.size>=MAX_CACHED_DOCUMENTS){let oldest=cache.keys().next().value;oldest!==void 0&&cache.delete(oldest)}cache.set(key,rendering),rendering.catch(()=>{cache.get(key)===rendering&&cache.delete(key)})}return rendering})();return new Response(request.method==="HEAD"?null:html2,{status:200,headers:{"cache-control":"no-store","content-type":"text/html; charset=utf-8","x-content-type-options":"nosniff"}})}var MAX_CACHED_DOCUMENTS,THEME_SCRIPT,METADATA_FIELDS,reportedMetadataWarnings,init_landing_handler=__esm({"src/landing-handler.ts"(){"use strict";init_landing();init_origin();MAX_CACHED_DOCUMENTS=32,THEME_SCRIPT='<script>(()=>{const d=document.documentElement,q=matchMedia("(prefers-color-scheme: dark)");let s;const a=()=>{if(d.dataset.theme!==s)return;s=q.matches?"dark":"light";d.dataset.theme=s};a();q.addEventListener("change",a)})()</script>';METADATA_FIELDS=["title","description","icon","image"],reportedMetadataWarnings=new Set}});var DEFAULT_DISPLAY_MODES=["inline","fullscreen","pip"],VALID_DISPLAY_MODES=new Set(["inline","fullscreen","pip"]);function normalizeViewConfig(config2){let autoResize=config2?.autoResize??!0,modes=config2?.displayModes===void 0?DEFAULT_DISPLAY_MODES:config2.displayModes;if(!Array.isArray(modes)||modes.length===0)throw new Error('viewConfig.displayModes must be a non-empty array that includes "inline"');let seen=new Set,normalizedModes=[];for(let mode of modes){if(typeof mode!="string"||!VALID_DISPLAY_MODES.has(mode))throw new Error(`viewConfig.displayModes contains invalid mode ${JSON.stringify(mode)}; expected "inline", "fullscreen", or "pip"`);if(seen.has(mode))throw new Error(`viewConfig.displayModes contains duplicate mode "${mode}"`);seen.add(mode),normalizedModes.push(mode)}if(!seen.has("inline"))throw new Error('viewConfig.displayModes must include "inline"');let preferred=config2?.preferredDisplayMode;if(preferred!==void 0&&preferred!=="inline"&&preferred!=="fullscreen")throw new Error('viewConfig.preferredDisplayMode must be "inline" or "fullscreen"');if(preferred!==void 0&&!seen.has(preferred))throw new Error("viewConfig.preferredDisplayMode must belong to displayModes");return{...preferred!==void 0&&{preferredDisplayMode:preferred},autoResize,displayModes:normalizedModes}}init_dist();import{createServer as createNodeHttpServer}from"node:http";var GET_MATCH_RESULT=Symbol();var bufferToFormData=(arrayBuffer,contentType)=>new Response(arrayBuffer,{headers:{"Content-Type":contentType.replace(/^[^;]+/,mediaType=>mediaType.toLowerCase())}}).formData();var MAX_NESTED_OBJECTS=1e4,isRawRequest=request=>"headers"in request,parseBody=async(request,options=Object.create(null))=>{let{all=!1,dot=!1}=options,mediaType=(isRawRequest(request)?request.headers:request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return mediaType==="multipart/form-data"||mediaType==="application/x-www-form-urlencoded"?parseFormData(request,{all,dot}):{}};async function parseFormData(request,options){if(!isRawRequest(request)&&request.bodyCache.formData)return convertFormDataToBodyData(await request.bodyCache.formData,options);let headers=isRawRequest(request)?request.headers:request.raw.headers,arrayBuffer=await request.arrayBuffer(),formDataPromise=bufferToFormData(arrayBuffer,headers.get("Content-Type")||"");isRawRequest(request)||(request.bodyCache.formData=formDataPromise);let formData=await formDataPromise;return formData?convertFormDataToBodyData(formData,options):{}}function convertFormDataToBodyData(formData,options){let form=Object.create(null),nestingState={count:0};return formData.forEach((value,key)=>{options.all||key.endsWith("[]")?handleParsingAllValues(form,key,value):form[key]=value}),options.dot&&Object.entries(form).forEach(([key,value])=>{key.includes(".")&&(handleParsingNestedValues(form,key,value,nestingState),delete form[key])}),form}var handleParsingAllValues=(form,key,value)=>{form[key]!==void 0?Array.isArray(form[key])?form[key].push(value):form[key]=[form[key],value]:key.endsWith("[]")?form[key]=[value]:form[key]=value},handleParsingNestedValues=(form,key,value,state)=>{if(/(?:^|\.)__proto__\./.test(key))return;let nestedForm=form,keys2=key.split(".",34);keys2.length>33&&throwNestingLimitExceeded(),keys2.forEach((key2,index)=>{index===keys2.length-1?nestedForm[key2]=value:((!nestedForm[key2]||typeof nestedForm[key2]!="object"||Array.isArray(nestedForm[key2])||nestedForm[key2]instanceof File)&&(state.count++>=MAX_NESTED_OBJECTS&&throwNestingLimitExceeded(),nestedForm[key2]=Object.create(null)),nestedForm=nestedForm[key2])})},throwNestingLimitExceeded=()=>{throw new Error("Nesting limit exceeded")};var splitPath=path=>{let paths=path.split("/");return paths[0]===""&&paths.shift(),paths},splitRoutingPath=routePath=>{let{groups,path}=extractGroupsFromPath(routePath),paths=splitPath(path);return replaceGroupMarks(paths,groups)},extractGroupsFromPath=path=>{let groups=[];return path=path.replace(/\{[^}]+\}/g,(match2,index)=>{let mark=`@${index}`;return groups.push([mark,match2]),mark}),{groups,path}},replaceGroupMarks=(paths,groups)=>{for(let i=groups.length-1;i>=0;i--){let[mark]=groups[i];for(let j=paths.length-1;j>=0;j--)if(paths[j].includes(mark)){paths[j]=paths[j].replace(mark,groups[i][1]);break}}return paths},patternCache={},getPattern=(label,next)=>{if(label==="*")return"*";let match2=label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(match2){let cacheKey=`${label}#${next}`;return patternCache[cacheKey]||(match2[2]?patternCache[cacheKey]=next&&next[0]!==":"&&next[0]!=="*"?[cacheKey,match2[1],new RegExp(`^${match2[2]}(?=/${next})`)]:[label,match2[1],new RegExp(`^${match2[2]}$`)]:patternCache[cacheKey]=[label,match2[1],!0]),patternCache[cacheKey]}return null},tryDecode=(str,decoder)=>{try{return decoder(str)}catch{return str.replace(/(?:%[0-9A-Fa-f]{2})+/g,match2=>{try{return decoder(match2)}catch{return match2}})}},tryDecodeURI=str=>tryDecode(str,decodeURI),getPath=request=>{let url2=request.url,start=url2.indexOf("/",url2.indexOf(":")+4),i=start;for(;i<url2.length;i++){let charCode=url2.charCodeAt(i);if(charCode===37){let queryIndex=url2.indexOf("?",i),hashIndex=url2.indexOf("#",i),end=queryIndex===-1?hashIndex===-1?void 0:hashIndex:hashIndex===-1?queryIndex:Math.min(queryIndex,hashIndex),path=url2.slice(start,end);return tryDecodeURI(path.includes("%25")?path.replace(/%25/g,"%2525"):path)}else if(charCode===63||charCode===35)break}return url2.slice(start,i)};var getPathNoStrict=request=>{let result=getPath(request);return result.length>1&&result.at(-1)==="/"?result.slice(0,-1):result},mergePath=(base,sub,...rest)=>(rest.length&&(sub=mergePath(sub,...rest)),`${base?.[0]==="/"?"":"/"}${base}${sub==="/"?"":`${base?.at(-1)==="/"?"":"/"}${sub?.[0]==="/"?sub.slice(1):sub}`}`),checkOptionalParameter=path=>{if(path.charCodeAt(path.length-1)!==63||!path.includes(":"))return null;let segments=path.split("/"),results=[],basePath="";return segments.forEach(segment=>{if(segment!==""&&!/\:/.test(segment))basePath+="/"+segment;else if(/\:/.test(segment))if(segment.charCodeAt(segment.length-1)===63){results.length===0&&basePath===""?results.push("/"):results.push(basePath);let optionalSegment=segment.slice(0,-1);basePath+="/"+optionalSegment,results.push(basePath)}else basePath+="/"+segment}),results.filter((v,i,a)=>a.indexOf(v)===i)},tryDecodeURIComponent=str=>str.indexOf("%")!==-1?tryDecode(str,decodeURIComponent_):str,_decodeURI=value=>(value.indexOf("+")!==-1&&(value=value.replace(/\+/g," ")),tryDecodeURIComponent(value)),_getQueryParam=(url2,key,multiple)=>{let hashIndex=url2.indexOf("#",8);hashIndex!==-1&&(url2=url2.slice(0,hashIndex));let encoded;if(!multiple&&key&&key.indexOf("%")===-1&&key.indexOf("+")===-1){let keyIndex2=url2.indexOf("?",8);if(keyIndex2===-1)return;for(url2.startsWith(key,keyIndex2+1)||(keyIndex2=url2.indexOf(`&${key}`,keyIndex2+1));keyIndex2!==-1;){let trailingKeyCode=url2.charCodeAt(keyIndex2+key.length+1);if(trailingKeyCode===61){let valueIndex=keyIndex2+key.length+2,endIndex=url2.indexOf("&",valueIndex);return _decodeURI(url2.slice(valueIndex,endIndex===-1?void 0:endIndex))}else if(trailingKeyCode==38||isNaN(trailingKeyCode))return"";keyIndex2=url2.indexOf(`&${key}`,keyIndex2+1)}if(encoded=/[%+]/.test(url2),!encoded)return}let results=Object.create(null);encoded??=/[%+]/.test(url2);let keyIndex=url2.indexOf("?",8);for(;keyIndex!==-1;){let nextKeyIndex=url2.indexOf("&",keyIndex+1),valueIndex=url2.indexOf("=",keyIndex);valueIndex>nextKeyIndex&&nextKeyIndex!==-1&&(valueIndex=-1);let name=url2.slice(keyIndex+1,valueIndex===-1?nextKeyIndex===-1?void 0:nextKeyIndex:valueIndex);if(encoded&&(name=_decodeURI(name)),keyIndex=nextKeyIndex,name==="")continue;let value;valueIndex===-1?value="":(value=url2.slice(valueIndex+1,nextKeyIndex===-1?void 0:nextKeyIndex),encoded&&(value=_decodeURI(value))),multiple?(results[name]&&Array.isArray(results[name])||(results[name]=[]),results[name].push(value)):results[name]??=value}return key?results[key]:results},getQueryParam=_getQueryParam,getQueryParams=(url2,key)=>_getQueryParam(url2,key,!0),decodeURIComponent_=decodeURIComponent;var HonoRequest=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(request,path="/",matchResult=[[]]){this.raw=request,this.path=path,this.#matchResult=matchResult}param(key){return key?this.#getDecodedParam(key):this.#getAllDecodedParams()}#getDecodedParam(key){let paramKey=this.#matchResult[0][this.routeIndex]?.[1][key],param=this.#getParamValue(paramKey);return param&&tryDecodeURIComponent(param)}#getAllDecodedParams(){let decoded={},keys2=Object.keys(this.#matchResult[0][this.routeIndex]?.[1]??{});for(let key of keys2){let value=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);value!==void 0&&(decoded[key]=tryDecodeURIComponent(value))}return decoded}#getParamValue(paramKey){return this.#matchResult[1]?this.#matchResult[1][paramKey]:paramKey}query(key){return getQueryParam(this.url,key)}queries(key){return getQueryParams(this.url,key)}header(name){if(name)return this.raw.headers.get(name)??void 0;let headerData=Object.create(null);return this.raw.headers.forEach((value,key)=>{headerData[key]=value}),headerData}async parseBody(options){return parseBody(this,options)}#cachedBody=key=>{let{bodyCache,raw:raw2}=this,cachedBody=bodyCache[key];if(cachedBody)return cachedBody;for(let anyCachedKey in bodyCache)return bodyCache[anyCachedKey].then(body=>{anyCachedKey==="json"&&(body=JSON.stringify(body));let contentType=anyCachedKey==="formData"?void 0:raw2.headers.get("content-type");return new Response(body,{headers:contentType?{"Content-Type":contentType}:void 0})[key]()});return bodyCache[key]=raw2[key]()};json(){return this.#cachedBody("text").then(text2=>JSON.parse(text2))}text(){return this.#cachedBody("text")}arrayBuffer(){return this.#cachedBody("arrayBuffer")}bytes(){return this.#cachedBody("arrayBuffer").then(buffer=>new Uint8Array(buffer))}blob(){return this.#cachedBody("blob")}formData(){return this.#cachedBody("formData")}addValidatedData(target,data){(this.#validatedData??={})[target]=data}valid(target){return this.#validatedData?.[target]}get url(){return this.raw.url}get method(){return this.raw.method}get[GET_MATCH_RESULT](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,route]])=>route)}get routePath(){return this.#matchResult[0].map(([[,route]])=>route)[this.routeIndex].path}};var HtmlEscapedCallbackPhase={Stringify:1,BeforeStream:2,Stream:3},raw=(value,callbacks)=>{let escapedString=new String(value);return escapedString.isEscaped=!0,escapedString.callbacks=callbacks,escapedString};var resolveCallback=async(str,phase,preserveCallbacks,context,buffer)=>{typeof str=="object"&&!(str instanceof String)&&(str instanceof Promise||(str=str.toString()),str instanceof Promise&&(str=await str));let callbacks=str.callbacks;if(!callbacks?.length)return Promise.resolve(str);buffer?buffer[0]+=str:buffer=[str];let resStr=Promise.all(callbacks.map(c=>c({phase,buffer,context}))).then(res=>Promise.all(res.filter(Boolean).map(str2=>resolveCallback(str2,phase,!1,context,buffer))).then(()=>buffer[0]));return preserveCallbacks?raw(await resStr,callbacks):resStr};var TEXT_PLAIN="text/plain; charset=UTF-8",setDefaultContentType=(contentType,headers)=>({"Content-Type":contentType,...headers}),createResponseInstance=(body,init)=>new Response(body,init),Context=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(req,options){this.#rawRequest=req,options&&(this.#executionCtx=options.executionCtx,this.env=options.env,this.#notFoundHandler=options.notFoundHandler,this.#path=options.path,this.#matchResult=options.matchResult)}get req(){return this.#req??=new HonoRequest(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&"respondWith"in this.#executionCtx)return this.#executionCtx;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error("This context has no ExecutionContext")}get res(){return this.#res||=createResponseInstance(null,{headers:this.#preparedHeaders??=new Headers})}set res(_res){if(this.#res&&_res){_res=createResponseInstance(_res.body,_res);for(let[k,v]of this.#res.headers.entries())if(k!=="content-type")if(k==="set-cookie"){let cookies=this.#res.headers.getSetCookie();_res.headers.delete("set-cookie");for(let cookie of cookies)_res.headers.append("set-cookie",cookie)}else _res.headers.set(k,v)}this.#res=_res,this.finalized=!0}render=(...args)=>(this.#renderer??=content=>this.html(content),this.#renderer(...args));setLayout=layout=>this.#layout=layout;getLayout=()=>this.#layout;setRenderer=renderer=>{this.#renderer=renderer};header=(name,value,options)=>{this.finalized&&(this.#res=createResponseInstance(this.#res.body,this.#res));let headers=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;value===void 0?headers.delete(name):options?.append?headers.append(name,value):headers.set(name,value)};status=status=>{this.#status=status};set=(key,value)=>{this.#var??=new Map,this.#var.set(key,value)};get=key=>this.#var?this.#var.get(key):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(data,arg,headers){let responseHeaders=this.#res?new Headers(this.#res.headers):this.#preparedHeaders;if(typeof arg=="object"&&arg.headers){responseHeaders??=new Headers;for(let[key,value]of new Headers(arg.headers))key==="set-cookie"?responseHeaders.append(key,value):responseHeaders.set(key,value)}if(headers){if(!responseHeaders){let count=0;for(let k in headers)if(++count>1||typeof headers[k]!="string"){responseHeaders=new Headers;break}}if(responseHeaders)for(let k in headers){let v=headers[k];if(typeof v=="string")responseHeaders.set(k,v);else{responseHeaders.delete(k);for(let v2 of v)responseHeaders.append(k,v2)}}}let status=typeof arg=="number"?arg:arg?.status??this.#status;return createResponseInstance(data,{status,headers:responseHeaders??headers})}newResponse=(...args)=>this.#newResponse(...args);body=(data,arg,headers)=>this.#newResponse(data,arg,headers);text=(text2,arg,headers)=>!this.#preparedHeaders&&!this.#status&&!arg&&!headers&&!this.finalized?new Response(text2):this.#newResponse(text2,arg,setDefaultContentType(TEXT_PLAIN,headers));json=(object5,arg,headers)=>this.#newResponse(JSON.stringify(object5),arg,setDefaultContentType("application/json",headers));html=(html2,arg,headers)=>{let res=html3=>this.#newResponse(html3,arg,setDefaultContentType("text/html; charset=UTF-8",headers));return typeof html2=="object"?resolveCallback(html2,HtmlEscapedCallbackPhase.Stringify,!1,{}).then(res):res(html2)};redirect=(location,status)=>{let locationString=String(location);return this.header("Location",/[^\x00-\xFF]/.test(locationString)?encodeURI(locationString):locationString),this.newResponse(null,status??302)};notFound=()=>(this.#notFoundHandler??=()=>createResponseInstance(),this.#notFoundHandler(this))};var compose=(middleware,onError,onNotFound)=>(context,next)=>{let index=-1;return dispatch(0);async function dispatch(i){if(i<=index)throw new Error("next() called multiple times");index=i;let res,isError=!1,handler;if(middleware[i]?(handler=middleware[i][0][0],context.req.routeIndex=i):handler=i===middleware.length&&next||void 0,handler)try{res=await handler(context,()=>dispatch(i+1))}catch(err){if(err instanceof Error&&onError)context.error=err,res=await onError(err,context),isError=!0;else throw err}else context.finalized===!1&&onNotFound&&(res=await onNotFound(context));return res&&(context.finalized===!1||isError)&&(context.res=res),context}};var METHODS=["get","post","put","delete","options","patch","query"],MESSAGE_MATCHER_IS_ALREADY_BUILT="Can not add a route since the matcher is already built.",UnsupportedPathError=class extends Error{};var COMPOSED_HANDLER="__COMPOSED_HANDLER";var notFoundHandler=c=>c.text("404 Not Found",404),errorHandler=(err,c)=>{if("getResponse"in err){let res=err.getResponse();return c.newResponse(res.body,res)}return console.error(err),c.text("Internal Server Error",500)},Hono=class Hono2{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#path="/";routes=[];constructor(options={}){[...METHODS,"all"].forEach(method=>{this[method]=(args1,...args)=>{let methodName=method.toUpperCase();return typeof args1=="string"?this.#path=args1:this.#addRoute(methodName,this.#path,args1),args.forEach(handler=>{this.#addRoute(methodName,this.#path,handler)}),this}}),this.on=(method,path,...handlers)=>{for(let p of[path].flat()){this.#path=p;for(let m of[method].flat()){let methodName=m.toUpperCase();for(let handler of handlers)this.#addRoute(methodName,this.#path,handler)}}return this},this.use=(arg1,...handlers)=>(typeof arg1=="string"?this.#path=arg1:(this.#path="*",handlers.unshift(arg1)),handlers.forEach(handler=>{this.#addRoute("ALL",this.#path,handler)}),this);let{strict,...optionsWithoutStrict}=options;Object.assign(this,optionsWithoutStrict),this.getPath=strict??!0?options.getPath??getPath:getPathNoStrict}#clone(){let clone2=new Hono2({router:this.router,getPath:this.getPath});return clone2.errorHandler=this.errorHandler,clone2.#notFoundHandler=this.#notFoundHandler,clone2.routes=this.routes,clone2}#notFoundHandler=notFoundHandler;errorHandler=errorHandler;route(path,app){let subApp=this.basePath(path);return app.routes.map(r=>{let handler;app.errorHandler===errorHandler?handler=r.handler:(handler=async(c,next)=>(await compose([],app.errorHandler)(c,()=>r.handler(c,next))).res,handler[COMPOSED_HANDLER]=r.handler),subApp.#addRoute(r.method,r.path,handler,r.basePath)}),this}basePath(path){let subApp=this.#clone();return subApp._basePath=mergePath(this._basePath,path),subApp}onError=handler=>(this.errorHandler=handler,this);notFound=handler=>(this.#notFoundHandler=handler,this);mount(path,applicationHandler,options){let replaceRequest,optionHandler;options&&(typeof options=="function"?optionHandler=options:(optionHandler=options.optionHandler,options.replaceRequest===!1?replaceRequest=request=>request:replaceRequest=options.replaceRequest));let getOptions=optionHandler?c=>{let options2=optionHandler(c);return Array.isArray(options2)?options2:[options2]}:c=>{let executionContext;try{executionContext=c.executionCtx}catch{}return[c.env,executionContext]};replaceRequest||=(()=>{let mergedPath=mergePath(this._basePath,path),pathPrefixLength=mergedPath==="/"?0:mergedPath.length;return request=>{let url2=new URL(request.url);return url2.pathname=this.getPath(request).slice(pathPrefixLength)||"/",new Request(url2,request)}})();let handler=async(c,next)=>{let res=await applicationHandler(replaceRequest(c.req.raw),...getOptions(c));if(res)return res;await next()};return this.#addRoute("ALL",mergePath(path,"*"),handler),this}#addRoute(method,path,handler,baseRoutePath){path=mergePath(this._basePath,path);let r={basePath:baseRoutePath!==void 0?mergePath(this._basePath,baseRoutePath):this._basePath,path,method,handler};this.router.add(method,path,[handler,r]),this.routes.push(r)}#handleError(err,c){if(err instanceof Error)return this.errorHandler(err,c);throw err}#dispatch(request,executionCtx,env2,method){if(method==="HEAD")return(async()=>new Response(null,await this.#dispatch(request,executionCtx,env2,"GET")))();let path=this.getPath(request,{env:env2}),matchResult=this.router.match(method,path),c=new Context(request,{path,matchResult,env:env2,executionCtx,notFoundHandler:this.#notFoundHandler});if(matchResult[0].length===1){let res;try{res=matchResult[0][0][0][0](c,async()=>{c.res=await this.#notFoundHandler(c)})}catch(err){return this.#handleError(err,c)}return res instanceof Promise?res.then(resolved=>resolved||(c.finalized?c.res:this.#notFoundHandler(c))).catch(err=>this.#handleError(err,c)):res??this.#notFoundHandler(c)}let composed=compose(matchResult[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let context=await composed(c);if(!context.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return context.res}catch(err){return this.#handleError(err,c)}})()}fetch=(request,...rest)=>this.#dispatch(request,rest[1],rest[0],request.method);request=(input,requestInit,Env,executionCtx)=>input instanceof Request?this.fetch(requestInit?new Request(input,requestInit):input,Env,executionCtx):(input=input.toString(),this.fetch(new Request(/^https?:\/\//.test(input)?input:`http://localhost${mergePath("/",input)}`,requestInit),Env,executionCtx));fire=()=>{addEventListener("fetch",event=>{event.respondWith(this.#dispatch(event.request,event,void 0,event.request.method))})}};var createNullObject=()=>Object.create(null);var emptyParam=[];function match(method,path){let matchers=this.buildAllMatchers(),match2=((method2,path2)=>{let matcher=matchers[method2]||matchers.ALL,staticMatch=matcher[2][path2];if(staticMatch)return staticMatch;let match3=path2.match(matcher[0]);if(!match3)return[[],emptyParam];let index=match3.indexOf("",1);return[matcher[1][index],match3]});return this.match=match2,match2(method,path)}var LABEL_REG_EXP_STR="[^/]+";var TAIL_WILDCARD_REG_EXP_STR="(?:|/.*)",PATH_ERROR=Symbol(),regExpMetaChars=new Set(".\\+*[^]$()");function compareKey(a,b){return a.length===1?b.length===1?a<b?-1:1:-1:b.length===1?1:a===".*"||a==="(?:|/.*)"?b==="(?:|/.*)"?-1:1:b===".*"||b==="(?:|/.*)"?-1:a==="[^/]+"?1:b==="[^/]+"?-1:a.length===b.length?a<b?-1:1:b.length-a.length}var Node=class Node2{#index;#varIndex;#children=createNullObject();insert(tokens,index,paramMap,context,isStatic){let node2=this;for(let i=0,len=tokens.length;i<len;i++){let token=tokens[i],pattern=token.length===1?token==="*"?i===len-1?["","",".*"]:["","",LABEL_REG_EXP_STR]:null:token==="/*"?["","",TAIL_WILDCARD_REG_EXP_STR]:token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),nextNode;if(pattern){let name=pattern[1],regexpStr=pattern[2]||"[^/]+";if(name&&pattern[2]&&(regexpStr===".*"||(regexpStr=regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(regexpStr))||regexpStr.length===1&&regExpMetaChars.has(regexpStr)))throw PATH_ERROR;if(nextNode=node2.#children[regexpStr],!nextNode){if(regexpStr!==".*"&&regexpStr!=="(?:|/.*)"){for(let k in node2.#children)if((regexpStr.length>1||k.length>1)&&k!==".*"&&k!=="(?:|/.*)")throw PATH_ERROR}nextNode=node2.#children[regexpStr]=new Node2}name!==""&&(nextNode.#varIndex??=context.varIndex++,paramMap.push([name,nextNode.#varIndex]))}else if(nextNode=node2.#children[token],!nextNode){for(let k in node2.#children)if(k.length>1&&k!==".*"&&k!=="(?:|/.*)")throw PATH_ERROR;nextNode=node2.#children[token]=new Node2}node2=nextNode}if(node2.#index!==void 0)throw PATH_ERROR;node2.#index=isStatic?-1:index}buildRegExpStr(){let strList=Object.keys(this.#children).sort(compareKey).map(k=>{let c=this.#children[k],childStr=c.buildRegExpStr();return childStr===""?"":(typeof c.#varIndex=="number"?`(${k})@${c.#varIndex}`:regExpMetaChars.has(k)?`\\${k}`:k)+childStr}).filter(Boolean);return typeof this.#index=="number"&&this.#index!==-1&&strList.unshift(`#${this.#index}`),strList.length===0?"":strList.length===1?strList[0]:"(?:"+strList.join("|")+")"}};var Trie=class{#context={varIndex:0};#root=new Node;#index=0;paths=createNullObject();insert(path,isStatic){if(isStatic){this.#root.insert(path.split(""),0,[],this.#context,!0);return}let paramAssoc=[],groups=[],markedPath=path;for(let i=0;;){let replaced=!1;if(markedPath=markedPath.replace(/\{[^}]+\}/g,m=>{let mark=`@\\${i}`;return groups[i]=[mark,m],i++,replaced=!0,mark}),!replaced)break}let tokens=markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=groups.length-1;i>=0;i--){let[mark]=groups[i];for(let j=tokens.length-1;j>=0;j--)if(tokens[j].indexOf(mark)!==-1){tokens[j]=tokens[j].replace(mark,groups[i][1]);break}}this.#root.insert(tokens,this.#index,paramAssoc,this.#context,!1),this.paths[path]=[this.#index++,paramAssoc]}buildRegExp(){let regexp=this.#root.buildRegExpStr();if(regexp==="")return[/^$/,[],[]];let captureIndex=0,indexReplacementMap=[],paramReplacementMap=[];return regexp=regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g,(_,handlerIndex,paramIndex)=>handlerIndex!==void 0?(indexReplacementMap[++captureIndex]=Number(handlerIndex),"$()"):(paramIndex!==void 0&&(paramReplacementMap[Number(paramIndex)]=++captureIndex),"")),[new RegExp(`^${regexp}`),indexReplacementMap,paramReplacementMap]}};var wildcardRegExpCache=createNullObject();function buildWildcardRegExp(path){return wildcardRegExpCache[path]??=new RegExp(`^${path.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(match2,metaChar)=>metaChar?`\\${metaChar}`:match2==="/*"?TAIL_WILDCARD_REG_EXP_STR:match2==="*"?".*":`/:${LABEL_REG_EXP_STR}`)}$`)}function findMiddleware(middleware,path){for(let k of Object.keys(middleware).sort((a,b)=>b.length-a.length))if(buildWildcardRegExp(k).test(path))return[...middleware[k]]}var RegExpRouter=class{name="RegExpRouter";#middleware;#routes;#tries;constructor(){this.#middleware={ALL:createNullObject()},this.#routes={ALL:createNullObject()},this.#tries={ALL:new Trie}}#insertPath(method,path){try{this.#tries[method].insert(path,!/\*|\/:/.test(path))}catch(e){throw e===PATH_ERROR?new UnsupportedPathError(path):e}}add(method,path,handler){let middleware=this.#middleware,routes=this.#routes;if(!middleware)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);if(!middleware[method]){this.#tries[method]=new Trie;for(let handlerMap of[middleware,routes]){handlerMap[method]=createNullObject();for(let p in handlerMap.ALL)handlerMap[method][p]=[...handlerMap.ALL[p]],this.#insertPath(method,p)}}path==="/*"&&(path="*");let methods=method==="ALL"?Object.keys(middleware):[method];if(/\*$/.test(path)){let re=buildWildcardRegExp(path);for(let m of methods)middleware[m][path]||(this.#insertPath(m,path),middleware[m][path]=findMiddleware(middleware[m],path)||findMiddleware(middleware.ALL,path)||[]);for(let handlerMap of[middleware,routes])for(let m of methods)for(let p in handlerMap[m])re.test(p)&&handlerMap[m][p].push([handler,path]);return}let paths=checkOptionalParameter(path)||[path];for(let path2 of paths)for(let m of methods)routes[m][path2]||(this.#insertPath(m,path2),routes[m][path2]=findMiddleware(middleware[m],path2)||findMiddleware(middleware.ALL,path2)||[]),routes[m][path2].push([handler,path2])}match=match;buildAllMatchers(){let matchers=createNullObject();for(let method of Object.keys(this.#routes))matchers[method]=this.#buildMatcher(method);return this.#middleware=this.#routes=this.#tries=void 0,wildcardRegExpCache=createNullObject(),matchers}#buildMatcher(method){let middleware=this.#middleware[method],routes=this.#routes[method],trie=this.#tries[method],staticMap=createNullObject(),handlerData=[],[regexp,indexReplacementMap,paramReplacementMap]=trie.buildRegExp();for(let r of[middleware,routes])for(let path in r){let handlers=r[path],pathData=trie.paths[path];if(!pathData){staticMap[path]=[handlers.map(([h])=>[h,createNullObject()]),emptyParam];continue}handlerData[pathData[0]]=handlers.map(([h,handlerPath])=>[h,trie.paths[handlerPath][1].reduceRight((map,[key],i)=>(map[key]=paramReplacementMap[pathData[1][i][1]],map),createNullObject())])}return[regexp,indexReplacementMap.map(i=>handlerData[i]),staticMap]}};var SmartRouter=class{name="SmartRouter";#routers=[];#routes=[];constructor(init){this.#routers=init.routers}add(method,path,handler){if(!this.#routes)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);this.#routes.push([method,path,handler])}match(method,path){if(!this.#routes)throw new Error("Fatal error");let routers=this.#routers,routes=this.#routes,len=routers.length,i=0,res;for(;i<len;i++){let router=routers[i];try{for(let i2=0,len2=routes.length;i2<len2;i2++)router.add(...routes[i2]);res=router.match(method,path)}catch(e){if(e instanceof UnsupportedPathError)continue;throw e}this.match=router.match.bind(router),this.#routers=[router],this.#routes=void 0;break}if(i===len)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,res}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw new Error("No active router has been determined yet.");return this.#routers[0]}};var emptyParams=createNullObject(),order=0,Node3=class Node4{#methods=[];#children=createNullObject();#patterns=[];#pattern;#params=emptyParams;insert(method,path,handler){let curNode=this,parts=splitRoutingPath(path),possibleKeys=new Set,i=0;for(let p of parts){let nextP=parts[++i],pattern=getPattern(p,nextP)||(nextP===void 0&&p&&p.indexOf("*")===p.length-1?p:null),isParam=Array.isArray(pattern),key=isParam?pattern[0]:pattern||p,child=curNode.#children[key]||=new Node4;pattern&&!child.#pattern&&(child.#pattern=pattern,curNode.#patterns.push(child)),curNode=child,isParam&&possibleKeys.add(pattern[1])}curNode.#methods.push({[method]:{handler,possibleKeys:[...possibleKeys],score:++order}})}#pushHandlerSets(handlerSets,node2,method,nodeParams,params){for(let i=0,len=node2.#methods.length;i<len;i++){let m=node2.#methods[i],handlerSet=m[method]||m.ALL;if(handlerSet){handlerSet.params=createNullObject(),handlerSets.push(handlerSet);for(let i2=0,len2=handlerSet.possibleKeys.length;i2<len2;i2++){let key=handlerSet.possibleKeys[i2];handlerSet.params[key]=params?.[key]&&!i2?params[key]:nodeParams[key]??params?.[key]}}}}search(method,path){let handlerSets=[];this.#params=emptyParams;let curNodes=[this],parts=splitPath(path),curNodesQueue=[],len=parts.length,partOffsets=null;for(let i=0;i<len;i++){let part=parts[i],isLast=i===len-1,tempNodes=[];for(let j=0,len2=curNodes.length;j<len2;j++){let node2=curNodes[j],nextNode=node2.#children[part];nextNode&&(nextNode.#params=node2.#params,isLast?(nextNode.#children["*"]&&this.#pushHandlerSets(handlerSets,nextNode.#children["*"],method,node2.#params),this.#pushHandlerSets(handlerSets,nextNode,method,node2.#params)):tempNodes.push(nextNode));for(let child of node2.#patterns){let pattern=child.#pattern,params=node2.#params===emptyParams?{}:{...node2.#params};if(typeof pattern=="string"){(pattern==="*"||part.startsWith(pattern.slice(0,-1)))&&(this.#pushHandlerSets(handlerSets,child,method,node2.#params),pattern==="*"&&(child.#params=params,tempNodes.push(child)));continue}let[,name,matcher]=pattern;if(!(!part&&matcher===!0)){if(matcher!==!0){if(!partOffsets){partOffsets=[];let offset=path[0]==="/"?1:0;for(let p=0;p<len;p++)partOffsets[p]=offset,offset+=parts[p].length+1}let restPathString=path.slice(partOffsets[i]),m=matcher.exec(restPathString);if(m){params[name]=m[0],this.#pushHandlerSets(handlerSets,child,method,node2.#params,params),m[0].length===restPathString.length&&child.#children["*"]&&this.#pushHandlerSets(handlerSets,child.#children["*"],method,node2.#params,params);for(let _ in child.#children){child.#params=params;let componentCount=m[0].match(/\//g)?.length??0;(curNodesQueue[componentCount]||=[]).push(child);break}continue}}(matcher===!0||matcher.test(part))&&(params[name]=part,isLast?(this.#pushHandlerSets(handlerSets,child,method,params,node2.#params),child.#children["*"]&&this.#pushHandlerSets(handlerSets,child.#children["*"],method,params,node2.#params)):(child.#params=params,tempNodes.push(child)))}}}let shifted=curNodesQueue.shift();curNodes=shifted?tempNodes.concat(shifted):tempNodes}return handlerSets[1]&&handlerSets.sort((a,b)=>a.score-b.score),[handlerSets.map(({handler,params})=>[handler,params])]}};var TrieRouter=class{name="TrieRouter";#node=new Node3;add(method,path,handler){for(let result of checkOptionalParameter(path)||[path])this.#node.insert(method,result,handler)}match(method,path){return this.#node.search(method,path)}};var Hono3=class extends Hono{constructor(options={}){super(options),this.router=options.router??new SmartRouter({routers:[new RegExpRouter,new TrieRouter]})}};init_origin();init_public_route();var FAVICON_CACHE_CONTROL="public, max-age=31536000, immutable",FAVICON_REDIRECT_CACHE_CONTROL="public, max-age=300";function protocolOf(value){return/^([a-z][a-z\d+.-]*):/i.exec(value)?.[1]?.toLowerCase()}function publicAssetPath(basePath,source){return`${basePath==="/"?"":basePath}/_mcp-use/public/${source.split("/").map(segment=>encodeURIComponent(segment)).join("/")}`}function isLocalPublicSource(source){return protocolOf(source)===void 0}function selectFaviconFromIcons(icons){return icons[0]}function assertLocalPublicSource(source,field){if(source.startsWith("/")||source.includes("\\")||source.includes("?")||source.includes("#")||source.split("/").some(segment=>segment===""||segment===".."))throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`)}function parseDataImage(source,field){let comma=source.indexOf(",");if(comma<0)throw new TypeError(`${field} must be a valid image data URL`);let metadata=source.slice(5,comma),payload=source.slice(comma+1),parts=metadata.split(";"),mimeType=parts[0]?.toLowerCase()??"";if(!mimeType.startsWith("image/"))throw new TypeError(`${field} data URL must use an image MIME type`);try{if(parts.includes("base64")){let binary2=atob(payload);return{mimeType,bytes:Uint8Array.from(binary2,character=>character.charCodeAt(0))}}return{mimeType,bytes:new TextEncoder().encode(decodeURIComponent(payload))}}catch{throw new TypeError(`${field} must be a valid image data URL`)}}function assertBrandingSource(source,field){if(typeof source!="string"||source.length===0)throw new TypeError(`${field} must be a non-empty string`);let protocol=protocolOf(source);if(protocol===void 0)return assertLocalPublicSource(source,field),source;if(protocol==="data")return parseDataImage(source,field),source;if(protocol!=="http"&&protocol!=="https")throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(source)}catch{throw new TypeError(`${field} must be a valid absolute http(s) URL`)}return source}function normalizeServerBranding(config2){let websiteUrl;if(config2.websiteUrl!==void 0){if(typeof config2.websiteUrl!="string"||config2.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let parsed;try{parsed=new URL(config2.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");websiteUrl=config2.websiteUrl}let icons;if(config2.icons!==void 0){if(!Array.isArray(config2.icons))throw new TypeError("icons must be an array of MCP Icon objects");icons=Object.freeze(config2.icons.map((value,index)=>{if(typeof value!="object"||value===null)throw new TypeError(`icons[${index}] must be an MCP Icon object`);let icon=value,src=assertBrandingSource(icon.src,`icons[${index}].src`),mimeType=icon.mimeType;if(mimeType!==void 0&&(typeof mimeType!="string"||!mimeType.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${index}].mimeType must be an image MIME type when provided`);let sizes=icon.sizes;if(sizes!==void 0&&(!Array.isArray(sizes)||sizes.some(size=>typeof size!="string"||size.length===0)))throw new TypeError(`icons[${index}].sizes must be an array of non-empty strings when provided`);let normalizedSizes=sizes===void 0?void 0:sizes.map(size=>size),theme=icon.theme;if(theme!==void 0&&theme!=="light"&&theme!=="dark")throw new TypeError(`icons[${index}].theme must be "light" or "dark" when provided`);return Object.freeze({src,...mimeType!==void 0&&{mimeType},...normalizedSizes!==void 0&&{sizes:Object.freeze(normalizedSizes)},...theme!==void 0&&{theme}})}))}let explicitFavicon=config2.favicon===void 0?void 0:assertBrandingSource(config2.favicon,"favicon"),inferred=explicitFavicon===void 0?selectFaviconFromIcons(icons??[]):void 0,favicon=explicitFavicon??inferred?.src,faviconMimeType=inferred?.mimeType??icons?.find(icon=>icon.src===explicitFavicon)?.mimeType;return Object.freeze({...favicon!==void 0&&{favicon},...faviconMimeType!==void 0&&{faviconMimeType},...icons!==void 0&&{icons},...websiteUrl!==void 0&&{websiteUrl}})}function resolveImplementationIcons(icons,request,basePath){return icons.map(icon=>({...icon,src:request!==void 0&&isLocalPublicSource(icon.src)?`${resolveAssetsBase(request)}${publicAssetPath(basePath,icon.src)}`:icon.src,...icon.sizes!==void 0&&{sizes:[...icon.sizes]}}))}function hasLocalBrandingAsset(branding){return branding.favicon!==void 0&&isLocalPublicSource(branding.favicon)||branding.icons?.some(icon=>isLocalPublicSource(icon.src))===!0}function createFaviconHandler(branding,options){let source=branding.favicon;if(source!==void 0)return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(request.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let protocol=protocolOf(source);if(protocol==="http"||protocol==="https")return new Response(null,{status:307,headers:{Location:source,"Cache-Control":FAVICON_REDIRECT_CACHE_CONTROL}});if(protocol==="data"){let data=parseDataImage(source,"favicon");return new Response(request.method==="HEAD"?null:data.bytes.buffer,{status:200,headers:{"Content-Type":branding.faviconMimeType??data.mimeType,"Cache-Control":FAVICON_CACHE_CONTROL,"X-Content-Type-Options":"nosniff"}})}let{join}=await import("path"),publicRoot=options.dev?join(options.projectRoot,"public"):join(options.projectRoot,".mcp-use/build/views/public"),diskPath=await resolvePublicFilePath(publicRoot,source);if(diskPath===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let response=await servePublicFile(diskPath,{...options.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}});return response.headers.set("Cache-Control",FAVICON_CACHE_CONTROL),response.headers.set("X-Content-Type-Options","nosniff"),branding.faviconMimeType!==void 0&&response.headers.set("Content-Type",branding.faviconMimeType),response}}function isOAuthProviderLike(value){if(typeof value!="object"||value===null)return!1;let provider=value;return typeof provider.createTokenVerifier=="function"&&typeof provider.mapAuthInfo=="function"&&(typeof provider.oauthMetadata=="object"&&provider.oauthMetadata!==null||typeof provider.oauthMetadata=="function")}function assertServerConfig(config2){if(config2.mixedAuth!==void 0&&typeof config2.mixedAuth!="boolean")throw new TypeError("mixedAuth must be a boolean");if(config2.mixedAuth===!0&&!isOAuthProviderLike(config2.oauth))throw new TypeError("mixedAuth requires an OAuth provider; set oauth on the server");if(config2.basePath!==void 0){if(typeof config2.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath}=config2;if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#")||/\s/.test(basePath)||basePath.includes("//")||basePath.length>1&&basePath.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(config2.port!==void 0&&(typeof config2.port!="number"||!Number.isInteger(config2.port)||config2.port<0||config2.port>65535))throw new TypeError("port must be an integer between 0 and 65535");if(config2.skills!==void 0&&typeof config2.skills!="boolean"){if(typeof config2.skills!="object"||config2.skills===null||Array.isArray(config2.skills))throw new TypeError("skills must be a boolean or configuration object");let directory=config2.skills.directory;if(directory!==void 0&&typeof directory!="string")throw new TypeError("skills.directory must be a string when provided")}}var DEFAULT_LISTEN_HOST="127.0.0.1";function resolveListenHost(explicitHost,configuredHost,env2=process.env){if(explicitHost!==void 0)return explicitHost;let envHost=env2.HOST?.trim();return envHost!==void 0&&envHost!==""?envHost:configuredHost??DEFAULT_LISTEN_HOST}function resolveListenPort(explicitPort,configuredPort,env2=process.env){if(explicitPort!==void 0)return explicitPort;let envPort=parsePort(env2.PORT);return envPort!==void 0?envPort:configuredPort??3e3}function parsePort(value){if(value===void 0||value.trim()==="")return;let port=Number(value);return Number.isInteger(port)&&port>=0&&port<=65535?port:void 0}import{isBufferedResponse}from"#mcp-use-buffered-response";function toNodeHandler(handler,opts){return async(req,res,parsedBody)=>{typeof parsedBody=="function"&&(parsedBody=void 0);let finished=!1,abort=new AbortController;res.on("close",()=>{finished||abort.abort()}),res.destroyed===!0&&abort.abort();let request,response;try{request=await toWebRequest(req,parsedBody,{signal:abort.signal}),response=await handler.fetch(request,{...req.auth!==void 0&&{authInfo:req.auth},...parsedBody!==void 0&&{parsedBody}})}catch(error3){try{opts?.onerror?.(error3 instanceof Error?error3:new Error(String(error3)))}catch{}response=internalServerErrorResponse2(echoableRequestId2(parsedBody))}let headers={},setCookies=response.headers.getSetCookie?.();for(let[name,value]of response.headers){if(name==="set-cookie"&&setCookies?.length){headers[name]=setCookies;continue}headers[name]=value}if(res.writeHead(response.status,headers),response.body===null){finished=!0,res.end();return}if(isBufferedResponse(response,request)){try{let bytes=new Uint8Array(await response.arrayBuffer());finished=!0,res.end(bytes)}catch{finished=!0,res.end()}return}let drainResolve,releaseDrainWait=()=>{drainResolve?.(),drainResolve=void 0},waitForDrain=()=>new Promise(resolve=>{drainResolve=resolve});res.on("drain",releaseDrainWait);let closed=new Promise(resolve=>{abort.signal.addEventListener("abort",()=>resolve(),{once:!0})});try{for await(let chunk of response.body){if(abort.signal.aborted)break;let bytes=chunk instanceof Uint8Array?chunk:new Uint8Array(chunk);res.write(bytes)===!1&&await Promise.race([waitForDrain(),closed])}}catch{}finished=!0,res.end()}}async function toWebRequest(req,parsedBody,options){let method=(req.method??"GET").toUpperCase(),url2=`http://${singleHeaderValue(req.headers.host)??singleHeaderValue(req.headers[":authority"])??"localhost"}${req.url??"/"}`,headers=new Headers;for(let[name,value]of Object.entries(req.headers))if(!(value===void 0||name.startsWith(":")))if(Array.isArray(value))for(let item of value)headers.append(name,item);else headers.set(name,value);let body;if(method!=="GET"&&method!=="HEAD")if(parsedBody===void 0){let decoder=new TextDecoder,collected="";for await(let chunk of req)collected+=typeof chunk=="string"?chunk:decoder.decode(chunk,{stream:!0});collected+=decoder.decode(),collected.length>0&&(body=collected)}else{let serialized=JSON.stringify(parsedBody);headers.delete("content-encoding"),headers.delete("transfer-encoding"),serialized===void 0?headers.delete("content-length"):(body=serialized,headers.set("content-length",String(new TextEncoder().encode(serialized).byteLength)))}return new Request(url2,{method,headers,...options?.signal!==void 0&&{signal:options.signal},...body!==void 0&&{body}})}function singleHeaderValue(value){return Array.isArray(value)?value[0]:value}function echoableRequestId2(body){if(body===null||typeof body!="object"||Array.isArray(body))return null;let{method,id}=body;return typeof method!="string"?null:typeof id=="string"||typeof id=="number"?id:null}function internalServerErrorResponse2(id){return Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id},{status:500})}init_dist();init_fetch_app();init_dist();var UI_EXTENSION_ID="io.modelcontextprotocol/ui",UI_MIME_TYPE="text/html;profile=mcp-app",UI_RESOURCE_URI_PREFIX="ui://views/";var UI_RESOURCE_URI_META_KEY="ui/resourceUri";function viewResourceUri(viewName){return`${UI_RESOURCE_URI_PREFIX}${viewName}.html`}var clientCapabilitiesByRequest=new WeakMap;function stashClientCapabilities(request,capabilities){clientCapabilitiesByRequest.set(request,capabilities)}function extractClientCapabilitiesFromBody(body){if(typeof body!="object"||body===null)return;let params=body.params;if(typeof params!="object"||params===null)return;let meta2=params._meta;if(typeof meta2!="object"||meta2===null)return;let capabilities=meta2[CLIENT_CAPABILITIES_META_KEY];if(!(typeof capabilities!="object"||capabilities===null))return capabilities}function supportsViews(capabilities){let extensions=capabilities?.extensions;if(extensions===void 0)return!1;let uiExtension=extensions[UI_EXTENSION_ID];if(typeof uiExtension!="object"||uiExtension===null)return!1;let mimeTypes=uiExtension.mimeTypes;return Array.isArray(mimeTypes)?mimeTypes.includes(UI_MIME_TYPE):!1}function requireOAuthAuthInfo(authInfo){if(authInfo===void 0||authInfo.extra===void 0||authInfo.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function stringValue(value){return typeof value=="string"?value:void 0}function coordinateValue(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)?value:void 0}function normalizeUserContext(meta2){if(meta2===void 0)return;let locale=stringValue(meta2["openai/locale"])??stringValue(meta2["webplus/i18n"]),userAgent=stringValue(meta2["openai/userAgent"]),subject=stringValue(meta2["openai/subject"]),conversationId=stringValue(meta2["openai/session"]),organizationId=stringValue(meta2["openai/organization"]),rawLocation=meta2["openai/userLocation"],location;if(typeof rawLocation=="object"&&rawLocation!==null&&!Array.isArray(rawLocation)){let values=rawLocation,normalized={city:stringValue(values.city),region:stringValue(values.region),country:stringValue(values.country),timezone:stringValue(values.timezone),latitude:coordinateValue(values.latitude),longitude:coordinateValue(values.longitude)},entries=Object.entries(normalized).filter(entry=>entry[1]!==void 0);entries.length>0&&(location=Object.fromEntries(entries))}if(!(locale===void 0&&userAgent===void 0&&location===void 0&&subject===void 0&&conversationId===void 0&&organizationId===void 0))return{...locale!==void 0&&{locale},...userAgent!==void 0&&{userAgent},...location!==void 0&&{location},...subject!==void 0&&{subject},...conversationId!==void 0&&{conversationId},...organizationId!==void 0&&{organizationId}}}function requestEnvelope(ctx){return ctx.mcpReq.envelope}function requestClientInfo(ctx){return{...requestEnvelope(ctx)?.[CLIENT_INFO_META_KEY]??{}}}function toClientContext(ctx){let capabilities={...requestEnvelope(ctx)?.[CLIENT_CAPABILITIES_META_KEY]??{}},info=requestClientInfo(ctx),user=normalizeUserContext(ctx.mcpReq._meta);return{can(capability){return Object.hasOwn(capabilities,capability)},capabilities(){return{...capabilities}},extension(id){let settings=capabilities.extensions?.[id];return settings===void 0?void 0:{...settings}},info(){return{...info}},user(){return user===void 0?void 0:{...user,...user.location!==void 0&&{location:{...user.location}}}},supportsViews(){return supportsViews(capabilities)}}}function toRequestContext(ctx){let rawRequest=ctx.http?.req,http=rawRequest===void 0?void 0:getRequestBag(rawRequest).honoContext,request=http?.req??(rawRequest===void 0?void 0:new HonoRequest(rawRequest)),additions={signal:ctx.mcpReq.signal,...request!==void 0&&{request},...ctx.mcpReq.inputResponses!==void 0&&{inputResponses:ctx.mcpReq.inputResponses},client:toClientContext(ctx),requestState:()=>ctx.mcpReq.requestState(),async sendNotification(method,params){await ctx.mcpReq.notify({method,...params!==void 0&&{params}})},async reportProgress(progress,total,message){let progressToken=ctx.mcpReq._meta?.progressToken;return progressToken===void 0?!1:(await ctx.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}}}),!0)},async sendLog(level,data,logger){await ctx.mcpReq.notify({method:"notifications/message",params:{level,data,...logger!==void 0&&{logger}}})}};return http!==void 0?Object.assign(http,additions):{...additions,...request!==void 0&&{req:request}}}function isOAuthUpstreamToken(value){if(value===null||typeof value!="object")return!1;let token=value;return typeof token.accessToken=="string"&&Array.isArray(token.scopes)&&token.scopes.every(scope=>typeof scope=="string")&&(token.expiresAt===void 0||typeof token.expiresAt=="number")}function toAuthenticatedRequestContext(ctx){let authInfo=ctx.http?.authInfo;return requireOAuthAuthInfo(authInfo),Object.assign(toRequestContext(ctx),{auth:{user:authInfo.extra.user,payload:authInfo.extra.payload,accessToken:authInfo.token,scopes:[...authInfo.scopes],permissions:[...authInfo.extra.permissions],...authInfo.clientId.length>0&&{clientId:authInfo.clientId},expiresAt:authInfo.expiresAt,...authInfo.resource!==void 0&&{resource:authInfo.resource},...isOAuthUpstreamToken(authInfo.extra.upstream)&&{upstream:{accessToken:authInfo.extra.upstream.accessToken,scopes:[...authInfo.extra.upstream.scopes],...authInfo.extra.upstream.expiresAt!==void 0&&{expiresAt:authInfo.extra.upstream.expiresAt}}}}})}init_dist();function isReadResourceResult(result){return"contents"in result&&Array.isArray(result.contents)}function isGetPromptResult(result){return"messages"in result&&Array.isArray(result.messages)}function toResourceResult(result,uri){if(isReadResourceResult(result))return result;let mime=result._meta&&typeof result._meta=="object"&&typeof result._meta.mimeType=="string"?result._meta.mimeType:void 0,contents=[];for(let block of result.content??[]){let mapped=contentBlockToResourceContents(block,uri,mime);mapped!==void 0&&contents.push(mapped)}return contents.length===0&&result.structuredContent!==void 0&&contents.push({uri,mimeType:"application/json",text:JSON.stringify(result.structuredContent)}),contents.length===0&&contents.push({uri,mimeType:"text/plain",text:""}),{contents}}function contentBlockToResourceContents(block,uri,mimeHint){if(block.type==="text")return{uri,mimeType:mimeHint??"text/plain",text:block.text};if(block.type==="image"||block.type==="audio")return{uri,mimeType:block.mimeType,blob:block.data};if(block.type==="resource")return{...block.resource}}function toPromptResult(result){if(isInputRequiredResult(result)||isGetPromptResult(result))return result;let messages=(result.content??[]).map(content=>({role:"user",content}));return messages.length===0&&result.structuredContent!==void 0&&messages.push({role:"user",content:{type:"text",text:JSON.stringify(result.structuredContent)}}),messages.length===0&&messages.push({role:"user",content:{type:"text",text:""}}),{messages}}init_fetch_app();import{inheritBufferedResponse}from"#mcp-use-buffered-response";var DEFAULT_METHODS=["GET","HEAD","POST","OPTIONS"],DEFAULT_ALLOWED_HEADERS=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function resolveAllowedOrigin(origin,requestOrigin){return origin===void 0?requestOrigin:typeof origin=="function"?origin(requestOrigin):origin==="*"?"*":Array.isArray(origin)?requestOrigin!==null&&origin.includes(requestOrigin)?requestOrigin:null:origin}function corsHeaders(options,request){if(request.headers.has("Access-Control-Allow-Origin"))return;let requestOrigin=request.headers.get("Origin"),allowedOrigin=resolveAllowedOrigin(options.origin,requestOrigin);if(allowedOrigin===null)return;let headers={"Access-Control-Allow-Origin":allowedOrigin,"Access-Control-Allow-Methods":options.methods.join(", "),"Access-Control-Allow-Headers":options.allowedHeaders.join(", ")};return options.credentials&&(headers["Access-Control-Allow-Credentials"]="true"),allowedOrigin!=="*"&&(headers.Vary="Origin"),headers}function mergeCorsHeaders(response,headers){if(response.headers.has("Access-Control-Allow-Origin"))return response;let merged=new Headers(response.headers);return new Headers(headers).forEach((value,key)=>{merged.set(key,value)}),inheritBufferedResponse(response,new Response(response.body,{status:response.status,statusText:response.statusText,headers:merged}))}function corsFetchMiddleware(options){if(!(options.enabled!==!1))return async(_request,next)=>next();let resolved={...options.origin!==void 0&&{origin:options.origin},methods:options.methods??DEFAULT_METHODS,allowedHeaders:options.allowedHeaders??DEFAULT_ALLOWED_HEADERS,credentials:options.credentials??!1};return async(request,next)=>{let headers=corsHeaders(resolved,request);if(headers===void 0)return next();if(request.method==="OPTIONS")return new Response(null,{status:204,headers});let response=await next();return mergeCorsHeaders(response,headers)}}function isGlobalCorsEnabled(cors){return cors!==void 0&&cors.enabled!==!1}init_auth_BNDyLTqp();init_dist();var MCP_MIDDLEWARE_METHODS=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function withMcpMiddlewareParams(request,params){if(typeof request!="object"||request===null||Array.isArray(request))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...request,params}}function createMcpMiddlewareEntry(pattern,handler){let normalizedPattern=normalizeMcpMiddlewarePattern(pattern),invoke2=handler;if(normalizedPattern!=="*"&&!isMcpMiddlewareMethod(normalizedPattern))throw new TypeError(`Unsupported MCP middleware pattern "${pattern}". Use an exact MCP method or "mcp:*".`);return normalizedPattern==="*"?{pattern:normalizedPattern,handler:async(ctx,next)=>{let downstreamCalled=!1,downstreamResult;if(await invoke2(ctx,async()=>{downstreamResult=await next(),downstreamCalled=!0}),!downstreamCalled)throw new Error(`Wildcard MCP middleware "${normalizedPattern}" must call next()`);return downstreamResult}}:{pattern:normalizedPattern,handler:(ctx,next)=>invoke2(ctx,next)}}function createMcpEventListenerEntry(pattern,handler){let{pattern:normalizedPattern,phase}=parseMcpPattern(pattern),invoke2=handler;return{pattern:normalizedPattern,phase,handler:(ctx,result)=>invoke2(ctx,result)}}function matchesPattern(pattern,method){if(pattern==="*")return!0;if(pattern.endsWith("/*")){let prefix=pattern.slice(0,-1);return method.startsWith(prefix)}return pattern===method}function isMcpMiddlewareMethod(value){return MCP_MIDDLEWARE_METHODS.some(method=>method===value)}function composeMiddleware(entries,method,innerFn){let matching=entries.filter(entry=>matchesPattern(entry.pattern,method));return matching.length===0?_ctx=>innerFn():ctx=>{let index=-1,dispatch=i=>i<=index?Promise.reject(new Error("next() called multiple times")):(index=i,i===matching.length?innerFn():matching[i].handler(ctx,()=>dispatch(i+1)));return dispatch(0)}}function freezeMiddlewareContext(ctx){return Object.freeze({method:ctx.method,params:Object.freeze({...ctx.params}),...ctx.request!==void 0&&{request:ctx.request},...ctx.req!==void 0&&{req:ctx.req},...ctx.session!==void 0&&{session:Object.freeze({...ctx.session})},...ctx.auth!==void 0&&{auth:ctx.auth},state:new Map(ctx.state)})}async function runMcpOperation(middlewares,events,method,ctx,innerFn){dispatchMcpEvents(events,method,"before",ctx);let result=await composeMiddleware(middlewares,method,innerFn)(ctx);return assertValidMiddlewareResult(method,result),dispatchMcpEvents(events,method,"complete",ctx,result),result}function assertValidMiddlewareResult(method,result){if((method==="tools/call"||method==="resources/read"||method==="prompts/get")&&isInputRequiredResult(result))return;let validation=(()=>{switch(method){case"tools/call":return assertArrayProperty(method,result,"content"),CallToolResultSchema.safeParse(result);case"tools/list":return assertArrayResult(method,result),ListToolsResultSchema.safeParse({tools:result});case"resources/read":return assertArrayProperty(method,result,"contents"),ReadResourceResultSchema.safeParse(result);case"resources/list":return assertArrayResult(method,result),ListResourcesResultSchema.safeParse({resources:result});case"prompts/get":return assertArrayProperty(method,result,"messages"),GetPromptResultSchema.safeParse(result);case"prompts/list":return assertArrayResult(method,result),ListPromptsResultSchema.safeParse({prompts:result});default:throw new TypeError(`Unsupported MCP middleware method "${method}"`)}})();if(!validation.success)throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: ${validation.error.message}`)}function assertArrayResult(method,result){if(!Array.isArray(result))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected an array`)}function assertArrayProperty(method,result,property){if(typeof result!="object"||result===null||!Array.isArray(result[property]))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected a ${property} array`)}function dispatchMcpEvents(events,method,phase,ctx,result){let frozen=freezeMiddlewareContext(ctx);for(let entry of events)if(!(entry.phase!==phase||!matchesPattern(entry.pattern,method)))try{entry.handler(frozen,result)}catch(error3){console.error(`[mcp-use] MCP event listener for "${entry.pattern}" (${phase}) threw:`,error3)}}function parseMcpPattern(raw2){let pattern=raw2.startsWith("mcp:")?raw2.slice(4):raw2;return pattern.endsWith(":complete")?{pattern:pattern.slice(0,-9),phase:"complete"}:{pattern,phase:"before"}}function normalizeMcpMiddlewarePattern(raw2){return raw2.startsWith("mcp:")?raw2.slice(4):raw2}init_dist();init_fetch_app();import{isBufferedResponse as isBufferedResponse2,trackBufferedResponse}from"#mcp-use-buffered-response";function colorsEnabled(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function ansi(open2,close){return text2=>colorsEnabled()?`\x1B[${open2}m${text2}\x1B[${close}m`:text2}var bold=ansi(1,22),dim=ansi(2,22),red=ansi(31,39),green=ansi(32,39),yellow=ansi(33,39),blue=ansi(34,39),magenta=ansi(35,39),cyan=ansi(36,39),gray=ansi(90,39);function resolveLogLevel(configured){let raw2=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return raw2==="info"||raw2==="debug"||raw2==="trace"?raw2:configured??"info"}function formatClientInfo(info){if(!(info===void 0||typeof info.name!="string"))return typeof info.version=="string"&&info.version!==""?`${info.name}/${info.version}`:info.name}var detailFormatters={initialize:p=>({subject:formatClientInfo(p.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":p=>({subject:p.ref.type==="ref/prompt"?p.ref.name:p.ref.uri,input:p.argument}),"logging/setLevel":p=>({subject:p.level}),"prompts/get":p=>({subject:p.name,input:p.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":p=>({subject:p.uri}),"resources/subscribe":p=>({subject:p.uri}),"resources/unsubscribe":p=>({subject:p.uri}),"subscriptions/listen":()=>({}),"tools/call":p=>({subject:p.name,input:p.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function isKnownMethod(method){return Object.prototype.hasOwnProperty.call(detailFormatters,method)}function formatDetail(message){if(!isKnownMethod(message.method))return{};try{let formatter=detailFormatters[message.method],detail=formatter(message.params);return typeof detail.subject=="string"||detail.subject===void 0?detail:{}}catch{return{}}}var INLINE_JSON_MAX_LENGTH=80;function inlineJson(value){let text2;try{text2=JSON.stringify(value)??String(value)}catch{text2=String(value)}return text2.length>INLINE_JSON_MAX_LENGTH?`${text2.slice(0,INLINE_JSON_MAX_LENGTH)}...`:text2}function formatClientIdentity(message){let meta2=message.params?._meta;if(meta2===void 0)return;let info=meta2[CLIENT_INFO_META_KEY];if(!(typeof info!="object"||info===null||typeof info.name!="string"))return formatClientInfo(info)}function formatMcpClient(message){let modern=formatClientIdentity(message);if(modern!==void 0)return modern;if(message.method==="initialize")try{return formatClientInfo(message.params.clientInfo)}catch{return}}function sanitize(text2){return text2.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function methodStyle(method){return method.startsWith("tools/")?cyan:method.startsWith("resources/")?green:method.startsWith("prompts/")?magenta:method==="initialize"||method==="ping"?gray:blue}function describeRequest(httpMethod,pathname,mcpPath,body){if(pathname!==mcpPath)return{method:httpMethod,client:void 0,mcpRequest:void 0,streaming:!1};let requests=Array.isArray(body)?body.filter(isJSONRPCRequest):isJSONRPCRequest(body)?[body]:[],mcpRequest=requests[0];return mcpRequest===void 0?{method:httpMethod,client:void 0,mcpRequest:void 0,streaming:!1}:{method:requests.length===1?sanitize(mcpRequest.method):`batch(${requests.map(request=>sanitize(request.method)).join(",")})`,client:formatMcpClient(mcpRequest)??"unknown",mcpRequest,streaming:mcpRequest.method==="subscriptions/listen"}}var REDACTED_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function redactHeaders(headers){return Object.fromEntries(Object.entries(headers).map(([name,value])=>[name,REDACTED_HEADERS.has(name.toLowerCase())?"[REDACTED]":value]))}async function extractResponseOutcome(res,request){if(!res.body)return{errorMessage:null};let text2;try{let wasBuffered=isBufferedResponse2(res,request),clone2=res.clone();wasBuffered&&trackBufferedResponse(request,res),text2=await clone2.text()}catch{return{errorMessage:null}}if(!text2)return{errorMessage:null};let isSse=(res.headers.get("content-type")??"").includes("text/event-stream"),payloads=[],tryParse=raw2=>{try{payloads.push(JSON.parse(raw2))}catch{}};if(isSse){for(let line of text2.split(/\r?\n/))if(line.startsWith("data:")){let data=line.slice(5).trim();data&&tryParse(data)}}else tryParse(text2);let result;for(let payload of payloads){if(payload===null||typeof payload!="object")continue;let message=payload;if(typeof message.error?.message=="string")return{errorMessage:message.error.message};if(message.result?.isError===!0){let textBlock=(Array.isArray(message.result.content)?message.result.content:[]).find(b=>b?.type==="text"&&typeof b.text=="string");return{errorMessage:textBlock?String(textBlock.text):"tool error"}}"result"in message&&(result=message.result)}return{errorMessage:null,result}}function compactToolResult(result){if(result===null||typeof result!="object")return result;let{structuredContent,content}=result;if(structuredContent!==void 0)return structuredContent;if(Array.isArray(content)){let[block]=content;if(content.length===1&&block?.type==="text")return block.text}return content}function formatForDump(value){function truncate(val){return typeof val=="string"&&val.length>100?`${val.slice(0,100)}...`:Array.isArray(val)?val.map(truncate):val!==null&&typeof val=="object"?Object.fromEntries(Object.entries(val).map(([k,v])=>[k,truncate(v)])):val}try{return JSON.stringify(truncate(value),null,2)}catch{return String(value)}}var DUMP_BODY_MAX_LENGTH=1e4;async function printTraceDump(response,requestHeaders,requestBody,readResponseBody){console.log(`
792
785
  ${cyan("=".repeat(80))}`),console.log(bold(cyan("[TRACE] Request Details"))),console.log(cyan("-".repeat(80))),Object.keys(requestHeaders).length>0&&(console.log(yellow("Request Headers:")),console.log(formatForDump(redactHeaders(requestHeaders)))),requestBody!==void 0&&(console.log(yellow("Request Body:")),console.log(typeof requestBody=="string"?requestBody:formatForDump(requestBody)));let responseHeaders={};if(response.headers.forEach((value,key)=>{responseHeaders[key]=value}),Object.keys(responseHeaders).length>0&&(console.log(yellow("Response Headers:")),console.log(formatForDump(redactHeaders(responseHeaders)))),!readResponseBody)console.log(`${yellow("Response Body:")} (streaming \u2014 not dumped)`);else if(response.body===null)console.log(`${yellow("Response Body:")} (no body)`);else try{let text2=await response.clone().text();if(text2.length===0)console.log(`${yellow("Response Body:")} (empty)`);else{console.log(yellow("Response Body:"));try{console.log(formatForDump(JSON.parse(text2)))}catch{console.log(text2.length>DUMP_BODY_MAX_LENGTH?`${text2.slice(0,DUMP_BODY_MAX_LENGTH)}
793
786
  ... (truncated, ${text2.length-DUMP_BODY_MAX_LENGTH} more characters)`:text2)}}}catch{console.log(`${yellow("Response Body:")} (unable to read)`)}console.log(`${cyan("=".repeat(80))}
794
- `)}function styleStatus(status){let text2=String(status);return status>=500?magenta(text2):status>=400?red(text2):status>=300?yellow(text2):green(text2)}function isNoisyRequest(httpMethod,pathname){return httpMethod!=="GET"&&httpMethod!=="HEAD"?!1:pathname.endsWith("/favicon.ico")}function formatRequestLogLine(line){let{description,detail}=line;return[...line.prefix===void 0?[]:[bold(line.prefix)],methodStyle(description.method)(description.method),...detail?.subject===void 0?[]:[bold(sanitize(detail.subject))],line.pathname,styleStatus(line.status),...description.client===void 0?[]:[dim(`client=${sanitize(description.client)}`)],dim(`${line.durationMs}ms`),...line.suffix].join(" ")}function requestLogger(options={}){return options.enabled===!1?(_request,next)=>next():async(request,next)=>{let level=resolveLogLevel(options.level),startedAt=Date.now(),httpMethod=request.method,pathname=new URL(request.url).pathname;if(isNoisyRequest(httpMethod,pathname))return next();let requestHeaders={};level==="trace"&&request.headers.forEach((value,key)=>{requestHeaders[key]=value});let requestBody;if(httpMethod!=="GET"&&httpMethod!=="HEAD"){let parsedBody=getRequestBag(request).parsedBody;if(parsedBody!==void 0)requestBody=parsedBody;else try{requestBody=await request.clone().json(),(request.headers.get("content-type")??"").includes("application/json")&&(getRequestBag(request).parsedBody=requestBody)}catch{}}let description=describeRequest(httpMethod,pathname,options.mcpPath,requestBody),logLine=(status,detail2,suffix2=[])=>{console.log(formatRequestLogLine({prefix:options.prefix,description,detail:detail2,pathname,status,durationMs:Date.now()-startedAt,suffix:suffix2}))},response;try{response=await next()}catch(error3){throw logLine(500,void 0,[red(`ERROR ${sanitize(error3 instanceof Error?error3.message:String(error3))}`)]),error3}let streaming=description.streaming||response.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()==="text/event-stream",detail=description.mcpRequest===void 0?void 0:formatDetail(description.mcpRequest),suffix=[];if(description.mcpRequest!==void 0&&detail!==void 0){let echoPayloads=level!=="info";echoPayloads&&detail.input!==void 0&&suffix.push(inlineJson(detail.input));let outcome=streaming?{errorMessage:null}:await extractResponseOutcome(response,request);echoPayloads&&description.mcpRequest.method==="tools/call"&&outcome.errorMessage===null&&outcome.result!==void 0&&suffix.push(dim("->"),inlineJson(compactToolResult(outcome.result))),outcome.errorMessage!==null?suffix.push(red(`ERROR ${sanitize(outcome.errorMessage)}`)):response.status>=400&&suffix.push(red(`ERROR (HTTP ${response.status})`))}logLine(response.status,detail,suffix);let oauthEndpoint=options.mcpPath!==void 0&&pathname.startsWith(pathUnderBase(options.mcpPath,"oauth/"));return level==="trace"&&!oauthEndpoint&&await printTraceDump(response,requestHeaders,requestBody,!streaming),response}}init_dist();init_fetch_app();import{trackBufferedResponse as trackBufferedResponse2}from"#mcp-use-buffered-response";function createMcpMount(factory,options={}){let{path="/mcp",handler:handlerOptions,authInfo:getAuthInfo}=options,legacyMode=handlerOptions?.legacy??"stateless",handler=createMcpHandler(factory,{legacy:"stateless",...handlerOptions});return{handler,fetch:async request=>{if(!matchesPath(request,path))return new Response("Not Found",{status:404});if(legacyMode==="stateless"){let method=request.method.toUpperCase();if(method==="GET"||method==="DELETE"||method==="HEAD")return new Response(null,{status:204})}let bag=getRequestBag(request),parsedBody=bag.parsedBody;if(parsedBody===void 0)try{parsedBody=await request.clone().json()}catch{}let capabilities=extractClientCapabilitiesFromBody(parsedBody);capabilities!==void 0&&stashClientCapabilities(request,capabilities);let authInfo=getAuthInfo?.(request)??bag.authInfo,response=await handler.fetch(request,{...parsedBody!==void 0&&{parsedBody},...authInfo!==void 0&&{authInfo}});return response.headers.get("content-type")?.toLowerCase().includes("application/json")?"Bun"in globalThis&&response.body!==null?new Response(await response.arrayBuffer(),{status:response.status,statusText:response.statusText,headers:response.headers}):trackBufferedResponse2(request,response):response}}}function object2(value,label){if(value===null||typeof value!="object"||Array.isArray(value))throw new TypeError(`${label} must be an object`);return value}function array2(value,label){if(!Array.isArray(value))throw new TypeError(`${label} must be an array`);return value}function nonBlank(value,label){if(typeof value!="string"||!value.trim())throw new TypeError(`${label} must be a non-blank string`)}function standard(json,validate){return{"~standard":{version:1,vendor:"mcp-use",jsonSchema:{input:()=>json,output:()=>json},async validate(value){try{return{value:await validate(value)}}catch(error3){return{issues:[{message:error3 instanceof Error?error3.message:String(error3)}]}}}}}}function prepareSettings(options){let readTool=options.readTool??"settings.read",updateTool=options.updateTool??"settings.update";if(nonBlank(readTool,"readTool"),nonBlank(updateTool,"updateTool"),readTool===updateTool)throw new TypeError("Settings read and update tools must have different names");object2(options.fields,"fields");let fields=Object.entries(options.fields).map(([name,field])=>[name,{...field}]);if(!fields.length)throw new TypeError("Settings require at least one field");let properties={};for(let[name,field]of fields){if(nonBlank(field.title,`Setting ${name} title`),field.description!==void 0&&typeof field.description!="string")throw new TypeError(`Setting ${name} description must be a string`);let outputProperty=field.schema["~standard"].jsonSchema.output({target:"draft-2020-12"}),property=field.schema["~standard"].jsonSchema.input({target:"draft-2020-12"});if(!["boolean","string","number","integer"].includes(String(property.type))||outputProperty.type!==property.type||["$ref","anyOf","oneOf","allOf"].some(key=>key in property)||property.enum!==void 0&&(property.type!=="string"||!Array.isArray(property.enum)||!property.enum.length||!property.enum.every(item=>typeof item=="string")))throw new TypeError(`Unsupported native setting ${name}: use boolean, string, string enum, number, or integer`);let wireProperty=structuredClone(property);delete wireProperty.default,Object.defineProperty(properties,name,{enumerable:!0,value:{...wireProperty,title:field.title,...field.description!==void 0&&{description:field.description}}})}let schema2={type:"object",properties,required:fields.map(([name])=>name),additionalProperties:!1},layout=options.layout===void 0?void 0:structuredClone(options.layout);if(layout!==void 0)for(let groupValue of array2(layout,"Settings layout")){let group=object2(groupValue,"Settings layout group");if(group.kind!=="group")throw new TypeError("Settings layout groups must have kind 'group'");nonBlank(group.title,"Settings layout group title");for(let itemValue of array2(group.items,"Settings layout group items")){let item=object2(itemValue,"Settings layout item");if(item.kind==="property"){if(nonBlank(item.property,"Settings layout property"),!Object.hasOwn(properties,item.property))throw new TypeError(`Settings layout references unknown setting: ${item.property}`)}else if(item.kind==="tool"){if(nonBlank(item.tool,"Settings layout action tool"),nonBlank(item.title,"Settings layout action title"),item.description!==void 0&&typeof item.description!="string")throw new TypeError("Settings layout action description must be a string")}else throw new TypeError("Settings layout items must have kind 'property' or 'tool'")}}let validateValues=async(value,partial2=!1)=>{let values=object2(value,partial2?"set":"values");for(let name of Object.keys(values))if(!Object.hasOwn(properties,name))throw new TypeError(`Unknown setting: ${name}`);if(partial2&&!Object.keys(values).length)throw new TypeError("Set at least one setting");let result={};for(let[name,field]of fields){if(!Object.hasOwn(values,name)){if(!partial2)throw new TypeError(`Missing effective setting: ${name}`);continue}let parsed=await field.schema["~standard"].validate(values[name]);if(parsed.issues!==void 0)throw new TypeError(`Invalid setting ${name}: ${parsed.issues.map(issue2=>issue2.message).join(", ")}`);if(parsed.value===void 0||!["string","boolean","number"].includes(typeof parsed.value)||typeof parsed.value=="number"&&!Number.isFinite(parsed.value))throw new TypeError(`Invalid primitive setting: ${name}`);if(!Object.is(parsed.value,values[name]))throw new TypeError(`Setting ${name} schema must not transform values`);Object.defineProperty(result,name,{enumerable:!0,value:parsed.value})}return result},emptySchema=standard({type:"object",additionalProperties:!1},value=>{if(Object.keys(object2(value,"arguments")).length)throw new TypeError("Settings read accepts empty arguments");return{}}),updateInput=standard({type:"object",properties:{set:{...schema2,required:[],minProperties:1}},required:["set"],additionalProperties:!1},async value=>{let input=object2(value,"arguments");if(Object.keys(input).some(key=>key!=="set"))throw new TypeError("Unknown settings update argument");return{set:await validateValues(input.set,!0)}}),readOutput=standard({type:"object",properties:{schema:{type:"object"},values:schema2,layout:{type:"array",items:{type:"object",properties:{kind:{const:"group"},title:{type:"string"},items:{type:"array",items:{type:"object"}}},required:["kind","title","items"]}}},required:["schema","values"]},async value=>{let output=object2(value,"settings result");return{...output,values:await validateValues(output.values)}}),updateOutput=standard({type:"object",properties:{values:schema2},required:["values"]},async value=>({values:await validateValues(object2(value,"settings result").values)}));return{capability:{readTool,updateTool},schema:schema2,layout,readDefinition:{name:readTool,inputSchema:emptySchema,outputSchema:readOutput,annotations:{readOnlyHint:!0}},updateDefinition:{name:updateTool,inputSchema:updateInput,outputSchema:updateOutput}}}init_dist();function createPrefixCompletion(values){let strings=values.map(String);return value=>{let prefix=String(value??"").toLowerCase();return strings.filter(candidate=>candidate.toLowerCase().startsWith(prefix))}}function completable2(schema2,complete){return typeof complete=="function"?completable(schema2,(value,context)=>complete(String(value??""),context)):completable(schema2,createPrefixCompletion(complete))}function normalizeCompletions(completions){let normalized=Object.create(null);for(let[variable,completer]of Object.entries(completions))completer!==void 0&&(normalized[variable]=Array.isArray(completer)?createPrefixCompletion(completer):completer);return normalized}init_dist();var inputSchema=fromJsonSchema2({type:"object",properties:{query:{type:"string"}},required:["query"]}),outputSchema=fromJsonSchema2({type:"object",properties:{items:{type:"array",items:ResourceLinkSchema["~standard"].jsonSchema.output({target:"draft-2020-12"})}},required:["items"]});function record2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:{}}function prepareMentions(options){if(typeof options.name!="string"||!options.name.trim())throw new TypeError("Mention tool name must be a non-blank string");if(typeof options.search!="function")throw new TypeError("Mention search must be a callback");let{search:_search,...descriptor}=options;return{...descriptor,inputSchema,outputSchema,annotations:{readOnlyHint:!0,...options.annotations},_meta:{...options._meta,"openai/extensions":{...record2(options._meta?.["openai/extensions"]),"mentions/search":{}}}}}function finalizeMentionsMeta(definition,metadata){let rawUi=record2(definition._meta?.ui),visibility=definition.visibility!==void 0?[definition.visibility]:Array.isArray(rawUi.visibility)?rawUi.visibility:[];return{...metadata,ui:{...record2(metadata?.ui),visibility:[...new Set([...visibility,"app"])]}}}init_dist();var HTTP_METHODS=["get","put","post","delete","options","head","patch","trace"];function registerOpenAPITools(server,options){let operations=collectOperations(options.spec,options),names=createToolNames(operations),baseUrl=operations.length>0?resolveBaseUrl(options):void 0;for(let[index,operation]of operations.entries()){let name=names[index];if(name===void 0||baseUrl===void 0)continue;let inputBindings=createInputBindings(operation);server.tool({name,description:createToolDescription(operation),inputSchema:createToolInputSchema(options.spec,operation,inputBindings)},async params=>callOpenAPIOperation(operation,params,options,inputBindings,baseUrl))}}function collectOperations(spec,options){let collected=[];for(let[path,pathItemOrRef]of Object.entries(spec.paths??{})){let pathItem=resolveRef(spec,pathItemOrRef);if(pathItem===void 0||isReferenceObject(pathItem))continue;let pathParameters=resolveParameters(spec,pathItem.parameters);for(let method of HTTP_METHODS){let operationOrRef=pathItem[method];if(operationOrRef===void 0)continue;let operation=resolveRef(spec,operationOrRef);if(operation===void 0||isReferenceObject(operation))continue;let operationParameters=resolveParameters(spec,operation.parameters),requestBody=operation.requestBody===void 0?void 0:resolveRef(spec,operation.requestBody),item={method,path,operation,parameters:mergeParameters(pathParameters,operationParameters),...requestBody!==void 0&&!isReferenceObject(requestBody)&&{requestBody}};isIncluded(item,options)&&collected.push(item)}}return collected}function resolveParameters(spec,parameters){let resolved=[];for(let parameter of parameters??[]){let value=resolveRef(spec,parameter);value!==void 0&&!isReferenceObject(value)&&resolved.push(value)}return resolved}function mergeParameters(pathParameters,operationParameters){let merged=new Map;for(let parameter of[...pathParameters,...operationParameters])merged.set(`${parameter.in}:${parameter.name}`,parameter);return[...merged.values()]}function isIncluded(operation,options){if(options.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!options.tags.some(tag=>tags.has(tag)))return!1}return!(options.exclude??[]).some(rule=>matchesExcludeRule(operation,rule))}function matchesExcludeRule(operation,rule){if(rule.method&&rule.method.toLowerCase()!==operation.method||rule.operationId&&!matchesPattern2(rule.operationId,operation.operation.operationId??"")||rule.path&&!matchesPattern2(rule.path,operation.path))return!1;if(rule.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!rule.tags.some(tag=>tags.has(tag)))return!1}return!0}function matchesPattern2(pattern,value){return typeof pattern=="string"?pattern===value:(pattern.lastIndex=0,pattern.test(value))}function createToolNames(operations){let seen=new Map;return operations.map(operation=>{let baseName=slugifyToolName(operation.operation.operationId??`${operation.method}_${operation.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),count=seen.get(baseName)??0;if(seen.set(baseName,count+1),count===0)return baseName;let suffix=`_${count+1}`;return`${baseName.slice(0,64-suffix.length)}${suffix}`})}function createToolDescription(operation){return[operation.operation.summary,operation.operation.description,`HTTP: ${operation.method.toUpperCase()} ${operation.path}`].filter(part=>!!part).join(`
787
+ `)}function styleStatus(status){let text2=String(status);return status>=500?magenta(text2):status>=400?red(text2):status>=300?yellow(text2):green(text2)}function isNoisyRequest(httpMethod,pathname){return httpMethod!=="GET"&&httpMethod!=="HEAD"?!1:pathname.endsWith("/favicon.ico")}function formatRequestLogLine(line){let{description,detail}=line;return[...line.prefix===void 0?[]:[bold(line.prefix)],methodStyle(description.method)(description.method),...detail?.subject===void 0?[]:[bold(sanitize(detail.subject))],line.pathname,styleStatus(line.status),...description.client===void 0?[]:[dim(`client=${sanitize(description.client)}`)],dim(`${line.durationMs}ms`),...line.suffix].join(" ")}function requestLogger(options={}){return options.enabled===!1?(_request,next)=>next():async(request,next)=>{let level=resolveLogLevel(options.level),startedAt=Date.now(),httpMethod=request.method,pathname=new URL(request.url).pathname;if(isNoisyRequest(httpMethod,pathname))return next();let requestHeaders={};level==="trace"&&request.headers.forEach((value,key)=>{requestHeaders[key]=value});let requestBody;if(httpMethod!=="GET"&&httpMethod!=="HEAD"){let parsedBody=getRequestBag(request).parsedBody;if(parsedBody!==void 0)requestBody=parsedBody;else try{requestBody=await request.clone().json(),(request.headers.get("content-type")??"").includes("application/json")&&(getRequestBag(request).parsedBody=requestBody)}catch{}}let description=describeRequest(httpMethod,pathname,options.mcpPath,requestBody),logLine=(status,detail2,suffix2=[])=>{console.log(formatRequestLogLine({prefix:options.prefix,description,detail:detail2,pathname,status,durationMs:Date.now()-startedAt,suffix:suffix2}))},response;try{response=await next()}catch(error3){throw logLine(500,void 0,[red(`ERROR ${sanitize(error3 instanceof Error?error3.message:String(error3))}`)]),error3}let streaming=description.streaming||response.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()==="text/event-stream",detail=description.mcpRequest===void 0?void 0:formatDetail(description.mcpRequest),suffix=[];if(description.mcpRequest!==void 0&&detail!==void 0){let echoPayloads=level!=="info";echoPayloads&&detail.input!==void 0&&suffix.push(inlineJson(detail.input));let outcome=streaming?{errorMessage:null}:await extractResponseOutcome(response,request);echoPayloads&&description.mcpRequest.method==="tools/call"&&outcome.errorMessage===null&&outcome.result!==void 0&&suffix.push(dim("->"),inlineJson(compactToolResult(outcome.result))),outcome.errorMessage!==null?suffix.push(red(`ERROR ${sanitize(outcome.errorMessage)}`)):response.status>=400&&suffix.push(red(`ERROR (HTTP ${response.status})`))}logLine(response.status,detail,suffix);let oauthEndpoint=options.mcpPath!==void 0&&pathname.startsWith(pathUnderBase(options.mcpPath,"oauth/"));return level==="trace"&&!oauthEndpoint&&await printTraceDump(response,requestHeaders,requestBody,!streaming),response}}init_dist();init_fetch_app();import{trackBufferedResponse as trackBufferedResponse2}from"#mcp-use-buffered-response";function createMcpMount(factory,options={}){let{path="/mcp",handler:handlerOptions,authInfo:getAuthInfo}=options,legacyMode=handlerOptions?.legacy??"stateless",handler=createMcpHandler(factory,{legacy:"stateless",...handlerOptions});return{handler,fetch:async request=>{if(!matchesPath(request,path))return new Response("Not Found",{status:404});if(legacyMode==="stateless"){let method=request.method.toUpperCase();if(method==="GET"||method==="DELETE"||method==="HEAD")return new Response(null,{status:204})}let bag=getRequestBag(request),parsedBody=bag.parsedBody;if(parsedBody===void 0)try{parsedBody=await request.clone().json()}catch{}let capabilities=extractClientCapabilitiesFromBody(parsedBody);capabilities!==void 0&&stashClientCapabilities(request,capabilities);let authInfo=getAuthInfo?.(request)??bag.authInfo,response=await handler.fetch(request,{...parsedBody!==void 0&&{parsedBody},...authInfo!==void 0&&{authInfo}});return response.headers.get("content-type")?.toLowerCase().includes("application/json")?"Bun"in globalThis&&response.body!==null?new Response(await response.arrayBuffer(),{status:response.status,statusText:response.statusText,headers:response.headers}):trackBufferedResponse2(request,response):response}}}function object2(value,label){if(value===null||typeof value!="object"||Array.isArray(value))throw new TypeError(`${label} must be an object`);return value}function array2(value,label){if(!Array.isArray(value))throw new TypeError(`${label} must be an array`);return value}function nonBlank(value,label){if(typeof value!="string"||!value.trim())throw new TypeError(`${label} must be a non-blank string`)}function standard(json,validate2){return{"~standard":{version:1,vendor:"mcp-use",jsonSchema:{input:()=>json,output:()=>json},async validate(value){try{return{value:await validate2(value)}}catch(error3){return{issues:[{message:error3 instanceof Error?error3.message:String(error3)}]}}}}}}function prepareSettings(options){let readTool=options.readTool??"settings.read",updateTool=options.updateTool??"settings.update";if(nonBlank(readTool,"readTool"),nonBlank(updateTool,"updateTool"),readTool===updateTool)throw new TypeError("Settings read and update tools must have different names");object2(options.fields,"fields");let fields=Object.entries(options.fields).map(([name,field])=>[name,{...field}]);if(!fields.length)throw new TypeError("Settings require at least one field");let properties={};for(let[name,field]of fields){if(nonBlank(field.title,`Setting ${name} title`),field.description!==void 0&&typeof field.description!="string")throw new TypeError(`Setting ${name} description must be a string`);let outputProperty=field.schema["~standard"].jsonSchema.output({target:"draft-2020-12"}),property=field.schema["~standard"].jsonSchema.input({target:"draft-2020-12"});if(!["boolean","string","number","integer"].includes(String(property.type))||outputProperty.type!==property.type||["$ref","anyOf","oneOf","allOf"].some(key=>key in property)||property.enum!==void 0&&(property.type!=="string"||!Array.isArray(property.enum)||!property.enum.length||!property.enum.every(item=>typeof item=="string")))throw new TypeError(`Unsupported native setting ${name}: use boolean, string, string enum, number, or integer`);let wireProperty=structuredClone(property);delete wireProperty.default,Object.defineProperty(properties,name,{enumerable:!0,value:{...wireProperty,title:field.title,...field.description!==void 0&&{description:field.description}}})}let schema2={type:"object",properties,required:fields.map(([name])=>name),additionalProperties:!1},layout=options.layout===void 0?void 0:structuredClone(options.layout);if(layout!==void 0)for(let groupValue of array2(layout,"Settings layout")){let group=object2(groupValue,"Settings layout group");if(group.kind!=="group")throw new TypeError("Settings layout groups must have kind 'group'");nonBlank(group.title,"Settings layout group title");for(let itemValue of array2(group.items,"Settings layout group items")){let item=object2(itemValue,"Settings layout item");if(item.kind==="property"){if(nonBlank(item.property,"Settings layout property"),!Object.hasOwn(properties,item.property))throw new TypeError(`Settings layout references unknown setting: ${item.property}`)}else if(item.kind==="tool"){if(nonBlank(item.tool,"Settings layout action tool"),nonBlank(item.title,"Settings layout action title"),item.description!==void 0&&typeof item.description!="string")throw new TypeError("Settings layout action description must be a string")}else throw new TypeError("Settings layout items must have kind 'property' or 'tool'")}}let validateValues=async(value,partial2=!1)=>{let values=object2(value,partial2?"set":"values");for(let name of Object.keys(values))if(!Object.hasOwn(properties,name))throw new TypeError(`Unknown setting: ${name}`);if(partial2&&!Object.keys(values).length)throw new TypeError("Set at least one setting");let result={};for(let[name,field]of fields){if(!Object.hasOwn(values,name)){if(!partial2)throw new TypeError(`Missing effective setting: ${name}`);continue}let parsed=await field.schema["~standard"].validate(values[name]);if(parsed.issues!==void 0)throw new TypeError(`Invalid setting ${name}: ${parsed.issues.map(issue2=>issue2.message).join(", ")}`);if(parsed.value===void 0||!["string","boolean","number"].includes(typeof parsed.value)||typeof parsed.value=="number"&&!Number.isFinite(parsed.value))throw new TypeError(`Invalid primitive setting: ${name}`);if(!Object.is(parsed.value,values[name]))throw new TypeError(`Setting ${name} schema must not transform values`);Object.defineProperty(result,name,{enumerable:!0,value:parsed.value})}return result},emptySchema=standard({type:"object",additionalProperties:!1},value=>{if(Object.keys(object2(value,"arguments")).length)throw new TypeError("Settings read accepts empty arguments");return{}}),updateInput=standard({type:"object",properties:{set:{...schema2,required:[],minProperties:1}},required:["set"],additionalProperties:!1},async value=>{let input=object2(value,"arguments");if(Object.keys(input).some(key=>key!=="set"))throw new TypeError("Unknown settings update argument");return{set:await validateValues(input.set,!0)}}),readOutput=standard({type:"object",properties:{schema:{type:"object"},values:schema2,layout:{type:"array",items:{type:"object",properties:{kind:{const:"group"},title:{type:"string"},items:{type:"array",items:{type:"object"}}},required:["kind","title","items"]}}},required:["schema","values"]},async value=>{let output=object2(value,"settings result");return{...output,values:await validateValues(output.values)}}),updateOutput=standard({type:"object",properties:{values:schema2},required:["values"]},async value=>({values:await validateValues(object2(value,"settings result").values)}));return{capability:{readTool,updateTool},schema:schema2,layout,readDefinition:{name:readTool,inputSchema:emptySchema,outputSchema:readOutput,annotations:{readOnlyHint:!0}},updateDefinition:{name:updateTool,inputSchema:updateInput,outputSchema:updateOutput}}}init_dist();function createPrefixCompletion(values){let strings=values.map(String);return value=>{let prefix=String(value??"").toLowerCase();return strings.filter(candidate=>candidate.toLowerCase().startsWith(prefix))}}function completable2(schema2,complete){return typeof complete=="function"?completable(schema2,(value,context)=>complete(String(value??""),context)):completable(schema2,createPrefixCompletion(complete))}function normalizeCompletions(completions){let normalized=Object.create(null);for(let[variable,completer]of Object.entries(completions))completer!==void 0&&(normalized[variable]=Array.isArray(completer)?createPrefixCompletion(completer):completer);return normalized}init_dist();var inputSchema=fromJsonSchema2({type:"object",properties:{query:{type:"string"}},required:["query"]}),outputSchema=fromJsonSchema2({type:"object",properties:{items:{type:"array",items:ResourceLinkSchema["~standard"].jsonSchema.output({target:"draft-2020-12"})}},required:["items"]});function record2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:{}}function prepareMentions(options){if(typeof options.name!="string"||!options.name.trim())throw new TypeError("Mention tool name must be a non-blank string");if(typeof options.search!="function")throw new TypeError("Mention search must be a callback");let{search:_search,...descriptor}=options;return{...descriptor,inputSchema,outputSchema,annotations:{readOnlyHint:!0,...options.annotations},_meta:{...options._meta,"openai/extensions":{...record2(options._meta?.["openai/extensions"]),"mentions/search":{}}}}}function finalizeMentionsMeta(definition,metadata){let rawUi=record2(definition._meta?.ui),visibility=definition.visibility!==void 0?[definition.visibility]:Array.isArray(rawUi.visibility)?rawUi.visibility:[];return{...metadata,ui:{...record2(metadata?.ui),visibility:[...new Set([...visibility,"app"])]}}}init_dist();var HTTP_METHODS=["get","put","post","delete","options","head","patch","trace"];function registerOpenAPITools(server,options){let operations=collectOperations(options.spec,options),names=createToolNames(operations),baseUrl=operations.length>0?resolveBaseUrl(options):void 0;for(let[index,operation]of operations.entries()){let name=names[index];if(name===void 0||baseUrl===void 0)continue;let inputBindings=createInputBindings(operation);server.tool({name,description:createToolDescription(operation),inputSchema:createToolInputSchema(options.spec,operation,inputBindings)},async params=>callOpenAPIOperation(operation,params,options,inputBindings,baseUrl))}}function collectOperations(spec,options){let collected=[];for(let[path,pathItemOrRef]of Object.entries(spec.paths??{})){let pathItem=resolveRef(spec,pathItemOrRef);if(pathItem===void 0||isReferenceObject(pathItem))continue;let pathParameters=resolveParameters(spec,pathItem.parameters);for(let method of HTTP_METHODS){let operationOrRef=pathItem[method];if(operationOrRef===void 0)continue;let operation=resolveRef(spec,operationOrRef);if(operation===void 0||isReferenceObject(operation))continue;let operationParameters=resolveParameters(spec,operation.parameters),requestBody=operation.requestBody===void 0?void 0:resolveRef(spec,operation.requestBody),item={method,path,operation,parameters:mergeParameters(pathParameters,operationParameters),...requestBody!==void 0&&!isReferenceObject(requestBody)&&{requestBody}};isIncluded(item,options)&&collected.push(item)}}return collected}function resolveParameters(spec,parameters){let resolved=[];for(let parameter of parameters??[]){let value=resolveRef(spec,parameter);value!==void 0&&!isReferenceObject(value)&&resolved.push(value)}return resolved}function mergeParameters(pathParameters,operationParameters){let merged=new Map;for(let parameter of[...pathParameters,...operationParameters])merged.set(`${parameter.in}:${parameter.name}`,parameter);return[...merged.values()]}function isIncluded(operation,options){if(options.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!options.tags.some(tag=>tags.has(tag)))return!1}return!(options.exclude??[]).some(rule=>matchesExcludeRule(operation,rule))}function matchesExcludeRule(operation,rule){if(rule.method&&rule.method.toLowerCase()!==operation.method||rule.operationId&&!matchesPattern2(rule.operationId,operation.operation.operationId??"")||rule.path&&!matchesPattern2(rule.path,operation.path))return!1;if(rule.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!rule.tags.some(tag=>tags.has(tag)))return!1}return!0}function matchesPattern2(pattern,value){return typeof pattern=="string"?pattern===value:(pattern.lastIndex=0,pattern.test(value))}function createToolNames(operations){let seen=new Map;return operations.map(operation=>{let baseName=slugifyToolName(operation.operation.operationId??`${operation.method}_${operation.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),count=seen.get(baseName)??0;if(seen.set(baseName,count+1),count===0)return baseName;let suffix=`_${count+1}`;return`${baseName.slice(0,64-suffix.length)}${suffix}`})}function createToolDescription(operation){return[operation.operation.summary,operation.operation.description,`HTTP: ${operation.method.toUpperCase()} ${operation.path}`].filter(part=>!!part).join(`
795
788
 
796
- `)}function slugifyToolName(value){return value.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function createToolInputSchema(spec,operation,inputBindings){let properties={},required2=[];for(let{parameter,inputName}of inputBindings.parameters){let parameterSchema=transformSchema(spec,parameter.schema??{});properties[inputName]={...parameterSchema,description:parameter.description??`${parameter.in} parameter`},(parameter.required||parameter.in==="path")&&required2.push(inputName)}let bodySchema=getJsonRequestBodySchema(operation.requestBody);bodySchema!==void 0&&inputBindings.bodyInputName!==void 0&&(properties[inputBindings.bodyInputName]=transformSchema(spec,bodySchema),operation.requestBody?.required&&required2.push(inputBindings.bodyInputName));let definitions=createSchemaDefinitions(spec),schema2={type:"object",properties,additionalProperties:!1,...required2.length>0&&{required:required2},...definitions!==void 0&&{$defs:definitions}};return fromJsonSchema2(schema2)}function createInputBindings(operation){let parameters=operation.parameters.filter(parameter=>parameter.in!=="cookie"),bodyInputName=getJsonRequestBodySchema(operation.requestBody)===void 0?void 0:"body",nameCounts=new Map;for(let parameter of parameters)nameCounts.set(parameter.name,(nameCounts.get(parameter.name)??0)+1);let usedNames=new Set(bodyInputName===void 0?[]:[bodyInputName]);return{parameters:parameters.map(parameter=>{let preferredName=(nameCounts.get(parameter.name)??0)>1||parameter.name===bodyInputName?`${parameter.name}_${parameter.in}`:parameter.name;return{parameter,inputName:claimInputName(preferredName,usedNames)}}),...bodyInputName!==void 0&&{bodyInputName}}}function claimInputName(preferredName,usedNames){let inputName=preferredName,suffix=2;for(;usedNames.has(inputName);)inputName=`${preferredName}_${suffix}`,suffix+=1;return usedNames.add(inputName),inputName}function createSchemaDefinitions(spec){let schemas=readRecord(spec.components?.schemas);if(schemas===void 0)return;let definitions={};for(let[name,schema2]of Object.entries(schemas))definitions[name]=transformSchemaNode(spec,schema2,new Set);return definitions}function transformSchema(spec,schema2){let transformed=transformSchemaNode(spec,schema2,new Set);return readRecord(transformed)??{}}function transformSchemaNode(spec,value,resolvingRefs){if(Array.isArray(value))return value.map(item=>transformSchemaNode(spec,item,resolvingRefs));let object5=readRecord(value);if(object5===void 0)return value;let ref=typeof object5.$ref=="string"?object5.$ref:void 0,siblings={};for(let[key,child]of Object.entries(object5))key!=="$ref"&&(key==="nullable"&&typeof child=="boolean"||isExclusiveBoundKey(key)&&typeof child=="boolean"||(siblings[key]=transformSchemaNode(spec,child,resolvingRefs)));for(let[boundKey,exclusiveKey]of EXCLUSIVE_BOUND_KEYS)object5[exclusiveKey]===!0&&typeof object5[boundKey]=="number"&&(siblings[exclusiveKey]=object5[boundKey],delete siblings[boundKey]);let transformed=siblings;if(ref!==void 0){let schemaRef=rewriteSchemaRef(spec,ref);if(schemaRef!==void 0)transformed={$ref:schemaRef,...siblings};else if(!resolvingRefs.has(ref)){let resolved=resolveRef(spec,{$ref:ref});if(resolved!==void 0){let nextRefs=new Set(resolvingRefs);nextRefs.add(ref),transformed={...readRecord(transformSchemaNode(spec,resolved,nextRefs))??{},...siblings}}}}return object5.nullable===!0?{anyOf:[transformed,{type:"null"}]}:transformed}var EXCLUSIVE_BOUND_KEYS=[["minimum","exclusiveMinimum"],["maximum","exclusiveMaximum"]];function isExclusiveBoundKey(key){return key==="exclusiveMinimum"||key==="exclusiveMaximum"}function rewriteSchemaRef(spec,ref){let prefix="#/components/schemas/";if(ref.startsWith(prefix))return resolveRef(spec,{$ref:ref})===void 0?void 0:`#/$defs/${ref.slice(prefix.length)}`}function getJsonRequestBodySchema(requestBody){let content=requestBody?.content;if(content!==void 0)return content["application/json"]?.schema??content["application/*+json"]?.schema??Object.entries(content).find(([mediaType])=>mediaType.includes("+json"))?.[1].schema}async function callOpenAPIOperation(operation,params,options,inputBindings,baseUrl){let fetchImpl=options.fetch??globalThis.fetch,url2=buildUrl(operation,params,inputBindings.parameters,baseUrl),headers=buildHeaders(inputBindings.parameters,params,options),bodyInputName=inputBindings.bodyInputName,body=bodyInputName===void 0||params[bodyInputName]===void 0?void 0:JSON.stringify(params[bodyInputName]);body!==void 0&&!hasHeader(headers,"content-type")&&(headers["content-type"]="application/json");let response=await fetchImpl(url2,{method:operation.method.toUpperCase(),headers,...body!==void 0&&{body}}),contentType=response.headers.get("content-type")??"";if(!response.ok)return{content:[{type:"text",text:await response.text()}],isError:!0};if(contentType.includes("application/json")||contentType.includes("+json")){let text2=await response.text();try{let data=JSON.parse(text2);return{content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}catch{return{content:[{type:"text",text:text2}]}}}return{content:[{type:"text",text:await response.text()}]}}function buildUrl(operation,params,parameterBindings,baseUrl){let interpolatedPath=operation.path.replace(/{([^}]+)}/g,(_match,name)=>{let binding=parameterBindings.find(({parameter})=>parameter.in==="path"&&parameter.name===name);return encodeURIComponent(String(binding===void 0?"":params[binding.inputName]??""))}),url2=new URL(interpolatedPath.replace(/^\/+/,""),ensureTrailingSlash(baseUrl));for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="query")continue;let value=params[inputName];value==null||value===""||appendQueryParam(url2,parameter.name,value)}return url2.toString()}function buildHeaders(parameterBindings,params,options){let headers={...options.headers??{}};for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="header")continue;let value=params[inputName];value==null||value===""||(headers[parameter.name]=String(value))}return options.auth?.type==="bearer"&&options.auth.token&&(headers.authorization=`Bearer ${options.auth.token}`),options.auth?.type==="header"&&options.auth.value&&(headers[options.auth.name]=options.auth.value),headers}function resolveBaseUrl(options){let baseUrl=options.baseUrl??options.spec.servers?.[0]?.url;if(baseUrl===void 0||baseUrl.trim()==="")throw new Error("MCPServer.fromOpenAPI requires options.baseUrl or spec.servers[0].url");return baseUrl}function appendQueryParam(url2,name,value){if(Array.isArray(value)){for(let item of value)item!=null&&item!==""&&url2.searchParams.append(name,String(item));return}url2.searchParams.set(name,String(value))}function ensureTrailingSlash(url2){return url2.endsWith("/")?url2:`${url2}/`}function hasHeader(headers,name){return Object.keys(headers).some(headerName=>headerName.toLowerCase()===name)}function isReferenceObject(value){let object5=readRecord(value);return object5!==void 0&&typeof object5.$ref=="string"}function resolveRef(spec,value){if(!isReferenceObject(value))return value;if(!value.$ref.startsWith("#/"))return;let segments=value.$ref.slice(2).split("/").map(segment=>segment.replace(/~1/g,"/").replace(/~0/g,"~")),current=spec;for(let segment of segments){let object5=readRecord(current);if(object5===void 0||!(segment in object5))return;current=object5[segment]}return current}function readRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}init_dist();init_dist();init_fetch_app();function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isLocalhost(url2){let hostname=url2.hostname.toLowerCase();return hostname==="localhost"||hostname.endsWith(".localhost")||hostname==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(hostname)}function parseAbsoluteUrl(value,name){let url2;try{url2=new URL(value)}catch{throw new Error(`${name} must be an absolute URL`)}if(url2.origin==="null"||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute URL without credentials`);return url2}function assertSecureHttpUrl(url2,name){if(url2.protocol!=="https:"&&!(url2.protocol==="http:"&&isLocalhost(url2)))throw new Error(`${name} must use HTTPS, or HTTP for localhost`)}function assertOAuthMetadata(metadata){if(metadata===null||typeof metadata!="object"||!("issuer"in metadata)||typeof metadata.issuer!="string")throw new TypeError("oauthMetadata must include a string issuer");assertSecureHttpUrl(parseAbsoluteUrl(metadata.issuer,"oauthMetadata.issuer"),"oauthMetadata.issuer")}init_dist();function invalidToken(message,cause){let error3=new OAuthError(OAuthErrorCode.InvalidToken,message);return cause!==void 0&&(error3.cause=cause),error3}function resolveConfiguredOAuthResource(options){let provider=options.provider,basePath=normalizeBasePath(options.basePath);if(provider.resource!==void 0)return validateOAuthResource(provider.resource,basePath);if(options.mcpUrl!==void 0)return validateOAuthResource(appendBasePath(requireAbsoluteOrigin(options.mcpUrl,"MCP_URL"),basePath),basePath)}function resolveLocalOAuthResource(listenOrigin,basePath){let listenOriginUrl=requireAbsoluteOrigin(listenOrigin,"listen origin");if(!isLocalhost(listenOriginUrl))throw new Error("OAuth listen origin must be localhost or a loopback address");return validateOAuthResource(appendBasePath(listenOriginUrl,normalizeBasePath(basePath)),basePath)}function validateOAuthResource(resource2,basePath){let normalizedBasePath=normalizeBasePath(basePath),url2=parseAbsoluteUrl(resource2,"OAuth resource");if(url2.search!==""||url2.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(assertSecureHttpUrl(url2,"OAuth resource"),normalizePathname(url2.pathname)!==normalizedBasePath)throw new Error(`OAuth resource path must exactly match basePath (${normalizedBasePath})`);return url2.pathname=normalizedBasePath,url2}function wrapOAuthTokenVerifier(provider,expectedResource){let canonicalResource=normalizeResourceUrl(expectedResource),tokenVerifier=provider.createTokenVerifier(new URL(canonicalResource.href));if(tokenVerifier===null||typeof tokenVerifier!="object"||typeof tokenVerifier.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(token){let authInfo=await tokenVerifier.verifyAccessToken(token);assertVerifiedAuthInfo(authInfo),assertResourceBinding(authInfo,canonicalResource);let mapped;try{mapped=provider.mapAuthInfo(authInfo)}catch(error3){throw invalidToken("Token identity mapping failed",error3)}return assertMappedExtra(mapped),{...authInfo,scopes:[...authInfo.scopes],extra:{...authInfo.extra,...mapped}}}}}function assertResourceBinding(authInfo,expectedResource){if(authInfo.resource===void 0)throw invalidToken("Token verifier did not return a validated protected resource");if(parseTokenResource(authInfo.resource).href!==normalizeResourceUrl(expectedResource).href)throw invalidToken("Token resource does not match the protected resource")}function parseTokenResource(value){if(!(value instanceof URL))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");let resource2=value;if(!/^https?:$/.test(resource2.protocol)||resource2.username!==""||resource2.password!==""||resource2.search!==""||resource2.hash!==""||resource2.protocol==="http:"&&!isLocalhost(resource2))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return normalizeResourceUrl(resource2)}function normalizeResourceUrl(resource2){let normalized=new URL(resource2);return normalized.pathname=normalized.pathname==="/"?"/":normalized.pathname.replace(/\/+$/,""),normalized}function resolveOAuthMetadata(provider,resource2){let metadata=provider.oauthMetadata;if(typeof metadata!="function")return metadata;let resolved=metadata(new URL(resource2.href));return assertOAuthMetadata(resolved),resolved}function getOAuthProviderOptions(provider){return{oauthMetadata:provider.oauthMetadata,...provider.requiredScopes!==void 0&&{requiredScopes:[...provider.requiredScopes]},...provider.scopesSupported!==void 0&&{scopesSupported:[...provider.scopesSupported]},...provider.resourceName!==void 0&&{resourceName:provider.resourceName},...provider.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:provider.serviceDocumentationUrl}}}function assertVerifiedAuthInfo(authInfo){if(authInfo===null||typeof authInfo!="object"||typeof authInfo.token!="string"||authInfo.token.length===0||typeof authInfo.clientId!="string"||!Array.isArray(authInfo.scopes)||!authInfo.scopes.every(scope=>typeof scope=="string")||typeof authInfo.expiresAt!="number"||!Number.isFinite(authInfo.expiresAt)||authInfo.expiresAt<=Date.now()/1e3)throw invalidToken("Token verifier returned invalid authentication information")}function assertMappedExtra(mapped){if(mapped===null||typeof mapped!="object"||!("user"in mapped)||mapped.user===void 0||!isRecord(mapped.payload)||!Array.isArray(mapped.permissions)||!mapped.permissions.every(permission=>typeof permission=="string"))throw invalidToken("Token identity mapping must return user, payload, and string permissions")}function requireAbsoluteOrigin(value,name){let url2=parseAbsoluteUrl(value,name);if(url2.pathname!=="/"||url2.search!==""||url2.hash!==""||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute origin without a path`);return url2}function appendBasePath(origin,basePath){let resource2=new URL(origin.origin);return resource2.pathname=basePath,resource2}function normalizeBasePath(basePath){if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#"))throw new Error("basePath must be an absolute URL pathname");return normalizePathname(basePath)}function normalizePathname(pathname){if(pathname==="/")return"/";let end=pathname.length;for(;end>0&&pathname.charCodeAt(end-1)===47;)end--;return pathname.slice(0,end)}function oauthMetadata(provider,resource2){let options=getOAuthProviderOptions(provider),metadata=resolveOAuthMetadata(provider,resource2);return async(request,next)=>{let response=oauthMetadataResponse(request,{oauthMetadata:metadata,resourceServerUrl:resource2,...options.scopesSupported!==void 0&&{scopesSupported:[...options.scopesSupported]},...options.resourceName!==void 0&&{resourceName:options.resourceName},...options.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:options.serviceDocumentationUrl}});return response!==void 0?response:next()}}function authInfoFromRequest(request){return getRequestBag(request).authInfo}init_dist();import{createRemoteJWKSet,jwtVerify,errors}from"jose";var textEncoder=new TextEncoder,textDecoder=new TextDecoder("utf-8",{fatal:!0});function isBuilding(){return typeof process>"u"||process.env===void 0?!1:process.env.MCP_USE_PHASE==="build"}var DCR_CLIENT_TTL=365*24*60*60;var CIMD_MAX_BYTES=5*1024;var CIMD_CACHE_MS=300*1e3;var REFRESH_TTL=720*60*60;var UPSTREAM_TTL=1440*60*60,REMEMBER_TTL=365*24*60*60;init_policy();function resolveToolInputSchema(definition){return definition.inputSchema??definition.schema}init_dist();var META_KEY="openai/ui";function record3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function validateEntrypointInput(definition){let entrypoints=definition.view?.entrypoints;if(!entrypoints?.length)return;let schema2=resolveToolInputSchema(definition),validate=schema2?fromJsonSchema2(schema2["~standard"].jsonSchema.input({target:"draft-2020-12"}))["~standard"].validate:void 0;for(let entrypoint of entrypoints){let payloads=entrypoint.type==="file"?entrypoint.extensions.map(extension=>({file:{name:`file${extension}`,resourceUri:"host-resource://opaque-handle"}})):[{}];if(entrypoint.type==="file"&&!validate)throw new TypeError(`Tool "${definition.name}" file entrypoint requires an inputSchema accepting { file: { name, resourceUri } }.`);for(let payload of payloads){let result=validate?.(payload);if(result&&("then"in result||result.issues))throw new TypeError(`Tool "${definition.name}" ${entrypoint.type} entrypoint launch arguments do not satisfy its inputSchema.`)}}}function buildEntrypointMeta(definition){let entrypoints=definition.view?.entrypoints;if(entrypoints===void 0)return definition._meta;let existing=definition._meta?.[META_KEY];return{...definition._meta,[META_KEY]:{...record3(existing)?existing:{},entrypoints:entrypoints.map(entry=>entry.type==="file"?{type:entry.type,extensions:[...entry.extensions]}:{type:entry.type})}}}var EVENT="mcp_use_sdk_event",ENDPOINT="https://eu.i.posthog.com/i/v0/e/",TOKEN="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",CONTENT=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,RESERVED=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),runtimeId;function getRuntimeId(){return runtimeId??=crypto.randomUUID(),runtimeId}var once=new Set,pending=new Set,identities=new Map;function hasControl(value){return[...value].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})}function env(name){return typeof process>"u"?void 0:process.env?.[name]}function safeEnv(name){let value=env(name);return value!==void 0&&value.length>0&&value.length<=128&&!hasControl(value)?value:void 0}function canPersistTelemetryIdentity(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}function disabled(){if(env("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function isUsageDisabled(){return disabled()}function clean(properties){return Object.fromEntries(Object.entries(properties).filter(([key,value])=>key.length>128||hasControl(key)||key.startsWith("$")||RESERVED.has(key)||CONTENT.test(key)||value===void 0?!1:typeof value=="string"?value.length<=128&&!hasControl(value):typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value)))}async function identity(serverRoot){let projectId=safeEnv("MCP_USE_TELEMETRY_PROJECT_ID");if(projectId!==void 0)return{id:projectId,stability:"project"};if(serverRoot===void 0||!canPersistTelemetryIdentity())return{id:getRuntimeId(),stability:"process"};let existing=identities.get(serverRoot);if(existing!==void 0)return existing;let resolving=(async()=>{try{let fs=await import("fs/promises"),directory=`${serverRoot}/.mcp-use`,file=`${directory}/usage.json`,read=async()=>{try{let value=JSON.parse(await fs.readFile(file,"utf8"));if(typeof value=="object"&&value!==null&&"schemaVersion"in value&&value.schemaVersion===1&&"serverId"in value&&typeof value.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.serverId))return value.serverId}catch{}},stored=await read();if(stored!==void 0)return{id:stored,stability:"server"};await fs.mkdir(directory,{recursive:!0,mode:448});let created=crypto.randomUUID();try{return await fs.writeFile(file,`${JSON.stringify({schemaVersion:1,serverId:created})}
797
- `,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:getRuntimeId(),stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.12.0",server_id:resolvedIdentity.id,runtime_id:getRuntimeId(),identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}var BOT=/bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|headless|curl|wget|python-requests|go-http-client/i;function isLikelyBot(userAgent){return userAgent===null||BOT.test(userAgent)}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}init_dist();function schema(validateValue){return{"~standard":{version:1,vendor:"mcp-use",validate(value){try{return{value:validateValue(value)}}catch(error3){return{issues:[{message:error3 instanceof Error?error3.message:String(error3)}]}}}}}}function object3(value){if(typeof value!="object"||value===null||Array.isArray(value))throw new TypeError("params must be an object");return value}var listParams=schema(value=>{let cursor=object3(value).cursor;if(cursor!==void 0&&typeof cursor!="string")throw new TypeError("cursor must be a string");return cursor===void 0?{}:{cursor}}),uriParams=schema(value=>{let params=object3(value);if(typeof params.uri!="string")throw new TypeError("uri must be a string");if(params.cursor!==void 0&&typeof params.cursor!="string")throw new TypeError("cursor must be a string");return{uri:params.uri,...typeof params.cursor=="string"&&{cursor:params.cursor}}}),anyResult=schema(value=>object3(value));function decodePathSegment(value){try{return decodeURIComponent(value)}catch{return value}}function registerSkillsRuntime(server,snapshot){let skills=new Map(snapshot.skills.map(skill=>[skill.uri,skill]));for(let resource2 of snapshot.resources)server.registerResource(resource2.uri,resource2.uri,{title:resource2.name,mimeType:resource2.mimeType},async()=>({contents:[{uri:resource2.uri,mimeType:resource2.mimeType,...resource2.text!==void 0?{text:resource2.text}:{blob:resource2.blob}}]}));server.server.setRequestHandler("skills/list",{params:listParams,result:anyResult},async()=>({skills:snapshot.skills})),server.server.setRequestHandler("skills/get",{params:uriParams,result:anyResult},async({uri})=>{let skill=skills.get(uri);if(skill===void 0)throw new ProtocolError(INVALID_PARAMS,`Unknown skill: ${uri}`);return{skill}}),server.server.setRequestHandler("resources/directory/read",{params:uriParams,result:anyResult},async({uri})=>{let normalized=uri.replace(/\/$/,""),knownDirectories=new Set(snapshot.directories.map(item=>item.uri)),prefix=`${normalized}/`,children=new Map;for(let resource2 of snapshot.resources){if(!resource2.uri.startsWith(prefix))continue;let remainder=resource2.uri.slice(prefix.length),[name]=remainder.split("/");if(name===void 0||name==="")continue;let childUri=`${normalized}/${name}`;children.set(childUri,{uri:childUri,name:decodePathSegment(name),mimeType:remainder.includes("/")?"inode/directory":resource2.mimeType})}for(let directory of snapshot.directories){if(!directory.uri.startsWith(prefix))continue;let remainder=directory.uri.slice(prefix.length);remainder===""||remainder.includes("/")||children.set(directory.uri,{uri:directory.uri,name:directory.name,mimeType:"inode/directory"})}if(!knownDirectories.has(normalized))throw new ProtocolError(INVALID_PARAMS,`Unknown skill directory: ${uri}`);return{resources:[...children.values()].sort((left,right)=>left.uri.localeCompare(right.uri))}})}var SKILLS_EXTENSION_ID="io.modelcontextprotocol/skills",registerSkills=Symbol.for("mcp-use.registerSkills");init_origin();var registerViews=Symbol("mcp-use/registerViews");init_fetch_app();function resolveAssetUrl(assetPath,origin){if(!assetPath.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(assetPath)}`);return`${origin}${assetPath}`}function viewAssetsBasePath(basePath,viewName){return`${pathUnderBase(basePath,`_mcp-use/views/${viewName}`)}/`}function resolveExternalAssetUrl(assetPath,assetsBase,basePath,viewName){return assetPath.startsWith("http://")||assetPath.startsWith("https://")||assetPath.startsWith("data:")?assetPath:assetPath.startsWith("/")?resolveAssetUrl(assetPath,assetsBase):`${assetsBase}${viewAssetsBasePath(basePath,viewName)}${assetPath.replace(/^\/+/,"")}`}function resolvePublicBase(assetsBase,basePath){return`${assetsBase}${pathUnderBase(basePath,"_mcp-use/public")}/`}function escapeInlineScript(code){return code.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function escapeInlineStyle(css2){return css2.replaceAll(/<\/style/gi,"<\\/style")}function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var VIEW_BOOTSTRAP_STYLE=`<style>
789
+ `)}function slugifyToolName(value){return value.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function createToolInputSchema(spec,operation,inputBindings){let properties={},required2=[];for(let{parameter,inputName}of inputBindings.parameters){let parameterSchema=transformSchema(spec,parameter.schema??{});properties[inputName]={...parameterSchema,description:parameter.description??`${parameter.in} parameter`},(parameter.required||parameter.in==="path")&&required2.push(inputName)}let bodySchema=getJsonRequestBodySchema(operation.requestBody);bodySchema!==void 0&&inputBindings.bodyInputName!==void 0&&(properties[inputBindings.bodyInputName]=transformSchema(spec,bodySchema),operation.requestBody?.required&&required2.push(inputBindings.bodyInputName));let definitions=createSchemaDefinitions(spec),schema2={type:"object",properties,additionalProperties:!1,...required2.length>0&&{required:required2},...definitions!==void 0&&{$defs:definitions}};return fromJsonSchema2(schema2)}function createInputBindings(operation){let parameters=operation.parameters.filter(parameter=>parameter.in!=="cookie"),bodyInputName=getJsonRequestBodySchema(operation.requestBody)===void 0?void 0:"body",nameCounts=new Map;for(let parameter of parameters)nameCounts.set(parameter.name,(nameCounts.get(parameter.name)??0)+1);let usedNames=new Set(bodyInputName===void 0?[]:[bodyInputName]);return{parameters:parameters.map(parameter=>{let preferredName=(nameCounts.get(parameter.name)??0)>1||parameter.name===bodyInputName?`${parameter.name}_${parameter.in}`:parameter.name;return{parameter,inputName:claimInputName(preferredName,usedNames)}}),...bodyInputName!==void 0&&{bodyInputName}}}function claimInputName(preferredName,usedNames){let inputName=preferredName,suffix=2;for(;usedNames.has(inputName);)inputName=`${preferredName}_${suffix}`,suffix+=1;return usedNames.add(inputName),inputName}function createSchemaDefinitions(spec){let schemas=readRecord(spec.components?.schemas);if(schemas===void 0)return;let definitions={};for(let[name,schema2]of Object.entries(schemas))definitions[name]=transformSchemaNode(spec,schema2,new Set);return definitions}function transformSchema(spec,schema2){let transformed=transformSchemaNode(spec,schema2,new Set);return readRecord(transformed)??{}}function transformSchemaNode(spec,value,resolvingRefs){if(Array.isArray(value))return value.map(item=>transformSchemaNode(spec,item,resolvingRefs));let object5=readRecord(value);if(object5===void 0)return value;let ref=typeof object5.$ref=="string"?object5.$ref:void 0,siblings={};for(let[key,child]of Object.entries(object5))key!=="$ref"&&(key==="nullable"&&typeof child=="boolean"||isExclusiveBoundKey(key)&&typeof child=="boolean"||(siblings[key]=transformSchemaNode(spec,child,resolvingRefs)));for(let[boundKey,exclusiveKey]of EXCLUSIVE_BOUND_KEYS)object5[exclusiveKey]===!0&&typeof object5[boundKey]=="number"&&(siblings[exclusiveKey]=object5[boundKey],delete siblings[boundKey]);let transformed=siblings;if(ref!==void 0){let schemaRef=rewriteSchemaRef(spec,ref);if(schemaRef!==void 0)transformed={$ref:schemaRef,...siblings};else if(!resolvingRefs.has(ref)){let resolved=resolveRef(spec,{$ref:ref});if(resolved!==void 0){let nextRefs=new Set(resolvingRefs);nextRefs.add(ref),transformed={...readRecord(transformSchemaNode(spec,resolved,nextRefs))??{},...siblings}}}}return object5.nullable===!0?{anyOf:[transformed,{type:"null"}]}:transformed}var EXCLUSIVE_BOUND_KEYS=[["minimum","exclusiveMinimum"],["maximum","exclusiveMaximum"]];function isExclusiveBoundKey(key){return key==="exclusiveMinimum"||key==="exclusiveMaximum"}function rewriteSchemaRef(spec,ref){let prefix="#/components/schemas/";if(ref.startsWith(prefix))return resolveRef(spec,{$ref:ref})===void 0?void 0:`#/$defs/${ref.slice(prefix.length)}`}function getJsonRequestBodySchema(requestBody){let content=requestBody?.content;if(content!==void 0)return content["application/json"]?.schema??content["application/*+json"]?.schema??Object.entries(content).find(([mediaType])=>mediaType.includes("+json"))?.[1].schema}async function callOpenAPIOperation(operation,params,options,inputBindings,baseUrl){let fetchImpl=options.fetch??globalThis.fetch,url2=buildUrl(operation,params,inputBindings.parameters,baseUrl),headers=buildHeaders(inputBindings.parameters,params,options),bodyInputName=inputBindings.bodyInputName,body=bodyInputName===void 0||params[bodyInputName]===void 0?void 0:JSON.stringify(params[bodyInputName]);body!==void 0&&!hasHeader(headers,"content-type")&&(headers["content-type"]="application/json");let response=await fetchImpl(url2,{method:operation.method.toUpperCase(),headers,...body!==void 0&&{body}}),contentType=response.headers.get("content-type")??"";if(!response.ok)return{content:[{type:"text",text:await response.text()}],isError:!0};if(contentType.includes("application/json")||contentType.includes("+json")){let text2=await response.text();try{let data=JSON.parse(text2);return{content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}catch{return{content:[{type:"text",text:text2}]}}}return{content:[{type:"text",text:await response.text()}]}}function buildUrl(operation,params,parameterBindings,baseUrl){let interpolatedPath=operation.path.replace(/{([^}]+)}/g,(_match,name)=>{let binding=parameterBindings.find(({parameter})=>parameter.in==="path"&&parameter.name===name);return encodeURIComponent(String(binding===void 0?"":params[binding.inputName]??""))}),url2=new URL(interpolatedPath.replace(/^\/+/,""),ensureTrailingSlash(baseUrl));for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="query")continue;let value=params[inputName];value==null||value===""||appendQueryParam(url2,parameter.name,value)}return url2.toString()}function buildHeaders(parameterBindings,params,options){let headers={...options.headers??{}};for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="header")continue;let value=params[inputName];value==null||value===""||(headers[parameter.name]=String(value))}return options.auth?.type==="bearer"&&options.auth.token&&(headers.authorization=`Bearer ${options.auth.token}`),options.auth?.type==="header"&&options.auth.value&&(headers[options.auth.name]=options.auth.value),headers}function resolveBaseUrl(options){let baseUrl=options.baseUrl??options.spec.servers?.[0]?.url;if(baseUrl===void 0||baseUrl.trim()==="")throw new Error("MCPServer.fromOpenAPI requires options.baseUrl or spec.servers[0].url");return baseUrl}function appendQueryParam(url2,name,value){if(Array.isArray(value)){for(let item of value)item!=null&&item!==""&&url2.searchParams.append(name,String(item));return}url2.searchParams.set(name,String(value))}function ensureTrailingSlash(url2){return url2.endsWith("/")?url2:`${url2}/`}function hasHeader(headers,name){return Object.keys(headers).some(headerName=>headerName.toLowerCase()===name)}function isReferenceObject(value){let object5=readRecord(value);return object5!==void 0&&typeof object5.$ref=="string"}function resolveRef(spec,value){if(!isReferenceObject(value))return value;if(!value.$ref.startsWith("#/"))return;let segments=value.$ref.slice(2).split("/").map(segment=>segment.replace(/~1/g,"/").replace(/~0/g,"~")),current=spec;for(let segment of segments){let object5=readRecord(current);if(object5===void 0||!(segment in object5))return;current=object5[segment]}return current}function readRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}init_dist();init_dist();init_fetch_app();function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isLocalhost(url2){let hostname=url2.hostname.toLowerCase();return hostname==="localhost"||hostname.endsWith(".localhost")||hostname==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(hostname)}function parseAbsoluteUrl(value,name){let url2;try{url2=new URL(value)}catch{throw new Error(`${name} must be an absolute URL`)}if(url2.origin==="null"||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute URL without credentials`);return url2}function assertSecureHttpUrl(url2,name){if(url2.protocol!=="https:"&&!(url2.protocol==="http:"&&isLocalhost(url2)))throw new Error(`${name} must use HTTPS, or HTTP for localhost`)}function assertOAuthMetadata(metadata){if(metadata===null||typeof metadata!="object"||!("issuer"in metadata)||typeof metadata.issuer!="string")throw new TypeError("oauthMetadata must include a string issuer");assertSecureHttpUrl(parseAbsoluteUrl(metadata.issuer,"oauthMetadata.issuer"),"oauthMetadata.issuer")}init_dist();function invalidToken(message,cause){let error3=new OAuthError(OAuthErrorCode.InvalidToken,message);return cause!==void 0&&(error3.cause=cause),error3}function resolveConfiguredOAuthResource(options){let provider=options.provider,basePath=normalizeBasePath(options.basePath);if(provider.resource!==void 0)return validateOAuthResource(provider.resource,basePath);if(options.mcpUrl!==void 0)return validateOAuthResource(appendBasePath(requireAbsoluteOrigin(options.mcpUrl,"MCP_URL"),basePath),basePath)}function resolveLocalOAuthResource(listenOrigin,basePath){let listenOriginUrl=requireAbsoluteOrigin(listenOrigin,"listen origin");if(!isLocalhost(listenOriginUrl))throw new Error("OAuth listen origin must be localhost or a loopback address");return validateOAuthResource(appendBasePath(listenOriginUrl,normalizeBasePath(basePath)),basePath)}function validateOAuthResource(resource2,basePath){let normalizedBasePath=normalizeBasePath(basePath),url2=parseAbsoluteUrl(resource2,"OAuth resource");if(url2.search!==""||url2.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(assertSecureHttpUrl(url2,"OAuth resource"),normalizePathname(url2.pathname)!==normalizedBasePath)throw new Error(`OAuth resource path must exactly match basePath (${normalizedBasePath})`);return url2.pathname=normalizedBasePath,url2}function wrapOAuthTokenVerifier(provider,expectedResource){let canonicalResource=normalizeResourceUrl(expectedResource),tokenVerifier=provider.createTokenVerifier(new URL(canonicalResource.href));if(tokenVerifier===null||typeof tokenVerifier!="object"||typeof tokenVerifier.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(token){let authInfo=await tokenVerifier.verifyAccessToken(token);assertVerifiedAuthInfo(authInfo),assertResourceBinding(authInfo,canonicalResource);let mapped;try{mapped=provider.mapAuthInfo(authInfo)}catch(error3){throw invalidToken("Token identity mapping failed",error3)}return assertMappedExtra(mapped),{...authInfo,scopes:[...authInfo.scopes],extra:{...authInfo.extra,...mapped}}}}}function assertResourceBinding(authInfo,expectedResource){if(authInfo.resource===void 0)throw invalidToken("Token verifier did not return a validated protected resource");if(parseTokenResource(authInfo.resource).href!==normalizeResourceUrl(expectedResource).href)throw invalidToken("Token resource does not match the protected resource")}function parseTokenResource(value){if(!(value instanceof URL))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");let resource2=value;if(!/^https?:$/.test(resource2.protocol)||resource2.username!==""||resource2.password!==""||resource2.search!==""||resource2.hash!==""||resource2.protocol==="http:"&&!isLocalhost(resource2))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return normalizeResourceUrl(resource2)}function normalizeResourceUrl(resource2){let normalized=new URL(resource2);return normalized.pathname=normalized.pathname==="/"?"/":normalized.pathname.replace(/\/+$/,""),normalized}function resolveOAuthMetadata(provider,resource2){let metadata=provider.oauthMetadata;if(typeof metadata!="function")return metadata;let resolved=metadata(new URL(resource2.href));return assertOAuthMetadata(resolved),resolved}function getOAuthProviderOptions(provider){return{oauthMetadata:provider.oauthMetadata,...provider.requiredScopes!==void 0&&{requiredScopes:[...provider.requiredScopes]},...provider.scopesSupported!==void 0&&{scopesSupported:[...provider.scopesSupported]},...provider.resourceName!==void 0&&{resourceName:provider.resourceName},...provider.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:provider.serviceDocumentationUrl}}}function assertVerifiedAuthInfo(authInfo){if(authInfo===null||typeof authInfo!="object"||typeof authInfo.token!="string"||authInfo.token.length===0||typeof authInfo.clientId!="string"||!Array.isArray(authInfo.scopes)||!authInfo.scopes.every(scope=>typeof scope=="string")||typeof authInfo.expiresAt!="number"||!Number.isFinite(authInfo.expiresAt)||authInfo.expiresAt<=Date.now()/1e3)throw invalidToken("Token verifier returned invalid authentication information")}function assertMappedExtra(mapped){if(mapped===null||typeof mapped!="object"||!("user"in mapped)||mapped.user===void 0||!isRecord(mapped.payload)||!Array.isArray(mapped.permissions)||!mapped.permissions.every(permission=>typeof permission=="string"))throw invalidToken("Token identity mapping must return user, payload, and string permissions")}function requireAbsoluteOrigin(value,name){let url2=parseAbsoluteUrl(value,name);if(url2.pathname!=="/"||url2.search!==""||url2.hash!==""||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute origin without a path`);return url2}function appendBasePath(origin,basePath){let resource2=new URL(origin.origin);return resource2.pathname=basePath,resource2}function normalizeBasePath(basePath){if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#"))throw new Error("basePath must be an absolute URL pathname");return normalizePathname(basePath)}function normalizePathname(pathname){if(pathname==="/")return"/";let end=pathname.length;for(;end>0&&pathname.charCodeAt(end-1)===47;)end--;return pathname.slice(0,end)}function oauthMetadata(provider,resource2){let options=getOAuthProviderOptions(provider),metadata=resolveOAuthMetadata(provider,resource2);return async(request,next)=>{let response=oauthMetadataResponse(request,{oauthMetadata:metadata,resourceServerUrl:resource2,...options.scopesSupported!==void 0&&{scopesSupported:[...options.scopesSupported]},...options.resourceName!==void 0&&{resourceName:options.resourceName},...options.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:options.serviceDocumentationUrl}});return response!==void 0?response:next()}}function authInfoFromRequest(request){return getRequestBag(request).authInfo}init_dist();import{createRemoteJWKSet,jwtVerify,errors}from"jose";var textEncoder=new TextEncoder,textDecoder=new TextDecoder("utf-8",{fatal:!0});function isBuilding(){return typeof process>"u"||process.env===void 0?!1:process.env.MCP_USE_PHASE==="build"}var DCR_CLIENT_TTL=365*24*60*60;var CIMD_MAX_BYTES=5*1024;var CIMD_CACHE_MS=300*1e3;var REFRESH_TTL=720*60*60;var UPSTREAM_TTL=1440*60*60,REMEMBER_TTL=365*24*60*60;init_policy();function resolveToolInputSchema(definition){return definition.inputSchema??definition.schema}init_dist();var META_KEY="openai/ui";function record3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function validateEntrypointInput(definition){let entrypoints=definition.view?.entrypoints;if(!entrypoints?.length)return;let schema2=resolveToolInputSchema(definition),validate2=schema2?fromJsonSchema2(schema2["~standard"].jsonSchema.input({target:"draft-2020-12"}))["~standard"].validate:void 0;for(let entrypoint of entrypoints){let payloads=entrypoint.type==="file"?entrypoint.extensions.map(extension=>({file:{name:`file${extension}`,resourceUri:"host-resource://opaque-handle"}})):[{}];if(entrypoint.type==="file"&&!validate2)throw new TypeError(`Tool "${definition.name}" file entrypoint requires an inputSchema accepting { file: { name, resourceUri } }.`);for(let payload of payloads){let result=validate2?.(payload);if(result&&("then"in result||result.issues))throw new TypeError(`Tool "${definition.name}" ${entrypoint.type} entrypoint launch arguments do not satisfy its inputSchema.`)}}}function buildEntrypointMeta(definition){let entrypoints=definition.view?.entrypoints;if(entrypoints===void 0)return definition._meta;let existing=definition._meta?.[META_KEY];return{...definition._meta,[META_KEY]:{...record3(existing)?existing:{},entrypoints:entrypoints.map(entry=>entry.type==="file"?{type:entry.type,extensions:[...entry.extensions]}:{type:entry.type})}}}var EVENT="mcp_use_sdk_event",ENDPOINT="https://eu.i.posthog.com/i/v0/e/",TOKEN="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",CONTENT=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,RESERVED=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),runtimeId;function getRuntimeId(){return runtimeId??=crypto.randomUUID(),runtimeId}var once=new Set,pending=new Set,identities=new Map;function hasControl(value){return[...value].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})}function env(name){return typeof process>"u"?void 0:process.env?.[name]}function safeEnv(name){let value=env(name);return value!==void 0&&value.length>0&&value.length<=128&&!hasControl(value)?value:void 0}function canPersistTelemetryIdentity(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}function disabled(){if(env("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function isUsageDisabled(){return disabled()}function clean(properties){return Object.fromEntries(Object.entries(properties).filter(([key,value])=>key.length>128||hasControl(key)||key.startsWith("$")||RESERVED.has(key)||CONTENT.test(key)||value===void 0?!1:typeof value=="string"?value.length<=128&&!hasControl(value):typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value)))}async function identity(serverRoot){let projectId=safeEnv("MCP_USE_TELEMETRY_PROJECT_ID");if(projectId!==void 0)return{id:projectId,stability:"project"};if(serverRoot===void 0||!canPersistTelemetryIdentity())return{id:getRuntimeId(),stability:"process"};let existing=identities.get(serverRoot);if(existing!==void 0)return existing;let resolving=(async()=>{try{let fs=await import("fs/promises"),directory=`${serverRoot}/.mcp-use`,file=`${directory}/usage.json`,read=async()=>{try{let value=JSON.parse(await fs.readFile(file,"utf8"));if(typeof value=="object"&&value!==null&&"schemaVersion"in value&&value.schemaVersion===1&&"serverId"in value&&typeof value.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.serverId))return value.serverId}catch{}},stored=await read();if(stored!==void 0)return{id:stored,stability:"server"};await fs.mkdir(directory,{recursive:!0,mode:448});let created=crypto.randomUUID();try{return await fs.writeFile(file,`${JSON.stringify({schemaVersion:1,serverId:created})}
790
+ `,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:getRuntimeId(),stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.12.1",server_id:resolvedIdentity.id,runtime_id:getRuntimeId(),identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}var BOT=/bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|headless|curl|wget|python-requests|go-http-client/i;function isLikelyBot(userAgent){return userAgent===null||BOT.test(userAgent)}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}init_dist();function schema(validateValue){return{"~standard":{version:1,vendor:"mcp-use",validate(value){try{return{value:validateValue(value)}}catch(error3){return{issues:[{message:error3 instanceof Error?error3.message:String(error3)}]}}}}}}function object3(value){if(typeof value!="object"||value===null||Array.isArray(value))throw new TypeError("params must be an object");return value}var listParams=schema(value=>{let cursor=object3(value).cursor;if(cursor!==void 0&&typeof cursor!="string")throw new TypeError("cursor must be a string");return cursor===void 0?{}:{cursor}}),uriParams=schema(value=>{let params=object3(value);if(typeof params.uri!="string")throw new TypeError("uri must be a string");if(params.cursor!==void 0&&typeof params.cursor!="string")throw new TypeError("cursor must be a string");return{uri:params.uri,...typeof params.cursor=="string"&&{cursor:params.cursor}}}),anyResult=schema(value=>object3(value));function decodePathSegment(value){try{return decodeURIComponent(value)}catch{return value}}function registerSkillsRuntime(server,snapshot){let skills=new Map(snapshot.skills.map(skill=>[skill.uri,skill]));for(let resource2 of snapshot.resources)server.registerResource(resource2.uri,resource2.uri,{title:resource2.name,mimeType:resource2.mimeType},async()=>({contents:[{uri:resource2.uri,mimeType:resource2.mimeType,...resource2.text!==void 0?{text:resource2.text}:{blob:resource2.blob}}]}));server.server.setRequestHandler("skills/list",{params:listParams,result:anyResult},async()=>({skills:snapshot.skills})),server.server.setRequestHandler("skills/get",{params:uriParams,result:anyResult},async({uri})=>{let skill=skills.get(uri);if(skill===void 0)throw new ProtocolError(INVALID_PARAMS,`Unknown skill: ${uri}`);return{skill}}),server.server.setRequestHandler("resources/directory/read",{params:uriParams,result:anyResult},async({uri})=>{let normalized=uri.replace(/\/$/,""),knownDirectories=new Set(snapshot.directories.map(item=>item.uri)),prefix=`${normalized}/`,children=new Map;for(let resource2 of snapshot.resources){if(!resource2.uri.startsWith(prefix))continue;let remainder=resource2.uri.slice(prefix.length),[name]=remainder.split("/");if(name===void 0||name==="")continue;let childUri=`${normalized}/${name}`;children.set(childUri,{uri:childUri,name:decodePathSegment(name),mimeType:remainder.includes("/")?"inode/directory":resource2.mimeType})}for(let directory of snapshot.directories){if(!directory.uri.startsWith(prefix))continue;let remainder=directory.uri.slice(prefix.length);remainder===""||remainder.includes("/")||children.set(directory.uri,{uri:directory.uri,name:directory.name,mimeType:"inode/directory"})}if(!knownDirectories.has(normalized))throw new ProtocolError(INVALID_PARAMS,`Unknown skill directory: ${uri}`);return{resources:[...children.values()].sort((left,right)=>left.uri.localeCompare(right.uri))}})}var SKILLS_EXTENSION_ID="io.modelcontextprotocol/skills",registerSkills=Symbol.for("mcp-use.registerSkills");init_origin();var registerViews=Symbol("mcp-use/registerViews");init_fetch_app();function resolveAssetUrl(assetPath,origin){if(!assetPath.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(assetPath)}`);return`${origin}${assetPath}`}function viewAssetsBasePath(basePath,viewName){return`${pathUnderBase(basePath,`_mcp-use/views/${viewName}`)}/`}function resolveExternalAssetUrl(assetPath,assetsBase,basePath,viewName){return assetPath.startsWith("http://")||assetPath.startsWith("https://")||assetPath.startsWith("data:")?assetPath:assetPath.startsWith("/")?resolveAssetUrl(assetPath,assetsBase):`${assetsBase}${viewAssetsBasePath(basePath,viewName)}${assetPath.replace(/^\/+/,"")}`}function resolvePublicBase(assetsBase,basePath){return`${assetsBase}${pathUnderBase(basePath,"_mcp-use/public")}/`}function escapeInlineScript(code){return code.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function escapeInlineStyle(css2){return css2.replaceAll(/<\/style/gi,"<\\/style")}function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var VIEW_BOOTSTRAP_STYLE=`<style>
798
791
  html,body,#root{background:transparent}
799
792
  html,body{margin:0}
800
793
  #root[data-mcp-use-loading]{display:flex;min-height:100vh;align-items:center;justify-content:center;flex-direction:column;gap:10px;color:rgba(127,127,127,.9)}