konjir 0.0.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/konjir.mjs ADDED
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire}from"node:module";var __defProp=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:(newValue)=>all[name]=()=>newValue})};var __require=createRequire(import.meta.url);var{create:__create,defineProperty:__defProp2,getOwnPropertyDescriptor:__getOwnPropDesc,getOwnPropertyNames:__getOwnPropNames,getPrototypeOf:__getProtoOf}=Object,__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});if(symbols)__defProp2(target,Symbol.toStringTag,{value:"Module"});return target},__copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(var keys=__getOwnPropNames(from),i=0,n=keys.length,key;i<n;i++)if(key=keys[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));var 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 declares2019Dialect($schema){return typeof $schema==="string"&&DRAFT_2019_09_URIS.has($schema.replace(/#$/,""))}function declaredDialect(schema,remedy){if(!("$schema"in schema)||typeof schema.$schema!=="string")return"2020-12";let declared=schema.$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 Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`)}var exports_util={};__export(exports_util,{unwrapMessage:()=>unwrapMessage,uint8ArrayToHex:()=>uint8ArrayToHex,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToBase64:()=>uint8ArrayToBase64,toZod:()=>toZod,stringifyPrimitive:()=>stringifyPrimitive,slugify:()=>slugify,shallowClone:()=>shallowClone,safeExtend:()=>safeExtend,required:()=>required,rawShape:()=>rawShape,randomString:()=>randomString,propertyKeyTypes:()=>propertyKeyTypes,promiseAllObject:()=>promiseAllObject,primitiveTypes:()=>primitiveTypes,prefixIssues:()=>prefixIssues,pick:()=>pick,partial:()=>partial,parsedType:()=>parsedType,own:()=>own,optionalKeys:()=>optionalKeys,omit:()=>omit,objectClone:()=>objectClone,numKeys:()=>numKeys,nullish:()=>nullish,normalizeParams:()=>normalizeParams,mergeDefs:()=>mergeDefs,merge:()=>merge,members:()=>members,jsonStringifyReplacer:()=>jsonStringifyReplacer,joinValues:()=>joinValues,issue:()=>issue,isPlainObject:()=>isPlainObject,isObject:()=>isObject,installLazyProp:()=>installLazyProp,hide:()=>hide,hexToUint8Array:()=>hexToUint8Array,getSizableOrigin:()=>getSizableOrigin,getParsedType:()=>getParsedType,getLengthableOrigin:()=>getLengthableOrigin,getEnumValues:()=>getEnumValues,getElementAtPath:()=>getElementAtPath,floatSafeRemainder:()=>floatSafeRemainder,finalizeIssue:()=>finalizeIssue,extend:()=>extend,explicitlyAborted:()=>explicitlyAborted,escapeRegex:()=>escapeRegex,esc:()=>esc,derived:()=>derived,defineLazyInternal:()=>defineLazyInternal,defineLazy:()=>defineLazy,createTransparentProxy:()=>createTransparentProxy,constantCatch:()=>constantCatch,codePointLength:()=>codePointLength,cloneDef:()=>cloneDef,clone:()=>clone,cleanRegex:()=>cleanRegex,cleanEnum:()=>cleanEnum,captureStackTrace:()=>captureStackTrace,cached:()=>cached,base64urlToUint8Array:()=>base64urlToUint8Array,base64ToUint8Array:()=>base64ToUint8Array,attachSchema:()=>attachSchema,assignProp:()=>assignProp,assertNotEqual:()=>assertNotEqual,assertNever:()=>assertNever,assertIs:()=>assertIs,assertEqual:()=>assertEqual,assert:()=>assert,allowsEval:()=>allowsEval,aborted:()=>aborted,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,Class:()=>Class,CONSTANT_CATCH:()=>CONSTANT_CATCH,BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES});function assertEqual(val){return val}function assertNotEqual(val){return val}function toZod(){return(schema)=>schema}function assertIs(_arg){}function assertNever(_x){throw 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(array,separator="|"){return array.map((val)=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){if(typeof value==="bigint")return value.toString();return value}class Cached{constructor(getter){this._getter=getter,this._value=void 0}get value(){let getter=this._getter;if(getter!==void 0)this._value=getter(),this._getter=void 0;return this._value}}function cached(getter){return new Cached(getter)}function nullish(input){return input===null||input===void 0}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);if(Math.abs(ratio-roundedRatio)<tolerance)return 0;return ratio-roundedRatio}var EVALUATING=Symbol("evaluating");function defineLazy(object,key,getter){let value=void 0;Object.defineProperty(object,key,{get(){if(value===EVALUATING)return;if(value===void 0)value=EVALUATING,value=getter();return value},set(v){Object.defineProperty(object,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(schema){return rawShape(schema._zod.def)??schema._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){if(key in target)assignProp(target,key,value);else target[key]=value}function mirrorShape(target,source,keys,wrap){let raw=sourceShape(source);for(let key of keys){let desc=Object.getOwnPropertyDescriptor(raw,key);if(!desc.enumerable)continue;if(desc.get)deferProp(target,key,()=>{let value=source._zod.def.shape[key];return wrap?wrap(value,key):value});else 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);if(!desc.enumerable)continue;if(desc.get)deferProp(target,key,()=>source[key]);else 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(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path){if(!path)return obj;return path.reduce((acc,key)=>acc?.[key],obj)}function promiseAllObject(promisesObj){let keys=Object.keys(promisesObj),promises=keys.map((key)=>promisesObj[key]);return Promise.all(promises).then((results)=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString(length=10){let str="";for(let i=0;i<length;i++)str+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];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,"")}var captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};function isObject(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}var allowsEval=cached(()=>{if(globalConfig.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0)return!0;if(typeof ctor!=="function")return!0;let prot=ctor.prototype;if(isObject(prot)===!1)return!1;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)return!1;return!0}function shallowClone(o){if(isPlainObject(o))return{...o};if(Array.isArray(o))return[...o];if(o instanceof Map)return new Map(o);if(o instanceof Set)return new Set(o);return o}function numKeys(data){let keyCount=0;for(let key in data)if(Object.prototype.hasOwnProperty.call(data,key))keyCount++;return keyCount}var 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":if(Array.isArray(data))return"array";if(data===null)return"null";if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function")return"promise";if(typeof Map<"u"&&data instanceof Map)return"map";if(typeof Set<"u"&&data instanceof Set)return"set";if(typeof Date<"u"&&data instanceof Date)return"date";if(typeof File<"u"&&data instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return 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 Error("Cannot specify both `message` and `error` params");params.error=params.message}if(delete params.message,typeof params.error==="string")return{...params,error:()=>params.error};return 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){if(typeof value==="bigint")return value.toString()+"n";if(typeof value==="string")return`"${value}"`;return`${value}`}function optionalKeys(shape){return Object.keys(shape).filter((k)=>{return shape[k]._zod.optin!==void 0&&shape[k]._zod.optout==="optional"})}var NUMBER_FORMAT_RANGES=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pick(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let newShape={};return mirrorShape(newShape,schema,maskedKeys(schema,mask)),clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function maskedKeys(schema,mask){let raw=sourceShape(schema),keys=[];for(let key of Reflect.ownKeys(mask)){if(!Object.getOwnPropertyDescriptor(raw,key)?.enumerable)throw Error(`Unrecognized key: "${String(key)}"`);if(mask[key])keys.push(key)}return keys}function omit(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let omitted=new Set(maskedKeys(schema,mask)),newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)).filter((key)=>!omitted.has(key))),clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function extend(schema,shape){if(!isPlainObject(shape))throw Error("Invalid input to extend: expected a plain object");let checks=schema._zod.def.checks;if(checks&&checks.length>0){let existingShape=sourceShape(schema);for(let key of Reflect.ownKeys(shape))if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function extended(schema,shape){let newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema))),mirrorProps(newShape,shape),newShape}function safeExtend(schema,shape){if(!isPlainObject(shape))throw Error("Invalid input to safeExtend: expected a plain object");return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function merge(a,b){if(!b?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(a._zod.def.checks?.length)throw 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(Class,schema,mask,name="partial"){let checks=schema._zod.def.checks;if(checks&&checks.length>0)throw Error(`.${name}() cannot be used on object schemas containing refinements`);let selected=mask?new Set(maskedKeys(schema,mask)):void 0,newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),Class&&((value,key)=>selected&&!selected.has(key)?value:new Class({type:"optional",innerType:value}))),clone(schema,mergeDefs(schema._zod.def,{shape:newShape,checks:[]}))}function required(Class,schema,mask){let selected=mask?new Set(maskedKeys(schema,mask)):void 0,newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),(value,key)=>selected&&!selected.has(key)?value:new Class({type:"nonoptional",innerType:value})),clone(schema,mergeDefs(schema._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 _a;return(_a=iss).path??(_a.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message==="string"?message:message?.message}function attachSchema(issues,start,inst){var _a;for(let i=start;i<issues.length;i++)(_a=issues[i]).schema??(_a.schema=inst)}function finalizeIssue(iss,ctx,config){var _a;let traits=iss.inst?._zod?.traits;if(traits?.has("$ZodType"))if(traits.has("$ZodCheck"))(_a=iss).schema??(_a.schema=iss.inst);else 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(config.customError?.(iss))??unwrapMessage(config.localeError?.(iss))??"Invalid input",full={};for(let k of Object.keys(iss)){if(k==="inst"||k==="schema"||k==="continue"||k==="input"||k==="__proto__")continue;full[k]=iss[k]}if(full.path??(full.path=[]),full.message=message,ctx?.reportInput)full.input=iss.input;return full}function getSizableOrigin(input){if(input instanceof Set)return"set";if(input instanceof Map)return"map";if(input instanceof File)return"file";return"unknown"}var highSurrogate=/[\uD800-\uDBFF]/;function codePointLength(str){let units=str.length;if(!highSurrogate.test(str))return units;let count=units;for(let i=0;i<units-1;i++)if((str.charCodeAt(i)&64512)===55296&&(str.charCodeAt(i+1)&64512)===56320)count--,i++;return count}function getLengthableOrigin(input){if(Array.isArray(input))return"array";if(typeof input==="string")return"string";return"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;if(typeof iss==="string")return{message:iss,code:"custom",input,inst};return{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>{return Number.isNaN(Number.parseInt(k,10))}).map((el)=>el[1])}function base64ToUint8Array(base64){let binaryString=atob(base64),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(base64url){let base64=base64url.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base64.length%4)%4);return base64ToUint8Array(base64+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 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("")}class Class{constructor(..._args){}}function members(proto,table){for(let key in table){let desc=Object.getOwnPropertyDescriptor(table,key);if(desc.get)Object.defineProperty(proto,key,{...desc,enumerable:!1});else 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}var installing,broke=!1,breaker={configurable:!0,get(){broke=!0;return}};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);if(broke)delete this[key];else Object.defineProperty(this,key,{configurable:!0,writable:!0,value});return 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);if(!proto)return;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})}})}var CONSTANT_CATCH="~constantCatch";function constantCatch(value){let fn=()=>value;return fn[CONSTANT_CATCH]=!0,fn}var _a,NEVER=Object.freeze({status:"aborted"}),_zodDesc={value:void 0,enumerable:!1},_E="captureStackTrace"in Error?Error:null;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,initializer,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){_zodDesc.value=new Internals(def);try{Object.defineProperty(inst,"_zod",_zodDesc)}finally{_zodDesc.value=void 0}}else if(inst._zod.traits.has(name))return;if(inst._zod.traits.add(name),initializer(inst,def),initialized){let own2=Object.getPrototypeOf(inst),ctorProto=inst._zod.constr.prototype,up=own2;while(up&&up!==ctorProto)up=Object.getPrototypeOf(up);let target=up??own2;if(!initialized.has(target))initialized.add(target),members(target,protoMembers)}let proto2=_.prototype;for(let k in proto2){if(!Object.prototype.hasOwnProperty.call(proto2,k))continue;if(!(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;if(pp)pp(inst);return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:(inst)=>{if(params?.Parent&&inst instanceof params.Parent)return!0;return inst?._zod?.traits?.has(name)}}),Object.defineProperty(_,"name",{value:name}),_}class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class $ZodEncodeError extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`);this.name="ZodEncodeError"}}(_a=globalThis).__zod_globalConfig??(_a.__zod_globalConfig={});var globalConfig=globalThis.__zod_globalConfig;function config(newConfig){if(newConfig)Object.assign(globalConfig,newConfig);return 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}var _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);if(!_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 node(obj,key,make){if(!Object.prototype.hasOwnProperty.call(obj,key))if(key==="__proto__")Object.defineProperty(obj,key,{value:make(),writable:!0,enumerable:!0,configurable:!0});else obj[key]=make();return obj[key]}function flattenError(error,mapper=(issue2)=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error.issues)if(sub.path.length>0)node(fieldErrors,sub.path[0],()=>[]).push(mapper(sub));else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error,mapper=(issue2)=>issue2.message){let fieldErrors={_errors:[]},processError=(error2,path=[])=>{for(let issue2 of error2.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;while(i<fullpath.length){let el=fullpath[i],terminal=i===fullpath.length-1;if(el==="_errors"){if(terminal)curr._errors.push(mapper(issue2));i++;continue}if(!Object.prototype.hasOwnProperty.call(curr,el))Object.defineProperty(curr,el,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let node2=curr[el];if(terminal)node2._errors.push(mapper(issue2));curr=node2,i++}}}};return processError(error),fieldErrors}function finalizeParams(callee,params){return{callee:params?.callee??callee,Err:params?.Err}}var _parse=(_Err)=>{let fn=(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._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};var _parseAsync=(_Err)=>{let fn=async(schema,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;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};var _safeParse=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._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}};function failure(Err,issues,ctx){let error;return{success:!1,get error(){if(!error)error=new Err(issues.map((iss)=>finalizeIssue(iss,ctx,config()))),issues=void 0,ctx=void 0;return error},set error(e){error=e,issues=void 0,ctx=void 0}}}var _safeParseAsync=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length?failure(_Err,result.issues,ctx):{success:!0,data:result.value}};var COMPILE_INVALID=Symbol.for("zod.compile.invalid"),COMPILE_FALLBACK=Symbol.for("zod.compile.fallback"),validate=(schema,value,_ctx)=>{let validator=schema._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(schema,value,_ctx)};function validateFallback(schema,value,_ctx){let ctx=_ctx?{..._ctx,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},fallbackRun=schema._zod.bag.fallbackRun,result;if(fallbackRun)ctx[COMPILE_FALLBACK]=!0,result=fallbackRun({value,issues:[]},ctx);else result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length===0}var validateAsync=async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length===0},_encode=(_Err)=>{let parse=_parse(_Err),fn=(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return parse(schema,value,ctx,finalizeParams(fn,_params))};return fn};var _decode=(_Err)=>{let parse=_parse(_Err),fn=(schema,value,_ctx,_params)=>{return parse(schema,value,_ctx,finalizeParams(fn,_params))};return fn};var _encodeAsync=(_Err)=>{let parseAsync=_parseAsync(_Err),fn=async(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return await parseAsync(schema,value,ctx,finalizeParams(fn,_params))};return fn};var _decodeAsync=(_Err)=>{let parseAsync=_parseAsync(_Err),fn=async(schema,value,_ctx,_params)=>{return await parseAsync(schema,value,_ctx,finalizeParams(fn,_params))};return fn};var _safeEncode=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)};var _safeDecode=(_Err)=>(schema,value,_ctx)=>{return _safeParse(_Err)(schema,value,_ctx)};var _safeEncodeAsync=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)};var _safeDecodeAsync=(_Err)=>async(schema,value,_ctx)=>{return _safeParseAsync(_Err)(schema,value,_ctx)};var 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}$/;function nanoidOfLength(length){return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`)}var duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var 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=(version)=>{if(!version)return/^([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)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var 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,}$/;var _emoji="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function emoji(){return new RegExp(_emoji,"u")}var 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}|:))$/;var 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})?$/;var httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/;var 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])))";function anchor(source){return new RegExp(`^${source}$`)}var date=anchor(dateSource);function timeSource(args){return typeof args.precision==="number"?args.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":args.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${args.precision}}`:args.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){let opts=["Z"];if(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 anyString=/^[\s\S]{0,}$/;var bigint=/^-?\d+n?$/,integer=/^-?\d+$/,number=/^-?\d+(?:\.\d+)?$/,boolean=/^(?:true|false)$/i,_null=/^null$/i;var lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/;var $ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a2;inst._zod??(inst._zod={}),inst._zod.def=def,(_a2=inst._zod).onattach??(_a2.onattach=[])});var _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)=>{if(def.inclusive?payload.value<=def.value:payload.value<def.value)return;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)=>{if(def.inclusive?payload.value>=def.value:payload.value>def.value)return;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 Error("Cannot mix number and bigint in multiple_of check.");if(typeof payload.value==="bigint"?def.value!==BigInt(0)&&payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)return;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)){if(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});else 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}}if(input<minimum)payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort});if(input>maximum)payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}});var $ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a2;$ZodCheck.init(inst,def),(_a2=inst._zod.def).when??(_a2.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 _a2;$ZodCheck.init(inst,def),(_a2=inst._zod.def).when??(_a2.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 _a2;$ZodCheck.init(inst,def),(_a2=inst._zod.def).when??(_a2.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 _a2,_b;if($ZodCheck.init(inst,def),def.pattern)(_a2=inst._zod).check??(_a2.check=(payload)=>{if(def.pattern.lastIndex=0,def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})});else(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=(payload)=>{if(def.pattern.lastIndex=0,def.pattern.test(payload.value))return;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)=>{if(payload.value.includes(def.includes,def.position))return;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)=>{if(payload.value.startsWith(def.prefix))return;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)=>{if(payload.value.endsWith(def.suffix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}});var $ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=(payload)=>{payload.value=def.tx(payload.value)}});class Doc{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(`
3
+ `).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(", ")}) {
4
+ ${content.join(`
5
+ `)}
6
+ };`)(...Object.values(this.closed))}}var version={major:4,minor:6,patch:5};var $ZodType=$constructor("$ZodType",(inst,def)=>{var _a2;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)(_a2=inst._zod).deferred??(_a2.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))continue;if(!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()=>{if(await _,payload.issues.length===currLen)return;if(attachSchema(payload.issues,currLen,inst),!isAborted)isAborted=aborted(payload,currLen)});else{if(payload.issues.length===currLen)continue;if(attachSchema(payload.issues,currLen,inst),!isAborted)isAborted=aborted(payload,currLen)}}if(asyncResult)return asyncResult.then(()=>{return payload});return 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});if(canary instanceof Promise)return canary.then((canary2)=>{return handleCanaryResult(canary2,payload,ctx)});return 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};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}}var $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(_2){}if(typeof payload.value==="string")return payload;return 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 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;function canParseURL(input){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(input);return new URL(input),!0}catch{return!1}}function validateURL(trimmed,def){if(!("normalize"in def)&&!("hostname"in def)&&!("protocol"in def))return canParseURL(trimmed)||URL_UNPARSEABLE;return 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}}var asciiTabOrNewline=/[\t\n\r]/g;function stripTabAndNewline(value){return value.replace(asciiTabOrNewline,"")}function urlHostnameOk(url,hostname){return hostname.lastIndex=0,hostname.test(url.hostname)}function urlProtocolOk(url,protocol){return protocol.lastIndex=0,protocol.test(url.protocol.endsWith(":")?url.protocol.slice(0,-1):url.protocol)}var $ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=(payload)=>{try{let trimmed=payload.value.trim(),url=validateURL(trimmed,def);if(url===URL_BAD_FORMAT){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:payload.value,inst,continue:!def.abort});return}if(url===URL_UNPARSEABLE){payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort});return}if(url===!0){payload.value=stripTabAndNewline(trimmed);return}if(def.hostname&&!urlHostnameOk(url,def.hostname))payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort});if(def.protocol&&!urlProtocolOk(url,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?url.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 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:.]+$/;function isValidIPv6(value){if(!ipv6Alphabet.test(value))return!1;return canParseURL(`http://[${value}]`)}var $ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6),$ZodStringFormat.init(inst,def),inst._zod.check=(payload)=>{if(!isValidIPv6(payload.value))payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}});var $ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4),$ZodStringFormat.init(inst,def)});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);if(`${prefixNum}`!==prefix)return!1;if(prefixNum<0||prefixNum>128)return!1;return isValidIPv6(address)}var $ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6),$ZodStringFormat.init(inst,def),inst._zod.check=(payload)=>{if(!isValidCIDRv6(payload.value))payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}});function isValidBase64(data){if(data==="")return!0;if(/\s/.test(data))return!1;if(data.length%4!==0)return!1;try{return atob(data),!0}catch{return!1}}var 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)=>{if(isValidBase64(payload.value))return;payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}}),base64urlCharset=/^[A-Za-z0-9_-]*$/;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)}var $ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64urlCharset),$ZodStringFormat.init(inst,def),inst._zod.check=(payload)=>{if(isValidBase64URL(payload.value))return;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)});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));if("typ"in parsedHeader&&parsedHeader?.typ!=="JWT")return!1;if(!parsedHeader.alg)return!1;if(algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))return!1;return!0}catch{return!1}}var $ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=(payload)=>{if(isValidJWT(payload.value,def.alg))return;payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}});var $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)?String(input):void 0: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=Boolean(payload.value)}catch(_){}let input=payload.value;if(typeof input==="boolean")return payload;return 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(_){}if(typeof payload.value==="bigint")return payload;return payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst}),payload}});var $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;if(input===null)return payload;return 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)=>{return payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst}),payload}});var $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(_err){}let input=payload.value,isDate=input instanceof Date;if(isDate&&!Number.isNaN(input.getTime()))return payload;return payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst}),payload}});function handleArrayResult(result,final,index){if(result.issues.length)final.issues.push(...prefixIssues(index,result.issues));final.value[index]=result.value}var $ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def);let memo=globalConfig.memoizer;memo?.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=memo?memo.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}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});function handlePropertyResult(result,final,key,input,optin,optout){let isPresent=key in input,isOptionalOut=optout==="optional";if(!isPresent&&isOptionalOut&&optin==="optional")return;if(result.issues.length){if(optin!==void 0&&isOptionalOut&&!isPresent)return;final.issues.push(...prefixIssues(key,result.issues))}if(!isPresent&&optin===void 0){if(!result.issues.length)final.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[key]});return}if(result.value===void 0){if(isPresent||optin==="defaulted"&&!isOptionalOut)final.value[key]=void 0}else final.value[key]=result.value}var NO_SYMBOL_KEYS=[];function normalizeDef(def){let keys=Object.keys(def.shape),ownSymbols=Object.getOwnPropertySymbols(def.shape),symbolKeys=ownSymbols.length?ownSymbols:NO_SYMBOL_KEYS,allKeys=symbolKeys.length?[...keys,...symbolKeys]:keys;for(let k of allKeys)if(!def.shape?.[k]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(k)}": expected a Zod schema`);let okeys=optionalKeys(def.shape);return{...def,allKeys,symbolKeys,keySet:new Set(keys),numKeys:keys.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__"){if(t==="never")unrecognized.push(key);continue}if(t==="never"){unrecognized.push(key);continue}let r=_catchall.run({value:input[key],issues:[]},ctx);if(r instanceof Promise)proms.push(r.then((r2)=>handlePropertyResult(r2,payload,key,input,optin,optout)));else handlePropertyResult(r,payload,key,input,optin,optout)}if(unrecognized.length)payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst,continue:!0});if(!proms.length)return payload;return Promise.all(proms).then(()=>{return payload})}var $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){if(!Object.prototype.hasOwnProperty.call(propValues,key))assignProp(propValues,key,new Set);for(let v of field.values)propValues[key].add(v);if(field.optin!==void 0)propValues[key].add(void 0)}}return propValues});let isObject2=isObject,catchall=def.catchall,value,memo=globalConfig.memoizer;memo?.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=memo?memo.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);if(r instanceof Promise)proms.push(r.then((r2)=>handlePropertyResult(r2,payload,key,input,optin,optout)));else handlePropertyResult(r,payload,key,input,optin,optout)}if(!catchall)return proms.length?Promise.all(proms).then(()=>payload):payload;return handleCatchall(proms,input,payload,ctx,_normalized.value,inst,abortEarly===!0)}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);let superParse=inst._zod.parse,_normalized=cached(()=>normalizeDef(def)),memo=globalConfig.memoizer,generateFastpass=(shape)=>{let normalized=_normalized.value,syms=normalized.symbolKeys,doc=new Doc(["payload","ctx"],{shape,inst,memo,syms}),parseStr=(k)=>`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`,prefixStr=(id,k)=>`
7
+ let ${id}_ab = false;
8
+ for (let i = 0; i < ${id}.issues.length; i++) {
9
+ const iss = ${id}.issues[i];
10
+ iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
11
+ payload.issues.push(iss);
12
+ if (iss.continue !== true) ${id}_ab = true;
13
+ }
14
+ if (${id}_ab && ctx && ctx.abortEarly) {
15
+ payload.value = newResult;
16
+ return payload;
17
+ }`;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(memo?"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`,schema=shape[key],optin=schema?._zod?.optin,isOptionalIn=optin!==void 0,isOptionalOut=schema?._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(`
18
+ const ${id}_present = ${isPresent};
19
+ if (!${id}.issues.length || ${id}_present) {
20
+ if (${id}.issues.length) {${prefixStr(id,k)}
21
+ }
22
+
23
+ if (${assign}) {
24
+ newResult[${k}] = ${id}.value;
25
+ }
26
+ }
27
+
28
+ `)}else if(!isOptionalIn)doc.write(`
29
+ const ${id}_present = ${isPresent};
30
+ if (${id}.issues.length) {${prefixStr(id,k)}
31
+ }
32
+ if (!${id}_present && !${id}.issues.length) {
33
+ payload.issues.push({
34
+ code: "invalid_type",
35
+ expected: "nonoptional",
36
+ input: undefined,
37
+ path: [${k}]
38
+ });
39
+ if (ctx && ctx.abortEarly) {
40
+ payload.value = newResult;
41
+ return payload;
42
+ }
43
+ }
44
+
45
+ if (${id}_present) {
46
+ newResult[${k}] = ${id}.value;
47
+ }
48
+
49
+ `);else if(doc.write(`
50
+ if (${id}.issues.length) {${prefixStr(id,k)}
51
+ }
52
+ `),optin==="defaulted")doc.write(`newResult[${k}] = ${id}.value;`);else doc.write(`
53
+ if (${id}.value !== undefined || ${isPresent}) {
54
+ newResult[${k}] = ${id}.value;
55
+ }
56
+ `)}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;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;if(jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0){if(!fastpass)fastpass=generateFastpass(def.shape);if(payload=fastpass(payload,ctx),!catchall)return payload;return handleCatchall([],input,payload,ctx,value,inst,ctx?.abortEarly===!0)}return superParse(payload,ctx)}});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));if(nonaborted.length===1)return final.value=nonaborted[0].value,nonaborted[0];return final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map((result)=>result.issues.map((iss)=>finalizeIssue(iss,ctx,config())))}),final}var $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)));return}),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("|")})$`)}return});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)}}if(!async)return handleUnionResults(results,payload,inst,ctx);return Promise.all(results).then((results2)=>{return handleUnionResults(results2,payload,inst,ctx)})}});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 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 Error(`Duplicate discriminator value "${String(value)}"`);map.set(value,null)}else map.set(value,option)}return map}var $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 Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);if(pv[zod.def.discriminator]?.has(void 0))undefinedCount++;for(let[k,v]of Object.entries(pv)){if(!Object.prototype.hasOwnProperty.call(propValues,k))assignProp(propValues,k,new Set);for(let val of v)propValues[k].add(val)}}if(!zod.def.unionFallback&&undefinedCount>1)propValues[zod.def.discriminator]?.delete(void 0);return propValues}),def.options.forEach((option,i)=>{let propShape=rawShape(option._zod.def);if(propShape&&!Object.prototype.hasOwnProperty.call(propShape,def.discriminator))throw 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);if(opt&&(value!==void 0||ctx.direction!=="backward"))return opt._zod.run(payload,ctx);if(def.unionFallback||ctx.direction==="backward")return _super(payload,ctx);return 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);if(left instanceof Promise||right instanceof Promise)return Promise.all([left,right]).then(([left2,right2])=>{return handleIntersectionResults(payload,left2,right2)});return handleIntersectionResults(payload,left,right)}});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};if(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 keys;if(iss.code==="unrecognized_keys"&&!iss.path?.length)unrecIssue??(unrecIssue=iss),keys=iss.keys;else if(iss.code==="invalid_key"&&iss.origin==="record"&&iss.path?.length===1){let k=String(iss.path[0]);if(!keyIssues.has(k))keyIssues.set(k,iss);keys=[k]}else return!1;for(let k of keys){if(!unrecKeys.has(k))unrecKeys.set(k,{});unrecKeys.get(k)[side]=!0}return!0};for(let iss of left.issues)if(!collect(iss,"l"))result.issues.push(iss);for(let iss of right.issues)if(!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)):[];if(aggregated.length)result.issues.push({...unrecIssue,keys:aggregated});for(let k of bothKeys)if(!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 Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`)}return result.value=merged.data,result}var $ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def);let memo=globalConfig.memoizer;memo?.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=memo?memo.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 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);if(result instanceof Promise)proms.push(result.then((result2)=>{if(result2.issues.length)payload.issues.push(...prefixIssues(key,result2.issues));payload.value[outKey]=result2.value}));else{if(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);if(unrecognized&&unrecognized.length>0)payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized,continue:!0})}else{payload.value=memo?memo.alloc(inst,payload,{},ctx):{};let unrecognized;for(let key of Reflect.ownKeys(input)){if(key==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(input,key))continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw 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 Error("Async schemas not supported in object keys currently");if(retryResult.issues.length===0)keyResult=retryResult}if(keyResult.issues.length){if(def.mode==="loose")payload.value[key]=input[key];else if(values)unrecognized=unrecognized??[],unrecognized.push(key);else 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);if(result instanceof Promise)proms.push(result.then((result2)=>{if(result2.issues.length)payload.issues.push(...prefixIssues(key,result2.issues));payload.value[outKey]=result2.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[outKey]=result.value}}if(unrecognized&&unrecognized.length>0)payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized,continue:!0})}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});var $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;if(valuesSet.has(input))return payload;return 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;if(values.has(input))return payload;return payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}});var $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)=>{return payload.value=output2,payload});if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload}});function handleOptionalResult(payload,result){return payload.value=result.issues.length?void 0:result.value,payload}var $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);if(result instanceof Promise)return result.then((result2)=>handleOptionalResult(payload,result2));return 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)=>{return 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)=>{return zod.def.innerType._zod.values?new Set([...zod.def.innerType._zod.values,null]):void 0}),inst._zod.parse=(payload,ctx)=>{if(payload.value===null)return payload;return 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);if(result instanceof Promise)return result.then((result2)=>handleDefaultResult(result2,def));return handleDefaultResult(result,def)}});function handleDefaultResult(payload,def){if(payload.value===void 0)payload.value=def.defaultValue;return payload}var $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)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)payload.value=def.defaultValue;return 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);if(result instanceof Promise)return result.then((result2)=>handleNonOptionalResult(result2,inst));return handleNonOptionalResult(result,inst)}});function handleNonOptionalResult(payload,inst){if(!payload.issues.length&&payload.value===void 0)payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst});return payload}function handleCatchResult(payload,result,def,ctx){if(!result.issues.length){if(payload.value=result.value,result.memo)payload.memo=!0;return payload}return payload.value=def.catchValue({...result,value:payload.value,error:{issues:result.issues.map((iss)=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload}var $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);if(result instanceof Promise)return result.then((result2)=>handleCatchResult(payload,result2,def,ctx));return handleCatchResult(payload,result,def,ctx)}});var $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);if(right instanceof Promise)return right.then((right2)=>handlePipeResult(right2,def.in,ctx));return handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);if(left instanceof Promise)return left.then((left2)=>handlePipeResult(left2,def.out,ctx));return handlePipeResult(left,def.out,ctx)}});function handlePipeResult(left,next,ctx){if(left.issues.some((iss)=>iss.code!=="unrecognized_keys"))return left.aborted=!0,left;return next._zod.run({value:left.value,issues:left.issues},ctx)}var $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);if(result instanceof Promise)return result.then(handleReadonlyResult);return handleReadonlyResult(result)}});function handleReadonlyResult(payload){if(!payload.memo)payload.value=Object.freeze(payload.value);return payload}var $ZodLazy=$constructor("$ZodLazy",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"innerType",()=>{let d=def;if(!d._cachedInner)d._cachedInner=def.getter();return 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)=>{return inst._zod.innerType._zod.run(payload,ctx)}}),$ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>{return 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);return}});function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};if(inst._zod.def.params)_iss.params=inst._zod.def.params;payload.issues.push(issue(_iss))}}class $ZodCyclicError extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var STATE="~memo",NO_ISSUES=[];function isRef(value){return value!==null&&typeof value==="object"}function cloneIssues(issues){return issues.map((iss)=>iss.path?{...iss,path:iss.path.slice()}:{...iss})}var recursive=new WeakMap,NONE=0,ASSUMED=1,PROVEN=2;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);if(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;if(child>answer)answer=child}return answer},merge2=(answer)=>{if(answer>result)result=answer},def=inst._zod.def,kind=def.type;switch(kind){case"object":{let raw=rawShape(def);merge2(raw?shape(raw,!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")continue;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){if(answer!==ASSUMED)recursive.set(inst,answer===PROVEN);return answer}function bucketFor(state,inst){let bucket=state.buckets.get(inst);if(!bucket)bucket=new WeakMap,state.buckets.set(inst,bucket);return bucket}var handoff,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 _a2;(_a2=inst._zod).deferred??(_a2.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)};if(inst._zod.parse=wrapped,inst._zod.run===base)inst._zod.run=wrapped})},attach(inst){var _a2;let isRecursiveInst,rechecked=!1,lastCtx,lastBucket;(_a2=inst._zod).deferred??(_a2.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){if(inst._zod.parse=base,inst._zod.run===wrapped)inst._zod.run=base;return base(payload,ctx)}if(walked===PROVEN||rechecked)isRecursiveInst=!0;else rechecked=!0}let input=payload.value;if(!isRef(input))return base(payload,ctx);let state=ctx[STATE];if(!state)state={buckets:new WeakMap,backEdges:void 0},ctx[STATE]=state;let bucket;if(lastCtx===ctx)bucket=lastBucket;else bucket=bucketFor(state,inst),lastCtx=ctx,lastBucket=bucket;let hit=bucket.get(input);if(hit){if(payload.value=hit.value,hit.issues){if(hit.issues.length)payload.issues.push(...cloneIssues(hit.issues))}else payload.memo=!0,state.backEdges??(state.backEdges=new WeakSet),state.backEdges.add(hit.value);return payload}handoff=bucket;let depth=open.length,result=base(payload,ctx);handoff=void 0;let entry=open.length>depth?open.pop():void 0;if(result instanceof Promise)return result.then((r)=>{if(entry)entry.issues=r.issues.length?cloneIssues(r.issues):NO_ISSUES;return r});if(entry)entry.issues=result.issues.length?cloneIssues(result.issues):NO_ISSUES;return result};if(inst._zod.parse=wrapped,inst._zod.run===base)inst._zod.run=wrapped})}};function memoizer(){return memo}function isBackEdge(ctx,value){let backEdges=ctx[STATE]?.backEdges;return backEdges!==void 0&&isRef(value)&&backEdges.has(value)}var 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){if(type==="number"&&typeof input==="number"&&!Number.isFinite(input))return String(input);return 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":if(issue2.values.length===1)return`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;return`Invalid option: expected one of ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.exact?"exactly ":issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Too big: expected ${issue2.origin??"value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"}`;return`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);if(sizing)return`Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Invalid string: must start with "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Invalid string: must end with "${_issue.suffix}"`;if(_issue.format==="includes")return`Invalid string: must include "${_issue.includes}"`;if(_issue.format==="regex")return`Invalid string: must match pattern ${_issue.pattern}`;return`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":if(issue2.options&&Array.isArray(issue2.options)&&issue2.options.length>0)return`Invalid discriminator value. Expected ${issue2.options.map((o)=>`'${o}'`).join(" | ")}`;if(issue2.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${issue2.origin}`;default:return"Invalid input"}}};function en_default(){return{localeError:error()}}var _a2;class $ZodRegistry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema,..._meta){let meta=_meta[0];if(this._map.set(schema,meta),meta&&typeof meta==="object"&&"id"in meta)this._idmap.set(meta.id,schema);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema){let meta=this._map.get(schema);if(meta&&typeof meta==="object"&&"id"in meta)this._idmap.delete(meta.id);return this._map.delete(schema),this}get(schema){let p=schema._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}}function registry(){return new $ZodRegistry}(_a2=globalThis).__zod_globalRegistry??(_a2.__zod_globalRegistry=registry());var globalRegistry=globalThis.__zod_globalRegistry;function snapshotChecks(def){if(def.checks)def.checks=[...def.checks];return 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)=>{return payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;if(_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}function assignProps(target,...sources){for(let source of sources)for(let key of Reflect.ownKeys(source))if(Object.prototype.propertyIsEnumerable.call(source,key))assignProp(target,key,source[key]);return target}function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{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(schema,ctx,json,params,message){let result=typeof ctx.unrepresentable==="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return!1;if(result===void 0||result==="throw")throw Error(message);return Object.assign(json,result),!0}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a3;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen){if(seen.count++,_params.schemaPath.includes(schema))seen.cycle=_params.path;return seen.schema}let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result),ctx.sharedDefsExtractedFor=void 0,ctx.sharedEmitDoneFor=void 0;let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;processSchema(parent,ctx,params),ctx.seen.get(parent).isParent=!0}}let meta=ctx.metadataRegistry.get(schema);if(meta)assignProps(result.schema,meta);if(ctx.io==="input"&&isTransforming(schema))delete result.schema.examples,delete result.schema.default;if(ctx.io==="input"&&"_prefault"in result.schema)(_a3=result.schema).default??(_a3.default=result.schema._prefault);return delete result.schema._prefault,ctx.seen.get(schema).schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw 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 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);if(seen.def={...seen.schema},defId)seen.defId=defId;let schema2=seen.schema;for(let key in schema2)delete schema2[key];schema2.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
57
+
58
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==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){if(ctx.reused==="ref")extractToDef(entry)}}if(ctx.external)ctx.sharedDefsExtractedFor=ctx.external}function compactTypeUnion(schema){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!=="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type=option.type;for(let member of Array.isArray(type)?type:[type]){if(typeof member!=="string")return;if(!types.includes(member))types.push(member)}}delete schema.anyOf,schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]),UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){let extra=member.additionalProperties;if(extra===void 0||extra===!1||typeof extra!=="object"||extra===null)return null;return 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 object of objects){for(let key in object.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part=other.properties?.[key]??undeclaredConstraint(other);if(part===null||part===void 0)continue;if(!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 object.required??[])required2.add(key)}let folded={type:"object",properties};if(required2.size)folded.required=[...required2];if(objects.every((object)=>object.additionalProperties===!1))folded.additionalProperties=!1;else{let constraints=[];for(let object of objects){let constraint=undeclaredConstraint(object);if(constraint&&!constraints.some((seen)=>JSON.stringify(seen)===JSON.stringify(constraint)))constraints.push(constraint)}if(constraints.length===1)folded.additionalProperties=constraints[0];else if(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 union=unions[0],keyword=UNION_KEYS.find((k)=>Array.isArray(union[k]));if(Object.keys(union).length!==1)return;let rest=allOf.filter((m)=>m!==union),branches=union[keyword].map((branch)=>foldObjects([...rest,branch]));if(branches.some((b)=>!b))return;folded={[keyword]:branches}}if(!folded)return;delete json.allOf,assignProps(json,folded)}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=(zodSchema)=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},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"))schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema);else assignProps(schema2,refSchema);if(assignProps(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached))delete schema2[key]}if(refSchema.$ref&&refSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key]))delete schema2[key]}}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){if(schema2.$ref=parentSeen.schema.$ref,parentSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key]))delete schema2[key]}}}ctx.override({zodSchema,jsonSchema:schema2,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);if(existing)existing.push(json);else 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";else if(ctx.target==="draft-07")result.$schema="http://json-schema.org/draft-07/schema#";else if(ctx.target==="draft-04")result.$schema="http://json-schema.org/draft-04/schema#";else if(ctx.target==="openapi-3.0");if(ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw 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(schema)?.id;if(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];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;assignProp(defs,seen.defId,seen.def)}}if(ctx.external)ctx.sharedEmitDoneFor=ctx.external;if(ctx.external);else if(Object.keys(defs).length>0)if(ctx.target==="draft-2020-12")result.$defs=defs;else result.definitions=defs;try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch(_err){throw 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"){if(_schema._zod.traits.has("$ZodCodec"))return!0;return 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;if(def.rest&&isTransforming(def.rest,ctx))return!0;return!1}return!1}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{if(agg[key]===void 0||value>agg[key])agg[key]=value},narrowMax=(agg,key,value)=>{if(agg[key]===void 0||value<agg[key])agg[key]=value},narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value),narrowMax(agg,"maximum",value)},addDivisor=(agg,value)=>{if(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)=>{if(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)=>{if(setFormat(agg,def.format),def.pattern)addPattern(agg,def.pattern);if(def.format==="base64"||def.format==="base64url")agg.contentEncoding=def.format;if(def.local||def.precision===-1)agg.laxFormat=!0},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);let bag=schema._zod.bag;if(bag.minimum!==void 0)narrowMin(agg,"minimum",bag.minimum);if(bag.exclusiveMinimum!==void 0)narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum);if(bag.maximum!==void 0)narrowMax(agg,"maximum",bag.maximum);if(bag.exclusiveMaximum!==void 0)narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum);if(bag.multipleOf!==void 0)addDivisor(agg,bag.multipleOf);if(bag.format!==void 0){if(agg.format??(agg.format=bag.format),bag.format.includes("int"))agg.isInt=!0}if(bag.mime)intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var 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=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){if(json.format=formatMap[format]??format,json.format==="")delete json.format;if(format==="time"||laxFormat)delete json.format}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){let patternList=[...patterns].map(exactPattern);if(patternList.length===1)json.pattern=patternList[0].source;else if(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=(schema,ctx,_json,params)=>{let json=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);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)if(legacy)json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0;else json.exclusiveMinimum=exclusiveMinimum;else if(typeof minimum==="number")json.minimum=minimum;if(exMax)if(legacy)json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0;else json.exclusiveMaximum=exclusiveMaximum;else if(typeof maximum==="number")json.maximum=maximum;if(multipleOf){let divisors=new Set;for(let divisor of multipleOf)if(Number.isFinite(divisor)&&divisor!==0)divisors.add(Math.abs(divisor));else handleUnrepresentable(schema,ctx,json,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);let[first,...rest]=divisors;if(first!==void 0)json.multipleOf=first;if(rest.length)json.allOf=[...json.allOf??[],...rest.map((m)=>({multipleOf:m}))]}},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"BigInt cannot be represented in JSON Schema")},symbolProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0")json.type="string",json.nullable=!0,json.enum=[null];else json.type="null"},undefinedProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Undefined cannot be represented in JSON Schema")},voidProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,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=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.length===0){json.not={};return}if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values},literalProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;if(def.values.length===0){json.not={};return}let vals=[];for(let val of def.values)if(val===void 0){if(handleUnrepresentable(schema,ctx,json,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val==="bigint"){if(handleUnrepresentable(schema,ctx,json,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else vals.push(val);if(vals.length===0);else if(vals.length===1){let val=vals[0];if(json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.enum=[val];else json.const=val}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}},nanProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json,_params)=>{let _json=json,pattern=schema._zod.pattern;if(!pattern)throw Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json,_params)=>{let _json=json;_json.type="string",_json.format="binary",_json.contentEncoding="binary";let{minimum,maximum,mime}=aggregateChecks(schema);if(minimum!==void 0)_json.minLength=minimum;if(maximum!==void 0)_json.maxLength=maximum;if(!mime)return;if(mime.length===0)_json.not={};else if(mime.length===1)_json.contentMediaType=mime[0];else _json.anyOf=mime.map((m)=>({contentMediaType:m}))},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom types cannot be represented in JSON Schema")},functionProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Function types cannot be represented in JSON Schema")},transformProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Transforms cannot be represented in JSON Schema")},mapProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Map cannot be represented in JSON Schema")},setProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array",json.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){let def=schema._zod.def;if(def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform"))return inputOptin(def.out);if(def.type==="catch")return inputOptin(def.innerType);return schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema,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];if(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)requiredKeys.push(key)}if(requiredKeys.length>0)json.required=requiredKeys;if(def.catchall?._zod.def.type==="never")json.additionalProperties=!1;else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=!1}else if(def.catchall)json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive)json.oneOf=options;else json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._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=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"?"items":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;while(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;if(ctx.target==="draft-2020-12"){if(json.prefixItems=prefixItems,isClosed)json.items=!1;else if(rest)json.items=rest;if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else if(ctx.target==="openapi-3.0"){if(json.items={anyOf:prefixItems},rest)json.items.anyOf.push(rest);if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else{if(json.items=prefixItems,isClosed)json.additionalItems=!1;else if(rest)json.additionalItems=rest;if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}let{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum};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));if(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;if(rest.enum)rest.enum=rest.enum.map((v)=>typeof v==="number"?String(v):v);else if(typeof rest.const==="number")rest.const=String(rest.const);if(!numericType)return rest;if(rest.type="string",!values)rest.pattern=(types.includes("number")?number:integer).source;return rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())if(entry.def&&!bySchema.has(entry.schema))bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);if(rewritten!==names)rewrites.set(names,rewritten)}if(!rewrites.size)return;for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);if(rewritten)carrier.propertyNames=rewritten}}var recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._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 pending=pendingRecords.get(ctx);if(!pending)pending=[],pendingRecords.set(ctx,pending),ctx.deferred.push(()=>rewriteKeyNames(ctx));pending.push(schema)}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");if(validKeyValues.length>0)json.required=validKeyValues.map(String)}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0")seen.ref=def.innerType,json.nullable=!0;else json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=!1,serialized=JSON.stringify(value,(_,val)=>{if(typeof val!=="bigint")return val;return unrepresentable=!0,null});if(!unrepresentable)return JSON.parse(serialized);return handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT}var defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json.default=value},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json._prefault=value},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._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(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);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};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[_,schema]=entry;processSchema(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),assignProp(schemas,key,finalize(ctx2,schema))}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 _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);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 initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let proto=Object.getPrototypeOf(inst);if(_installedErrorProtos.has(proto))return;_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}})};var ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error});var parse2=_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(){if(!globalConfig.localeError)config(en_default())}function _ensureDefaultMemoizer(){if(!globalConfig.memoizer)config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>{return _ensureDefaultLocale(),$ZodType.init(inst,def),inst.def=def,inst.type=def.type,inst},{check(...chks){let def=this.def;return this.clone(exports_util.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 exports_util.hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set "~standard"(value){exports_util.own(this,"~standard",value)},parse:function _parse2(data,params){return parse2(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){exports_util.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)},exports_util.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))}});function string2(params){return _string(ZodString,params)}var 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)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});var 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},exports_util.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}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params)},exports_util.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))}}));var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});function never(params){return _never(ZodNever,params)}var 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))},exports_util.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}},{}));var 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}});function array(element,params){return _array(ZodArray,element,params)}var 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),exports_util.installLazyProp(inst,"shape",(self)=>self._zod.def.shape,!1)},{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(exports_util.mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(exports_util.mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(exports_util.mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(exports_util.mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(exports_util.mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return exports_util.extend(this,incoming)},safeExtend(incoming){return exports_util.safeExtend(this,incoming)},merge(other){return exports_util.merge(this,other)},pick(mask){return exports_util.pick(this,mask)},omit(mask){return exports_util.omit(this,mask)},partial(...args){return exports_util.partial(ZodOptional,this,args[0])},exactPartial(...args){return exports_util.partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return exports_util.required(ZodNonOptional,this,args[0])}});function object(shape,params){let def={type:"object",shape:shape??{},...exports_util.normalizeParams(params)};return new ZodObject(def)}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...exports_util.normalizeParams(params)})}var 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});function union(options,params){return new ZodUnion({type:"union",options,...exports_util.normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...exports_util.normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var 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});function record(keyType,valueType,params){if(!valueType||!valueType._zod)return new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...exports_util.normalizeParams(valueType)});return new ZodRecord({type:"record",keyType,valueType,...exports_util.normalizeParams(params)})}var 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 keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})}});function _enum(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}var 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 Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...exports_util.normalizeParams(params)})}var 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(exports_util.issue(issue2,payload.value,def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;if(_issue.code??(_issue.code="custom"),!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=inst),payload.issues.push(exports_util.issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output2)=>{return payload.value=output2,payload});return payload.value=output,payload}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var 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});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var 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});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var 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});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}var 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});function _default(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}var 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});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}var 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});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...exports_util.normalizeParams(params)})}var 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});function _catch(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:exports_util.constantCatch(catchValue)})}var 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});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var 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});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var 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()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var 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"};var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind2){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));var exports_iso={};__export(exports_iso,{time:()=>time2,duration:()=>duration2,datetime:()=>datetime2,date:()=>date2,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate});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 exports_coerce={};__export(exports_coerce,{string:()=>string3,number:()=>number3,date:()=>date3,boolean:()=>boolean3,bigint:()=>bigint2});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 LATEST_PROTOCOL_VERSION="2025-11-25";var 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";var JSONRPC_VERSION="2.0";var 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)=>{if(value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).length===0)return{form:{}};return 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:exports_iso.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:exports_coerce.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(()=>{return})),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 BRANDS=Symbol.for("mcp.sdk.errorBrands");function stampErrorBrands(instance,ctor){let brands=new Set,current=ctor;while(typeof current==="function"){let brand=current.mcpBrand;if(Object.prototype.hasOwnProperty.call(current,"mcpBrand")&&typeof brand==="string")brands.add(brand);current=Object.getPrototypeOf(current)}if(brands.size===0)return;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)}var 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 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};if(this.errorUri)response.error_uri=this.errorUri;return 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 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}};function resourceUrlFromServerUrl(url2){let resourceURL=typeof url2==="string"?new URL(url2):new URL(url2.href);return resourceURL.hash="",resourceURL}function withoutIssuer(body){if(typeof body!=="object"||body===null||Array.isArray(body))return body;let copy={...body};return delete copy.issuer,copy}function checkResourceAllowed({requestedResource,configuredResource}){let requested=typeof requestedResource==="string"?new URL(requestedResource):new URL(requestedResource.href),configured=typeof configuredResource==="string"?new URL(configuredResource):new URL(configuredResource.href);if(requested.origin!==configured.origin)return!1;if(requested.pathname.length<configured.pathname.length)return!1;let requestedPath=requested.pathname.endsWith("/")?requested.pathname:requested.pathname+"/",configuredPath=configured.pathname.endsWith("/")?configured.pathname:configured.pathname+"/";return requestedPath.startsWith(configuredPath)}var FIRST_MODERN_PROTOCOL_VERSION="2026-07-28",SUPPORTED_MODERN_PROTOCOL_VERSIONS=[FIRST_MODERN_PROTOCOL_VERSION];function isModernProtocolVersion(version2){return version2>=FIRST_MODERN_PROTOCOL_VERSION}function legacyProtocolVersions(versions2){return versions2.filter((version2)=>!isModernProtocolVersion(version2))}function modernProtocolVersions(versions2){return versions2.filter((version2)=>isModernProtocolVersion(version2))}function appendTextFallbackForNonObject(result){let sc=result.structuredContent;if(sc===void 0)return result;if(!(typeof sc!=="object"||sc===null||Array.isArray(sc)))return result;if(result.content?.some((c)=>c.type==="text")??!1)return result;return{...result,content:[...result.content??[],{type:"text",text:JSON.stringify(sc)}]}}var TOOL_RESULT_FOREIGN_FAMILY_KEYS=["task","inputRequests","requestState"];function normalizeContentlessToolResult(value){if(value===null||typeof value!=="object"||Array.isArray(value)||value.content!==void 0||TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key)=>(key in value)))return value;return{...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)=>{if(value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).length===0)return{form:{}};return 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:exports_iso.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)return;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}' — another result family cannot default into an empty tools/call success`});return}}).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1)}}var memo$1;function buildSchemas2025(){return memo$1??=build$1()}function isNonObjectJsonSchemaRoot(json){return json.type!=="object"}var REF_REWRITE_DATA_POSITION_KEYS=new Set(["const","enum","default","examples"]),REF_REWRITE_NAME_MAP_KEYS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);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")return node2;if(!parentIsNameMap&&establishesNewBase(node2.$id))return node2;let out={},convertedRecursion=!1;for(let[k,v]of Object.entries(node2))if(parentIsNameMap)out[k]=rewriteRefs(v,!1);else if((k==="$ref"||k==="$dynamicRef")&&typeof v==="string")out[k]=v==="#"?"#/properties/result":v.startsWith("#/")?`#/properties/result${v.slice(1)}`:v;else if(k==="$recursiveRef"&&v==="#"&&convertRecursiveRefs)convertedRecursion=!0;else if(REF_REWRITE_DATA_POSITION_KEYS.has(k))out[k]=v;else if(REF_REWRITE_NAME_MAP_KEYS.has(k))out[k]=rewriteRefs(v,!0);else out[k]=rewriteRefs(v,!1);if(convertedRecursion)if("$ref"in out)out.allOf=[...Array.isArray(out.allOf)?out.allOf:[],{$ref:"#/properties/result"}];else out.$ref="#/properties/result";return out};return{...$schema!==void 0&&{$schema},type:"object",properties:{result:rewriteRefs(natural,!1)},required:["result"]}}var 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},maps$1;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}var rev2025RequestMethods=Object.keys(requestMethodKeys$1),rev2025NotificationMethods=Object.keys(notificationMethodKeys$1);function isPlainObject$5(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function triState$1(schema,raw){if(schema===void 0)return{ok:!1,reason:"not-in-era"};let parsed=schema.safeParse(raw);return parsed.success?{ok:!0,value:parsed.data}:{ok:!1,reason:"invalid",message:String(parsed.error)}}var NOT_IN_ERA$1={ok:!1,reason:"not-in-era"};function toolNeedsLegacyWrap(t){return isPlainObject$5(t)&&isPlainObject$5(t.outputSchema)&&isNonObjectJsonSchemaRoot(t.outputSchema)}function toNeutralResult(value){return value}var rev2025Codec={era:"2025-11-25",hasRequestMethod:hasRequestMethod2025,hasNotificationMethod:hasNotificationMethod2025,validateRequest:(method,raw)=>triState$1(getRequestSchema(method),raw),validateResult:(method,raw)=>triState$1(getResultSchema(method),raw),validateNotification:(method,raw)=>triState$1(getNotificationSchema(method),raw),hasInputRequestMethod:()=>!1,validateInputRequest:()=>NOT_IN_ERA$1,validateInputResponse:()=>NOT_IN_ERA$1,samplingResultVariant:(hasTools,raw)=>{let s=buildSchemas2025();return triState$1(hasTools?s.CreateMessageResultWithToolsSchema:s.CreateMessageResultSchema,raw)},outboundEnvelope:(_material)=>{return},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);if(!valueIsNonObject&&!schemaWrapped)return withText;return{...withText,structuredContent:{result:sc}}},decodeResult(_method,raw){if(isPlainObject$5(raw)&&"resultType"in raw){let stripped={...raw};return delete stripped.resultType,{kind:"complete",result:toNeutralResult(stripped)}}return{kind:"complete",result:toNeutralResult(raw)}},encodeResult(method,result){if(method!=="tools/list")return result;let tools=result.tools;if(!Array.isArray(tools)||!tools.some((t)=>toolNeedsLegacyWrap(t)))return result;return{...result,tools:tools.map((t)=>toolNeedsLegacyWrap(t)?{...t,outputSchema:wrapOutputSchemaForLegacy(t.outputSchema)}:t)}},encodeErrorCode:(code)=>code===-32002?-32602:code,checkInboundEnvelope:(_material)=>{return}};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)=>{if(value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).length===0)return{form:{}};return 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:exports_iso.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)}}var memo2;function buildSchemas2026(){return memo2??=build()}var CACHEABLE_RESULT_METHODS=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function isCacheableResultMethod(method){return CACHEABLE_RESULT_METHODS.includes(method)}var RESULT_CACHE_HINT_FALLBACK=Symbol("modelcontextprotocol.resultCacheHintFallback");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"}var 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 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"];function stampResultType(method,result){let provided=result.resultType;if(provided===void 0)return{...result,resultType:"complete"};if(provided==="complete")return result;if(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$4(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function stampServerInfoMeta(result,serverInfo){if(serverInfo===void 0)return result;let meta2=result._meta;if(meta2===void 0)return{...result,_meta:{[SERVER_INFO_META_KEY]:serverInfo}};if(!isPlainObject$4(meta2))return result;if(meta2[SERVER_INFO_META_KEY]!==void 0)return result;return{...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}var INPUT_REQUEST_METHODS_2026=["elicitation/create","sampling/createMessage","roots/list"],maps;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}var 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};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}var rev2026RequestMethods=Object.keys(requestMethodKeys),rev2026NotificationMethods=Object.keys(notificationMethodKeys);function isPlainObject$3(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function triState(schema,raw){if(schema===void 0)return{ok:!1,reason:"not-in-era"};let parsed=schema.safeParse(raw);return parsed.success?{ok:!0,value:parsed.data}:{ok:!1,reason:"invalid",message:String(parsed.error)}}var NOT_IN_ERA={ok:!1,reason:"not-in-era"},REQUIRED_ENVELOPE_KEYS=[PROTOCOL_VERSION_META_KEY,CLIENT_CAPABILITIES_META_KEY];function enforceDeletedFields(method,result){let next=result,copied=!1,copy=()=>{if(!copied)next={...next},copied=!0;return next},tools=result.tools;if(method==="tools/list"&&Array.isArray(tools)&&tools.some((tool)=>isPlainObject$3(tool)&&("execution"in tool)))copy().tools=tools.map((tool)=>{if(!isPlainObject$3(tool)||!("execution"in tool))return tool;let rest={...tool};return delete rest.execution,rest});let capabilities=result.capabilities;if(isPlainObject$3(capabilities)&&"tasks"in capabilities){let rest={...capabilities};delete rest.tasks,copy().capabilities=rest}return next}var rev2026Codec={era:"2026-07-28",hasRequestMethod:hasRequestMethod2026,hasNotificationMethod:hasNotificationMethod2026,hasInputRequestMethod:(method)=>getInputRequestSchema2026(method)!==void 0,validateRequest:(method,raw)=>triState(getRequestSchema2026(method),raw),validateResult:(method,raw)=>triState(getResultSchema2026(method),raw),validateNotification:(method,raw)=>triState(getNotificationSchema2026(method),raw),validateInputRequest:(method,raw)=>triState(getInputRequestSchema2026(method),raw),validateInputResponse:(method,raw)=>triState(getInputResponseSchema2026(method),raw),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)if(!(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";if(path.length===1&&issues.some((existing)=>existing.key===key&&existing.problem==="missing"))continue;issues.push({key,problem:issue2.message})}return issues},projectCallToolResult:(result)=>appendTextFallbackForNonObject(result),inputRequestSchema:getInputRequestSchema2026,decodeResult(method,raw){if(!isPlainObject$3(raw))return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: not an object`,{method})};let rawResultType=raw.resultType;if(rawResultType===void 0)return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: missing required resultType — 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=raw.inputRequests,inputRequests=isPlainObject$3(rawInputRequests)?rawInputRequests:{},requestState=raw.requestState,metaParse=raw._meta===void 0?void 0:buildSchemas2026().ResultMetaSchema.safeParse(raw._meta),meta2=metaParse?.success?metaParse.data:void 0;if(Object.keys(inputRequests).length===0&&typeof requestState!=="string")return{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"})};return{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(raw);if(!parsed.success)return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: ${parsed.error}`,{method})}}let lifted={...raw};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("; ")}`}},wireResultSchemasMemo;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}var MODERN_WIRE_REVISION="2026-07-28";function codecForVersion(version2){return version2!==void 0&&isModernProtocolVersion(version2)?rev2026Codec:rev2025Codec}function classifiedWireEra(classification){if(classification.revision!==void 0)return codecForVersion(classification.revision).era;return 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"}var ALL_CODECS=[rev2025Codec,rev2026Codec],schemas_exports=__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});var isJSONRPCRequest=(value)=>JSONRPCRequestSchema.safeParse(value).success,isJSONRPCNotification=(value)=>JSONRPCNotificationSchema.safeParse(value).success,isJSONRPCResultResponse=(value)=>JSONRPCResultResponseSchema.safeParse(value).success,isJSONRPCErrorResponse=(value)=>JSONRPCErrorResponseSchema.safeParse(value).success;var isInputRequiredResult=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value)&&value.resultType==="input_required";var isInitializeRequest=(value)=>InitializeRequestSchema.safeParse(value).success,isInitializedNotification=(value)=>InitializedNotificationSchema.safeParse(value).success;var 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"]);function scanXMcpHeaderDeclarations(inputSchema){let declarations=[],seenLower=new Map,visit=(node2,path,reachable)=>{if(node2===null||typeof node2!=="object")return;let schema=node2;if(X_MCP_HEADER_KEY in schema){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 raw=schema[X_MCP_HEADER_KEY];if(typeof raw!=="string"||raw.length===0)return`${pathName(path)}: x-mcp-header MUST be a non-empty string`;if(!RFC9110_TOKEN.test(raw))return`${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let type=typeof schema.type==="string"?schema.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=raw.toLowerCase(),prior=seenLower.get(lower);if(prior!==void 0)return`x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;seenLower.set(lower,raw),declarations.push({path,headerName:raw,type})}let properties=schema.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=schema[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(inputSchema,[],!0);return fault===void 0?{valid:!0,declarations}:{valid:!1,reason:fault}}var 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"]);function pathName(path){return path.length===0?"<root>":path.join(".")}var BASE64_SENTINEL_PREFIX="=?base64?",BASE64_SENTINEL_SUFFIX="?=";function mcpParamPrimitiveToString(value){if(typeof value==="string")return value;if(typeof value==="boolean")return value?"true":"false";if(typeof value==="number"){if(!Number.isFinite(value))return;if(Number.isInteger(value)&&!Number.isSafeInteger(value))return;return String(value)}}function needsBase64(s){if(s.length===0)return!0;if(s.startsWith(BASE64_SENTINEL_PREFIX)&&s.endsWith(BASE64_SENTINEL_SUFFIX))return!0;if(s!==s.trim())return!0;for(let i=0;i<s.length;i++){let c=s.codePointAt(i);if(c===9||c>=32&&c<=126)continue;return!0}return!1}function utf8ToBase64(s){let bytes=new TextEncoder().encode(s),bin="";for(let b of bytes)bin+=String.fromCodePoint(b);return btoa(bin)}function encodeMcpParamValue(value){return needsBase64(value)?`${BASE64_SENTINEL_PREFIX}${utf8ToBase64(value)}${BASE64_SENTINEL_SUFFIX}`:value}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 buildMcpParamHeaders(declarations,args){let out={};for(let decl of declarations){let raw=valueAtPath(args,decl.path);if(raw===void 0||raw===null)continue;let stringValue=mcpParamPrimitiveToString(raw);if(stringValue===void 0)continue;out[`${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`]=encodeMcpParamValue(stringValue)}return out}var HEADER_MISMATCH_ERROR_CODE=-32020,INBOUND_VALIDATION_LADDER=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32000],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 — and a missing envelope on a request whose protocol-version header names a modern revision — 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’s 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 — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — 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’s 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 — 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–6) 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 — 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’s `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"};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 raw=isPlainObject$2(params)?params[field]:void 0;return{field,value:typeof raw==="string"?raw:void 0}}function isPlainObject$2(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function parseSchema(schema,data){return safeParse(schema,data)}function shapeKeys(schemas3){return new Set(schemas3.flatMap((schema)=>Object.keys(schema.shape)))}function isStandardSchema(schema){if(schema==null)return!1;let schemaType=typeof schema;if(schemaType!=="object"&&schemaType!=="function")return!1;if(!("~standard"in schema))return!1;return typeof schema["~standard"]?.validate==="function"}var warnedZodFallback=!1,JSON_SCHEMA_CONVERSION_TARGET="draft-2020-12";function standardSchemaToJsonSchema(schema,io="input"){let std=schema["~standard"],result;if(std.jsonSchema)result=std.jsonSchema[io]({target:JSON_SCHEMA_CONVERSION_TARGET});else if(std.vendor==="zod"){if(!("_zod"in schema))throw 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().");if(!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(schema,{target:JSON_SCHEMA_CONVERSION_TARGET,io})}else throw 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"){if(result.type!==void 0)return result;return isProvablyObjectShapedRoot(result)?{type:"object",...result}:result}if(result.type!==void 0&&result.type!=="object")throw 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(schema){if("properties"in schema||"patternProperties"in schema||"additionalProperties"in schema||"required"in schema)return!0;for(let key of["oneOf","anyOf","allOf"]){let members2=schema[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){if(!issue2.path?.length)return issue2.message;return`${issue2.path.map((p)=>String(typeof p==="object"?p.key:p)).join(".")}: ${issue2.message}`}async function validateStandardSchema(schema,data){let result=await schema["~standard"].validate(data);if(result.issues&&result.issues.length>0)return{success:!1,error:result.issues.map((i)=>formatIssue(i)).join(", ")};return{success:!0,data:result.value}}function zodEmittedPattern(schema){let jsonSchema=toJSONSchema(schema,{target:JSON_SCHEMA_CONVERSION_TARGET,io:"input"});return typeof jsonSchema.pattern==="string"?jsonSchema.pattern:void 0}var DATETIME_FRACTION_DIGITS=/\\\.\\d\{(\d+)\}/;function datetimeReferenceSchemas(pattern){let fractionDigits=DATETIME_FRACTION_DIGITS.exec(pattern),precisions=[void 0,-1,0];if(fractionDigits)precisions.push(Number(fractionDigits[1]));return[!1,!0].flatMap((local)=>[!1,!0].flatMap((offset)=>precisions.map((precision)=>exports_iso.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=[exports_iso.date()];break;case"date-time":referenceSchemas=datetimeReferenceSchemas(pattern);break}return new Set(referenceSchemas.map((schema)=>zodEmittedPattern(schema)).filter((emitted)=>emitted!==void 0))}function isLibraryFormatPattern(format,pattern,vendor){if(vendor!=="zod")return!0;return referencePatternsForFormat(format,pattern).has(pattern)}function isJsonObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function convertStandardElicitationSchema(schema){try{return standardSchemaToJsonSchema(schema,"input")}catch(error2){let detail=error2 instanceof Error?error2.message:String(error2);throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`)}}var ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function isAnnotationOnlyJsonSchemaKeyword(key){return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key)||key.startsWith("x-")}var 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);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))if(allowedKeys.has(key)||isAnnotationOnlyJsonSchemaKeyword(key))pruned[key]=value;else if(key==="pattern"&&node2.type==="string"&&typeof node2.format==="string"){if(!SUPPORTED_STRING_FORMATS.has(node2.format))pruned[key]=value;else if(typeof value!=="string"||!isLibraryFormatPattern(node2.format,value,vendor))unsupported.push(`${path}.${key}`)}else unsupported.push(`${path}.${key}`);return pruned}function walkRequestedSchema(converted,vendor){let pruned={},unsupported=[];for(let[key,value]of Object.entries(converted))if(key==="properties"&&isJsonObject(value))pruned[key]=Object.fromEntries(Object.entries(value).map(([name,node2])=>[name,walkProperty(node2,`properties.${name}`,vendor,unsupported)]));else if(ROOT_KEYS.has(key))pruned[key]=value;else if(!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=""){if(Array.isArray(original)&&Array.isArray(parsed))return original.flatMap((item,index)=>findDroppedConstraintPaths(item,parsed[index],`${path}[${index}]`));if(!isJsonObject(original)||!isJsonObject(parsed))return[];return Object.entries(original).flatMap(([key,value])=>{let childPath=path?`${path}.${key}`:key;if(!Object.prototype.hasOwnProperty.call(parsed,key))return isAnnotationOnlyJsonSchemaKeyword(key)?[]:[childPath];return findDroppedConstraintPaths(value,parsed[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 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}}}var inputRequired=Object.assign(buildInputRequired,{elicit(params){try{return{method:"elicitation/create",params:normalizeElicitInputParams(params)}}catch(error2){throw error2 instanceof ProtocolError?TypeError(error2.message,{cause:error2}):error2}},elicitUrl(params){return{method:"elicitation/create",params:{...params,mode:"url"}}},createMessage(params){return{method:"sampling/createMessage",params}},listRoots(){return{method:"roots/list"}}});var DEFAULT_INPUT_REQUIRED_AUTO_FULFILL=!0,DEFAULT_INPUT_REQUIRED_MAX_ROUNDS=10,REQUEST_STATE_ONLY_LEG_PACING_MS=250;function resolveInputRequiredDriverConfig(options){return{autoFulfill:options?.autoFulfill??DEFAULT_INPUT_REQUIRED_AUTO_FULFILL,maxRounds:options?.maxRounds??DEFAULT_INPUT_REQUIRED_MAX_ROUNDS}}function buildInputRequiredRetryParams(originalParams,responses,requestState){let hasResponses=responses!==void 0&&Object.keys(responses).length>0;if(!hasResponses&&requestState===void 0)return originalParams;return{...originalParams,...hasResponses&&{inputResponses:responses},...requestState!==void 0&&{requestState}}}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);if(outer?.addEventListener("abort",onOuterAbort,{once:!0}),outer?.aborted)controller.abort(outer.reason);return{signal:controller.signal,abort:(reason)=>controller.abort(reason),dispose:()=>outer?.removeEventListener("abort",onOuterAbort)}}async function runInputRequiredDriver(args){let{config:config2,method,originalParams,requestOptions,hooks,signal}=args,startedAt=args.flowStartedAt??Date.now(),payload=args.firstPayload,round=0;while(!0){if(round+=1,round>config2.maxRounds)throw new SdkError(SdkErrorCode.InputRequiredRoundsExceeded,inputRequiredRoundsExceededMessage(method,config2.maxRounds),{rounds:config2.maxRounds,lastResult:{inputRequests:payload.inputRequests,...payload.requestState!==void 0&&{requestState:payload.requestState}}});requestOptions.onprogress?.({progress:round,message:`Fulfilling input required by '${method}' (round ${round})`});let entries=Object.entries(payload.inputRequests??{}),responses;if(entries.length>0){let round$1=linkedRoundAbort(signal);try{let fulfilled=await Promise.all(entries.map(async([key,entry])=>{try{return[key,await hooks.dispatchInputRequest(key,entry,round$1.signal)]}catch(error2){throw round$1.abort(error2),error2}}));responses=Object.fromEntries(fulfilled)}finally{round$1.dispose()}}else await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS,signal);let legOptions={...requestOptions.timeout!==void 0&&{timeout:requestOptions.timeout}};if(requestOptions.maxTotalTimeout!==void 0){let totalElapsed=Date.now()-startedAt,remaining=requestOptions.maxTotalTimeout-totalElapsed;if(remaining<=0)throw new SdkError(SdkErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:requestOptions.maxTotalTimeout,totalElapsed});legOptions.maxTotalTimeout=remaining}let result=await hooks.retry(buildInputRequiredRetryParams(originalParams,responses,payload.requestState),legOptions);if(isInputRequiredResult(result)){payload={inputRequests:result.inputRequests??{},...result.requestState!==void 0&&{requestState:result.requestState}};continue}return result}}var 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={};function register(key,schema){let name=key.slice(0,-6);_specTypeSchemas[name]=schema,_isSpecType[name]=(v)=>schema.safeParse(v).success}for(let key of SPEC_SCHEMA_KEYS)register(key,schemas_exports[key]);for(let[key,schema]of Object.entries(authSchemas))register(key,schema);var specTypeSchemas=Object.freeze(_specTypeSchemas),isSpecType=Object.freeze(_isSpecType);function bootstrapOutboundCodec(method){switch(method){case"initialize":case"notifications/initialized":return codecForVersion(void 0);case"server/discover":return codecForVersion(MODERN_WIRE_REVISION);default:return}}var DEFAULT_REQUEST_TIMEOUT_MSEC=60000,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"];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];if(lifted.envelope=envelope,Object.keys(nextMeta).length>0)nextParams._meta=nextMeta;else delete nextParams._meta}for(let key of retryKeys){if(key==="inputResponses")lifted.inputResponses=nextParams[key];if(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;return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(value){let outcome=codec.validateResult(method,value);if(outcome.ok)return{value:outcome.value};return{issues:[{message:outcome.reason==="invalid"?outcome.message:`not-in-era: ${method}`}]}}}}}function requestStateAccessor(value){return()=>value}var NO_REQUEST_STATE=requestStateAccessor(void 0),writeNegotiatedProtocolVersion,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){if(notification.params.requestId===void 0)return;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);if(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=(error2)=>{_onerror?.(error2),this._onerror(error2)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{if(_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message))this._onresponse(message);else if(isJSONRPCRequest(message))this._onrequest(message,extra);else if(isJSONRPCNotification(message))this._onnotification(message,extra);else this._onerror(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 error2=new SdkError(SdkErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let handler of responseHandlers.values())handler(error2);for(let controller of requestHandlerAbortControllers.values())controller.abort(error2)}}_onerror(error2){this.onerror?.(error2)}_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(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;if(handler===void 0&&fallback===void 0)return;Promise.resolve().then(()=>handler===void 0?fallback(notification):handler(notification,codec)).catch((error2)=>this._onerror(Error(`Uncaught error in notification handler: ${error2}`)))}_onrequest(rawRequest,extra){let{message:request,lifted}=liftWireOnlyMaterial(rawRequest,"request"),codec=this._negotiatedWireCodec();if(extra?.classification===void 0&&this._shouldDropInbound(rawRequest)==="drop"){this._onerror(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((error2)=>this._onerror(Error(`Failed to send an error response: ${error2}`)))};if(extra?.classification!==void 0){let classified=classifiedWireEra(extra.classification);if(classified!==codec.era){this._onerror(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 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(error2){this._onerror(Error(`Failed to encode result for ${request.method}: ${error2}`)),sendErrorResponse(ProtocolErrorCode.InternalError,"Internal error");return}let response={result:encoded,jsonrpc:"2.0",id:request.id};await capturedTransport?.send(response)},async(error2)=>{if(abortController.signal.aborted)return;let thrownCode=Number.isSafeInteger(error2.code)?error2.code:ProtocolErrorCode.InternalError,errorResponse={jsonrpc:"2.0",id:request.id,error:{code:codec.encodeErrorCode(thrownCode),message:error2.message??"Internal error",...error2.data!==void 0&&{data:error2.data}}};await capturedTransport?.send(errorResponse)}).catch((error2)=>this._onerror(Error(`Failed to send response: ${error2}`))).finally(()=>{if(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(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(error2){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error2);return}handler(params)}_onresponse(response){let messageId=Number(response.id),handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}if(this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId),this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response))handler(response);else 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)){if(!isExtensionReusedRequestMethod(request.method))this._assertOutboundRequestInEra(codec,request.method);return this._requestWithSchemaViaCodec(codec,request,schemaOrOptions,maybeOptions)}this._assertOutboundRequestInEra(codec,request.method);let validate2=codecResultValidator(codec,request.method);if(validate2===void 0)throw 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=(error2)=>{reject(error2)};if(!this._transport){earlyReject(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method)}catch(error2){earlyReject(error2);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};if(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)=>{if(responseReceived)return;if(this._progressHandlers.delete(messageId),requestAbort===void 0){if(request.method!=="initialize")this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}}),{relatedRequestId,resumptionToken,onresumptiontoken}).catch((error2)=>this._onerror(Error(`Failed to send cancellation: ${error2}`)))}else 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(error2){return reject(error2 instanceof Error?error2:Error(String(error2)))}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)=>{if(parseResult.success)resolve(parseResult.data);else 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((error2)=>{this._progressHandlers.delete(messageId),reject(error2)})}).finally(()=>{if(onAbort)options?.signal?.removeEventListener("abort",onAbort);if(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(()=>{if(this._pendingDebouncedNotifications.delete(notification.method),!this._transport)return;this._transport?.send(jsonrpcNotification,options).catch((error2)=>this._onerror(error2))});return}await this._transport.send(jsonrpcNotification,options)}setRequestHandler(method,schemasOrHandler,maybeHandler){this.assertRequestHandlerCapability(method);let stored;if(typeof schemasOrHandler==="function"){if(!isSpecRequestMethod(method))throw 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);if(!outcome.ok){if(outcome.reason==="not-in-era")throw new ProtocolError(ProtocolErrorCode.InternalError,`No wire schema for ${method} in the resolved era`);throw 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 TypeError("setRequestHandler: handler is required");if(typeof schemasOrHandler==="function")this._customSchemaRequestMethods.delete(method);else 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 Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(method,schemasOrHandler,maybeHandler){if(typeof schemasOrHandler==="function"){if(!isSpecNotificationMethod(method))throw 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){if(outcome.reason==="not-in-era")throw new ProtocolError(ProtocolErrorCode.InternalError,`No wire schema for ${method} in the resolved era`);throw Error(outcome.message)}return Promise.resolve(schemasOrHandler(outcome.value))});return}if(!maybeHandler)throw 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)}};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 relatedMessagingUnavailable(member){throw new SdkError(SdkErrorCode.SendFailed,`ctx.mcpReq.${member} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function synthesizeInputRequestContext(key,method,params,signal,sessionId){return{sessionId,mcpReq:{id:key,method,_meta:params?._meta,requestState:requestStateAccessor(void 0),signal,send:()=>relatedMessagingUnavailable("send"),notify:()=>relatedMessagingUnavailable("notify")}}}async function dispatchInputRequest(host,codec,key,entry,signal){if(!isPlainObject2(entry)||typeof entry.method!=="string")throw new SdkError(SdkErrorCode.InvalidResult,`Invalid input request '${key}': each inputRequests entry must be an embedded request object with a method`,{key});let method=entry.method;if(!codec.hasInputRequestMethod(method))throw new SdkError(SdkErrorCode.InvalidResult,`Invalid input request '${key}': '${method}' is not an embedded request the ${codec.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key,method});let handler=host.getRequestHandler(method);if(handler===void 0)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Cannot fulfil input request '${key}': no handler is registered for '${method}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key,method});let params=isPlainObject2(entry.params)?entry.params:void 0;return await handler({jsonrpc:"2.0",id:key,method,...params!==void 0&&{params}},host.buildContext(synthesizeInputRequestContext(key,method,params,signal,host.sessionId)))}function buildRetryLegRequestOptions(options,legOptions){return{...options?.signal!==void 0&&{signal:options.signal},...options?.onprogress!==void 0&&{onprogress:options.onprogress},...options?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:options.resetTimeoutOnProgress},...options?.headers!==void 0&&{headers:options.headers},...legOptions.timeout!==void 0&&{timeout:legOptions.timeout},...legOptions.maxTotalTimeout!==void 0&&{maxTotalTimeout:legOptions.maxTotalTimeout},allowInputRequired:!0}}function runInputRequiredFlow(host,config2,decoded,flow){let{codec,request,options,flowStartedAt}=flow,firstPayload={inputRequests:decoded.inputRequests,...decoded.requestState!==void 0&&{requestState:decoded.requestState}},hooks={dispatchInputRequest:(key,entry,signal)=>dispatchInputRequest(host,codec,key,entry,signal),retry:(params,legOptions)=>flow.retry(params,buildRetryLegRequestOptions(options,legOptions))};return runInputRequiredDriver({config:config2,method:request.method,originalParams:request.params,firstPayload,flowStartedAt,signal:options?.signal,requestOptions:{...options?.timeout!==void 0&&{timeout:options.timeout},...options?.maxTotalTimeout!==void 0&&{maxTotalTimeout:options.maxTotalTimeout},...options?.onprogress!==void 0&&{onprogress:options.onprogress}},hooks})}function manualInputRequiredValue(decoded){return{resultType:"input_required",inputRequests:decoded.inputRequests,...decoded.requestState!==void 0&&{requestState:decoded.requestState},...decoded._meta!==void 0&&{_meta:decoded._meta}}}/*!
59
+ * content-type
60
+ * Copyright(c) 2015 Douglas Christopher Wilson
61
+ * MIT Licensed
62
+ */var 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 TypeError("argument string is required");var header=typeof string4==="object"?getcontenttype(string4):string4;if(typeof header!=="string")throw 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 TypeError("invalid media type");var obj=new ContentType(type.toLowerCase());if(index!==-1){var key,match,value;PARAM_REGEXP.lastIndex=index;while(match=PARAM_REGEXP.exec(header)){if(match.index!==index)throw TypeError("invalid parameter format");if(index+=match[0].length,key=match[1].toLowerCase(),value=match[2],value.charCodeAt(0)===34){if(value=value.slice(1,-1),value.indexOf("\\")!==-1)value=value.replace(QESC_REGEXP,"$1")}obj.parameters[key]=value}if(index!==header.length)throw TypeError("invalid parameter format")}return obj}function getcontenttype(obj){var header;if(typeof obj.getHeader==="function")header=obj.getHeader("content-type");else if(typeof obj.headers==="object")header=obj.headers&&obj.headers["content-type"];if(typeof header!=="string")throw 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);function mediaTypeEssence(header){if(!header)return;try{return import_content_type.parse(header).type}catch{let essence=(header.split(";",1)[0]??"").trim().toLowerCase();if(essence===""||header.slice(essence.length).includes(","))return;return essence}}function normalizeHeaders(headers){if(!headers)return{};if(headers instanceof Headers)return Object.fromEntries(headers.entries());if(Array.isArray(headers))return Object.fromEntries(headers);return{...headers}}function createFetchWithInit(baseFetch=fetch,baseInit){if(!baseInit)return baseFetch;return async(url2,init)=>{return baseFetch(url2,{...baseInit,...init,headers:init?.headers?{...normalizeHeaders(baseInit.headers),...normalizeHeaders(init.headers)}:baseInit.headers})}}var REDIRECT_STATUSES=new Set([301,302,303,307,308]),MAX_REDIRECTS=5;function isWithinOrigin(from,to){if(from.protocol===to.protocol&&from.host===to.host)return!0;return from.protocol==="http:"&&to.protocol==="https:"&&from.hostname===to.hostname&&!from.port&&!to.port}function redirectTarget(url2,response){let location=REDIRECT_STATUSES.has(response.status)?response.headers?.get("location"):void 0;if(!location)return;try{return new URL(location,url2)}catch{return}}var leftToFetch=new WeakSet;function fetchLeavingRedirects(baseFetch){let copy=(url2,init)=>baseFetch(url2,init);return leftToFetch.add(copy),copy}function fetchWithinOrigin(baseFetch){if(leftToFetch.has(baseFetch))return baseFetch;return async(url2,init)=>{if(init?.redirect==="error"||init?.redirect==="manual")return baseFetch(url2,init);let method=(init?.method??"GET").toUpperCase(),current=url2;for(let followed=0;;followed++){let response=await baseFetch(current,{...init,redirect:"manual"}),target=redirectTarget(current,response);if(!target||followed===MAX_REDIRECTS)return response;let from=new URL(current),keepsMethod=method==="GET"||response.status===307||response.status===308,keepsUserinfo=!(target.username||target.password)||target.username===from.username&&target.password===from.password;if(!keepsMethod||!keepsUserinfo||!isWithinOrigin(from,target))return response;await response.text?.().catch(()=>{}),current=target}}}function unfollowedRedirect(url2,response){if(response.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let target=redirectTarget(response.url||url2,response);if(!target)return;if(target.username=target.password=target.search=target.hash="",target.protocol==="http:"&&new URL(response.url||url2).protocol==="https:")return target.protocol="https:",`Redirect from https to plain http not followed; try ${target.href} as the endpoint`;return`Redirect to ${target.href} not followed; use that URL as the endpoint if it is the intended server`}var 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){super();if(!exports.IDENTIFIER.test(s))throw 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)=>{if(c instanceof Name)names[c.str]=(names[c.str]||0)+1;return names},{})}};exports._Code=_Code,exports.nil=new _Code("");function _(strs,...args){let code=[strs[0]],i=0;while(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;while(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){if(arg instanceof _Code)code.push(...arg._items);else if(arg instanceof Name)code.push(arg);else code.push(interpolate(arg))}exports.addCodeArg=addCodeArg;function optimize(expr){let i=1;while(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"){if(b instanceof Name||a[a.length-1]!=='"')return;if(typeof b!="string")return`${a.slice(0,-1)}${b}"`;if(b[0]==='"')return a.slice(0,-1)+b.slice(1);return}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 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?void 0:_b.has(prefix))||this._prefixes&&!this._prefixes.has(prefix))throw 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=code_1._`.${new code_1.Name(property)}[${itemIndex}]`}};exports.ValueScopeName=ValueScopeName;let line=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 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;return vs.get(keyOrRef)}scopeRefs(scopeName,values=this._values){return this._reduceValues(values,(name)=>{if(name.scopePath===void 0)throw Error(`CodeGen: name "${name}" has no value`);return code_1._`${scopeName}${name.scopePath}`})}scopeCode(values=this._values,usedValues,getCode){return this._reduceValues(values,(name)=>{if(name.value===void 0)throw 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=code_1._`${code}${def} ${name} = ${c};${this.opts._n}`}else if(c=getCode===null||getCode===void 0?void 0:getCode(name))code=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 Node=class{optimizeNodes(){return this}optimizeNames(_names,_constants){return this}},Def=class extends Node{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;if(this.rhs)this.rhs=optimizeExpr(this.rhs,names,constants);return this}get names(){return this.rhs instanceof code_1._CodeOrName?this.rhs.names:{}}},Assign=class extends Node{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;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 Node{constructor(label){super();this.label=label,this.names={}}render({_n}){return`${this.label}:`+_n}},Break=class extends Node{constructor(label){super();this.label=label,this.names={}}render({_n}){return`break${this.label?` ${this.label}`:""};`+_n}},Throw=class extends Node{constructor(error2){super();this.error=error2}render({_n}){return`throw ${this.error};`+_n}get names(){return this.error.names}},AnyCode=class extends Node{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 Node{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;while(i--){let n=nodes[i].optimizeNodes();if(Array.isArray(n))nodes.splice(i,1,...n);else if(n)nodes[i]=n;else nodes.splice(i,1)}return nodes.length>0?this:void 0}optimizeNames(names,constants){let{nodes}=this,i=nodes.length;while(i--){let n=nodes[i];if(n.optimizeNames(names,constants))continue;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);if(this.else)code+="else "+this.else.render(opts);return 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){if(cond===!1)return e instanceof If2?e:e.nodes;if(this.nodes.length)return this;return new If2(not(cond),e instanceof If2?[e]:e.nodes)}if(cond===!1||!this.nodes.length)return;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;return this.condition=optimizeExpr(this.condition,names,constants),this}get names(){let names=super.names;if(addExprNames(names,this.condition),this.else)addNames(names,this.else.names);return 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;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;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);if(this.catch)code+=this.catch.render(opts);if(this.finally)code+=this.finally.render(opts);return 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;if(this.catch)addNames(names,this.catch.names);if(this.finally)addNames(names,this.finally.names);return names}},Catch=class extends BlockNode{constructor(error2){super();this.error=error2}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?`
63
+ `:""},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);if(rhs!==void 0&&constant)this._constants[name.str]=rhs;return 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){if(typeof c=="function")c();else if(c!==code_1.nil)this._leafNode(new AnyCode(c));return this}object(...keyValues){let code=["{"];for(let[key,value]of keyValues){if(code.length>1)code.push(",");if(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 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){if(this._blockNode(node2),forBody)this.code(forBody).endFor();return 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,code_1._`${arr}.length`,(i)=>{this.var(name,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,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 Error('CodeGen: "return" should have one node');return this._endBlockNode(Return)}try(tryBody,catchCode,finallyCode){if(!catchCode&&!finallyCode)throw Error('CodeGen: "try" without "catch" and "finally"');let node2=new Try;if(this._blockNode(node2),this.code(tryBody),catchCode){let error2=this.name("e");this._currNode=node2.catch=new Catch(error2),catchCode(error2)}if(finallyCode)this._currNode=node2.finally=new Finally,this.code(finallyCode);return this._endBlockNode(Catch,Finally)}throw(error2){return this._leafNode(new Throw(error2))}block(body,nodeCount){if(this._blockStarts.push(this._nodes.length),body)this.code(body).endBlock(nodeCount);return this}endBlock(nodeCount){let len=this._blockStarts.pop();if(len===void 0)throw Error("CodeGen: not in self-balancing block");let toClose=this._nodes.length-len;if(toClose<0||nodeCount!==void 0&&toClose!==nodeCount)throw Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);return this._nodes.length=len,this}func(name,args=code_1.nil,async,funcBody){if(this._blockNode(new Func(name,args,async)),funcBody)this.code(funcBody).endFunc();return this}endFunc(){return this._endBlockNode(Func)}optimize(n=1){while(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 Error(`CodeGen: not in block "${N2?`${N1.kind}/${N2.kind}`:N1.kind}"`)}_elseNode(node2){let n=this._currNode;if(!(n instanceof If))throw 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)=>{if(c instanceof code_1.Name)c=replaceName(c);if(c instanceof code_1._Code)items.push(...c._items);else items.push(c);return items},[]));function replaceName(n){let c=constants[n.str];if(c===void 0||names[n.str]!==1)return n;return 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: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:code_1._`${par(x)} ${op} ${par(y)}`}function par(x){return x instanceof code_1.Name?x: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,schema){if(typeof schema=="boolean")return schema;if(Object.keys(schema).length===0)return!0;return checkUnknownRules(it,schema),!schemaHasRules(schema,it.self.RULES.all)}exports.alwaysValidSchema=alwaysValidSchema;function checkUnknownRules(it,schema=it.schema){let{opts,self}=it;if(!opts.strictSchema)return;if(typeof schema==="boolean")return;let rules=self.RULES.keywords;for(let key in schema)if(!rules[key])checkStrictMode(it,`unknown keyword: "${key}"`)}exports.checkUnknownRules=checkUnknownRules;function schemaHasRules(schema,rules){if(typeof schema=="boolean")return!schema;for(let key in schema)if(rules[key])return!0;return!1}exports.schemaHasRules=schemaHasRules;function schemaHasRulesButRef(schema,RULES){if(typeof schema=="boolean")return!schema;for(let key in schema)if(key!=="$ref"&&RULES.all[key])return!0;return!1}exports.schemaHasRulesButRef=schemaHasRulesButRef;function schemaRefOrVal({topSchemaRef,schemaPath},schema,keyword,$data){if(!$data){if(typeof schema=="number"||typeof schema=="boolean")return schema;if(typeof schema=="string")return codegen_1._`${schema}`}return 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){if(typeof str=="number")return`${str}`;return 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(codegen_1._`${to} !== true && ${from} !== undefined`,()=>{gen.if(codegen_1._`${from} === true`,()=>gen.assign(to,!0),()=>gen.assign(to,codegen_1._`${to} || {}`).code(codegen_1._`Object.assign(${to}, ${from})`))}),mergeToName:(gen,from,to)=>gen.if(codegen_1._`${to} !== true`,()=>{if(from===!0)gen.assign(to,!0);else gen.assign(to,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(codegen_1._`${to} !== true && ${from} !== undefined`,()=>gen.assign(to,codegen_1._`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),mergeToName:(gen,from,to)=>gen.if(codegen_1._`${to} !== true`,()=>gen.assign(to,from===!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",codegen_1._`{}`);if(ps!==void 0)setEvaluated(gen,props,ps);return props}exports.evaluatedPropsToName=evaluatedPropsToName;function setEvaluated(gen,props,ps){Object.keys(ps).forEach((p)=>gen.assign(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?codegen_1._`"[" + ${dataProp} + "]"`:codegen_1._`"['" + ${dataProp} + "']"`:isNumber?codegen_1._`"/" + ${dataProp}`: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)return;if(msg=`strict mode: ${msg}`,mode===!0)throw 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})=>codegen_1.str`must pass "${keyword}" keyword validation`},exports.keyword$DataError={message:({keyword,schemaType})=>schemaType?codegen_1.str`"${keyword}" keyword must be ${schemaType} ($data)`:codegen_1.str`"${keyword}" keyword is invalid ($data)`};function reportError(cxt,error2=exports.keywordError,errorPaths,overrideAllErrors){let{it}=cxt,{gen,compositeRule,allErrors}=it,errObj=errorObjectCode(cxt,error2,errorPaths);if(overrideAllErrors!==null&&overrideAllErrors!==void 0?overrideAllErrors:compositeRule||allErrors)addError(gen,errObj);else returnErrors(it,codegen_1._`[${errObj}]`)}exports.reportError=reportError;function reportExtraError(cxt,error2=exports.keywordError,errorPaths){let{it}=cxt,{gen,compositeRule,allErrors}=it;if(addError(gen,errorObjectCode(cxt,error2,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(codegen_1._`${names_1.default.vErrors} !== null`,()=>gen.if(errsCount,()=>gen.assign(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 Error("ajv implementation error");let err=gen.name("err");gen.forRange("i",errsCount,names_1.default.errors,(i)=>{if(gen.const(err,codegen_1._`${names_1.default.vErrors}[${i}]`),gen.if(codegen_1._`${err}.instancePath === undefined`,()=>gen.assign(codegen_1._`${err}.instancePath`,(0,codegen_1.strConcat)(names_1.default.instancePath,it.errorPath))),gen.assign(codegen_1._`${err}.schemaPath`,codegen_1.str`${it.errSchemaPath}/${keyword}`),it.opts.verbose)gen.assign(codegen_1._`${err}.schema`,schemaValue),gen.assign(codegen_1._`${err}.data`,data)})}exports.extendErrors=extendErrors;function addError(gen,errObj){let err=gen.const("err",errObj);gen.if(codegen_1._`${names_1.default.vErrors} === null`,()=>gen.assign(names_1.default.vErrors,codegen_1._`[${err}]`),codegen_1._`${names_1.default.vErrors}.push(${err})`),gen.code(codegen_1._`${names_1.default.errors}++`)}function returnErrors(it,errs){let{gen,validateName,schemaEnv}=it;if(schemaEnv.$async)gen.throw(codegen_1._`new ${it.ValidationError}(${errs})`);else gen.assign(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,error2,errorPaths){let{createErrors}=cxt.it;if(createErrors===!1)return codegen_1._`{}`;return errorObject(cxt,error2,errorPaths)}function errorObject(cxt,error2,errorPaths={}){let{gen,it}=cxt,keyValues=[errorInstancePath(it,errorPaths),errorSchemaPath(cxt,errorPaths)];return extraErrorProps(cxt,error2,keyValues),gen.object(...keyValues)}function errorInstancePath({errorPath},{instancePath}){let instPath=instancePath?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:codegen_1.str`${errSchemaPath}/${keyword}`;if(schemaPath)schPath=codegen_1.str`${schPath}${(0,util_1.getErrorPath)(schemaPath,util_1.Type.Str)}`;return[E.schemaPath,schPath]}function extraErrorProps(cxt,{params,message},keyValues){let{keyword,data,schemaValue,it}=cxt,{opts,propertyName,topSchemaRef,schemaPath}=it;if(keyValues.push([E.keyword,keyword],[E.params,typeof params=="function"?params(cxt):params||codegen_1._`{}`]),opts.messages)keyValues.push([E.message,typeof message=="function"?message(cxt):message]);if(opts.verbose)keyValues.push([E.schema,schemaValue],[E.parentSchema,codegen_1._`${topSchemaRef}${schemaPath}`],[names_1.default.data,data]);if(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,validateName}=it;if(schema===!1)falseSchemaError(it,!1);else if(typeof schema=="object"&&schema.$async===!0)gen.return(names_1.default.data);else gen.assign(codegen_1._`${validateName}.errors`,null),gen.return(!0)}exports.topBoolOrEmptySchema=topBoolOrEmptySchema;function boolOrEmptySchema(it,valid){let{gen,schema}=it;if(schema===!1)gen.var(valid,!1),falseSchemaError(it);else 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,self},type){let group=self.RULES.types[type];return group&&group!==!0&&shouldUseGroup(schema,group)}exports.schemaHasRulesForType=schemaHasRulesForType;function shouldUseGroup(schema,group){return group.rules.some((rule)=>shouldUseRule(schema,rule))}exports.shouldUseGroup=shouldUseGroup;function shouldUseRule(schema,rule){var _a3;return schema[rule.keyword]!==void 0||((_a3=rule.definition.implements)===null||_a3===void 0?void 0:_a3.some((kwd)=>schema[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(schema){let types=getJSONTypes(schema.type);if(types.includes("null")){if(schema.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!types.length&&schema.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(schema.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 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,()=>{if(coerceTo.length)coerceData(it,types,coerceTo);else 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",codegen_1._`typeof ${data}`),coerced=gen.let("coerced",codegen_1._`undefined`);if(opts.coerceTypes==="array")gen.if(codegen_1._`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`,()=>gen.assign(data,codegen_1._`${data}[0]`).assign(dataType,codegen_1._`typeof ${data}`).if(checkDataTypes(types,data,opts.strictNumbers),()=>gen.assign(coerced,data)));gen.if(codegen_1._`${coerced} !== undefined`);for(let t of coerceTo)if(COERCIBLE.has(t)||t==="array"&&opts.coerceTypes==="array")coerceSpecificType(t);gen.else(),reportTypeError(it),gen.endIf(),gen.if(codegen_1._`${coerced} !== undefined`,()=>{gen.assign(data,coerced),assignParentData(it,coerced)});function coerceSpecificType(t){switch(t){case"string":gen.elseIf(codegen_1._`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced,codegen_1._`"" + ${data}`).elseIf(codegen_1._`${data} === null`).assign(coerced,codegen_1._`""`);return;case"number":gen.elseIf(codegen_1._`${dataType} == "boolean" || ${data} === null
64
+ || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced,codegen_1._`+${data}`);return;case"integer":gen.elseIf(codegen_1._`${dataType} === "boolean" || ${data} === null
65
+ || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced,codegen_1._`+${data}`);return;case"boolean":gen.elseIf(codegen_1._`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced,!1).elseIf(codegen_1._`${data} === "true" || ${data} === 1`).assign(coerced,!0);return;case"null":gen.elseIf(codegen_1._`${data} === "" || ${data} === 0 || ${data} === false`),gen.assign(coerced,null);return;case"array":gen.elseIf(codegen_1._`${dataType} === "string" || ${dataType} === "number"
66
+ || ${dataType} === "boolean" || ${data} === null`).assign(coerced,codegen_1._`[${data}]`)}}}function assignParentData({gen,parentData,parentDataProperty},expr){gen.if(codegen_1._`${parentData} !== undefined`,()=>gen.assign(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 codegen_1._`${data} ${EQ} null`;case"array":cond=codegen_1._`Array.isArray(${data})`;break;case"object":cond=codegen_1._`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;break;case"integer":cond=numCond(codegen_1._`!(${data} % 1) && !isNaN(${data})`);break;case"number":cond=numCond();break;default:return 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)(codegen_1._`typeof ${data} == "number"`,_cond,strictNums?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=codegen_1._`typeof ${data} != "object"`;cond=types.null?notObj:codegen_1._`!${data} || ${notObj}`,delete types.null,delete types.array,delete types.object}else cond=codegen_1.nil;if(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})=>`must be ${schema}`,params:({schema,schemaValue})=>typeof schema=="string"?codegen_1._`{type: ${schema}}`: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}=it,schemaCode=(0,util_1.schemaRefOrVal)(it,schema,"type");return{gen,keyword:"type",data,schema:schema.type,schemaCode,schemaValue:schemaCode,parentSchema:schema,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 if(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=codegen_1._`${data}${(0,codegen_1.getProperty)(prop)}`;if(compositeRule){(0,util_1.checkStrictMode)(it,`default is ignored for: ${childData}`);return}let condition=codegen_1._`${childData} === undefined`;if(opts.useDefaults==="empty")condition=codegen_1._`${condition} || ${childData} === null || ${childData} === ""`;gen.if(condition,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: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),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:codegen_1._`Object.prototype.hasOwnProperty`})}exports.hasPropFunc=hasPropFunc;function isOwnProperty(gen,data,property){return codegen_1._`${hasPropFunc(gen)}.call(${data}, ${property})`}exports.isOwnProperty=isOwnProperty;function propertyInData(gen,data,property,ownProperties){let cond=codegen_1._`${data}${(0,codegen_1.getProperty)(property)} !== undefined`;return ownProperties?codegen_1._`${cond} && ${isOwnProperty(gen,data,property)}`:cond}exports.propertyInData=propertyInData;function noPropertyInData(gen,data,property,ownProperties){let cond=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?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]];if(it.opts.dynamicRef)valCxt.push([names_1.default.dynamicAnchors,names_1.default.dynamicAnchors]);let args=codegen_1._`${dataAndSchema}, ${gen.object(...valCxt)}`;return context!==codegen_1.nil?codegen_1._`${func}.call(${context}, ${args})`:codegen_1._`${func}(${args})`}exports.callValidateCode=callValidateCode;let newRegExp=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: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",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,keyword,it}=cxt;if(!Array.isArray(schema))throw Error("ajv implementation error");if(schema.some((sch)=>(0,util_1.alwaysValidSchema)(it,sch))&&!it.opts.unevaluated)return;let valid=gen.let("valid",!1),schValid=gen.name("_valid");gen.block(()=>schema.forEach((_sch,i)=>{let schCxt=cxt.subschema({keyword,schemaProp:i,compositeRule:!0},schValid);if(gen.assign(valid,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,parentSchema,it}=cxt,macroSchema=def.macro.call(it.self,schema,parentSchema,it),schemaRef=useKeyword(gen,keyword,macroSchema);if(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,parentSchema,$data,it}=cxt;checkAsyncKeyword(it,def);let validateRef=useKeyword(gen,keyword,!$data&&def.compile?def.compile.call(it.self,schema,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){if(assignValid(),def.modifying)modifyData(cxt);reportErrs(()=>cxt.error())}else{let ruleErrs=def.async?validateAsync3():validateSync();if(def.modifying)modifyData(cxt);reportErrs(()=>addErrs(cxt,ruleErrs))}}function validateAsync3(){let ruleErrs=gen.let("ruleErrs",null);return gen.try(()=>assignValid(codegen_1._`await `),(e)=>gen.assign(valid,!1).if(codegen_1._`${e} instanceof ${it.ValidationError}`,()=>gen.assign(ruleErrs,codegen_1._`${e}.errors`),()=>gen.throw(e))),ruleErrs}function validateSync(){let validateErrs=codegen_1._`${validateRef}.errors`;return gen.assign(validateErrs,null),assignValid(codegen_1.nil),validateErrs}function assignValid(_await=def.async?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,codegen_1._`${_await}${(0,code_1.callValidateCode)(cxt,validateRef,passCxt,passSchema)}`,def.modifying)}function reportErrs(errors3){var _a$1;gen.if((0,codegen_1.not)((_a$1=def.valid)!==null&&_a$1!==void 0?_a$1:valid),errors3)}}exports.funcKeywordCode=funcKeywordCode;function modifyData(cxt){let{gen,data,it}=cxt;gen.if(it.parentData,()=>gen.assign(data,codegen_1._`${it.parentData}[${it.parentDataProperty}]`))}function addErrs(cxt,errs){let{gen}=cxt;gen.if(codegen_1._`Array.isArray(${errs})`,()=>{gen.assign(names_1.default.vErrors,codegen_1._`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors,codegen_1._`${names_1.default.vErrors}.length`),(0,errors_1.extendErrors)(cxt)},()=>cxt.error())}function checkAsyncKeyword({schemaEnv},def){if(def.async&&!schemaEnv.$async)throw Error("async keyword in sync schema")}function useKeyword(gen,keyword,result){if(result===void 0)throw 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(schema,schemaType,allowUndefined=!1){return!schemaType.length||schemaType.some((st)=>st==="array"?Array.isArray(schema):st==="object"?schema&&typeof schema=="object"&&!Array.isArray(schema):typeof schema==st||allowUndefined&&typeof schema>"u")}exports.validSchemaType=validSchemaType;function validateKeywordUsage({schema,opts,self,errSchemaPath},def,keyword){if(Array.isArray(def.keyword)?!def.keyword.includes(keyword):def.keyword!==keyword)throw Error("ajv implementation error");let deps=def.dependencies;if(deps===null||deps===void 0?void 0:deps.some((kwd)=>!Object.prototype.hasOwnProperty.call(schema,kwd)))throw Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);if(def.validateSchema){if(!def.validateSchema(schema[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 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,schemaPath,errSchemaPath,topSchemaRef}){if(keyword!==void 0&&schema!==void 0)throw 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:codegen_1._`${it.schemaPath}${(0,codegen_1.getProperty)(keyword)}`,errSchemaPath:`${it.errSchemaPath}/${keyword}`}:{schema:sch[schemaProp],schemaPath:codegen_1._`${it.schemaPath}${(0,codegen_1.getProperty)(keyword)}${(0,codegen_1.getProperty)(schemaProp)}`,errSchemaPath:`${it.errSchemaPath}/${keyword}/${(0,util_1.escapeFragment)(schemaProp)}`}}if(schema!==void 0){if(schemaPath===void 0||errSchemaPath===void 0||topSchemaRef===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema,schemaPath,topSchemaRef,errSchemaPath}}throw 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 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",codegen_1._`${it.data}${(0,codegen_1.getProperty)(dataProp)}`,!0)),subschema.errorPath=codegen_1.str`${errorPath}${(0,util_1.getErrorPath)(dataProp,dpType,opts.jsPropertySyntax)}`,subschema.parentDataProperty=codegen_1._`${dataProp}`,subschema.dataPathArr=[...dataPathArr,subschema.parentDataProperty]}if(data!==void 0){if(dataContextProps(data instanceof codegen_1.Name?data:gen.let("data",data,!0)),propertyName!==void 0)subschema.propertyName=propertyName}if(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}){if(compositeRule!==void 0)subschema.compositeRule=compositeRule;if(createErrors!==void 0)subschema.createErrors=createErrors;if(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,keys;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(keys=Object.keys(a),length=keys.length,length!==Object.keys(b).length)return!1;for(i=length;i--!==0;)if(!Object.prototype.hasOwnProperty.call(b,keys[i]))return!1;for(i=length;i--!==0;){var key=keys[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(schema,opts,cb){if(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,schema,"",schema)};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,schema,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex){if(schema&&typeof schema=="object"&&!Array.isArray(schema)){pre(schema,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex);for(var key in schema){var sch=schema[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,schema,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,schema,prop)}else if(key in traverse.keywords||opts.allKeys&&!(key in traverse.skipKeywords))_traverse(opts,pre,post,sch,jsonPtr+"/"+key,rootSchema,jsonPtr,key,schema)}post(schema,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(schema,limit=!0){if(typeof schema=="boolean")return!0;if(limit===!0)return!hasRef(schema);if(!limit)return!1;return countKeys(schema)<=limit}exports.inlineRef=inlineRef;let REF_KEYWORDS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function hasRef(schema){for(let key in schema){if(REF_KEYWORDS.has(key))return!0;let sch=schema[key];if(Array.isArray(sch)&&sch.some(hasRef))return!0;if(typeof sch=="object"&&hasRef(sch))return!0}return!1}function countKeys(schema){let count=0;for(let key in schema){if(key==="$ref")return 1/0;if(count++,SIMPLE_INLINED.has(key))continue;if(typeof schema[key]=="object")(0,util_1.eachItem)(schema[key],(sch)=>count+=countKeys(sch));if(count===1/0)return 1/0}return count}function getFullPath(resolver,id="",normalize){if(normalize!==!1)id=normalizeId(id);return _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(schema,baseId){if(typeof schema=="boolean")return{};let{schemaId,uriResolver}=this.opts,schId=normalizeId(schema[schemaId]||baseId),baseIds={"":schId},pathPrefix=getFullPath(uriResolver,schId,!1),localRefs={},schemaRefs=new Set;return traverse(schema,{allKeys:!0},(sch,jsonPtr,_,parentJsonPtr)=>{if(parentJsonPtr===void 0)return;let fullPath=pathPrefix+jsonPtr,innerBaseId=baseIds[parentJsonPtr];if(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];if(typeof schOrRef=="string")schOrRef=this.refs[schOrRef];if(typeof schOrRef=="object")checkAmbiguosRef(sch,schOrRef.schema,ref);else if(ref!==normalizeId(fullPath))if(ref[0]==="#")checkAmbiguosRef(sch,localRefs[ref],ref),localRefs[ref]=sch;else this.refs[ref]=fullPath;return ref}function addAnchor(anchor2){if(typeof anchor2=="string"){if(!ANCHOR.test(anchor2))throw 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 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)){if(checkKeywords(it),schemaCxtHasRules(it)){topSchemaObjCode(it);return}}validateFunction(it,()=>(0,boolSchema_1.topBoolOrEmptySchema)(it))}exports.validateFunctionCode=validateFunctionCode;function validateFunction({gen,validateName,schema,schemaEnv,opts},body){if(opts.code.es5)gen.func(validateName,codegen_1._`${names_1.default.data}, ${names_1.default.valCxt}`,schemaEnv.$async,()=>{gen.code(codegen_1._`"use strict"; ${funcSourceUrl(schema,opts)}`),destructureValCxtES5(gen,opts),gen.code(body)});else gen.func(validateName,codegen_1._`${names_1.default.data}, ${destructureValCxt(opts)}`,schemaEnv.$async,()=>gen.code(funcSourceUrl(schema,opts)).code(body))}function destructureValCxt(opts){return codegen_1._`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef?codegen_1._`, ${names_1.default.dynamicAnchors}={}`:codegen_1.nil}}={}`}function destructureValCxtES5(gen,opts){gen.if(names_1.default.valCxt,()=>{if(gen.var(names_1.default.instancePath,codegen_1._`${names_1.default.valCxt}.${names_1.default.instancePath}`),gen.var(names_1.default.parentData,codegen_1._`${names_1.default.valCxt}.${names_1.default.parentData}`),gen.var(names_1.default.parentDataProperty,codegen_1._`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`),gen.var(names_1.default.rootData,codegen_1._`${names_1.default.valCxt}.${names_1.default.rootData}`),opts.dynamicRef)gen.var(names_1.default.dynamicAnchors,codegen_1._`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`)},()=>{if(gen.var(names_1.default.instancePath,codegen_1._`""`),gen.var(names_1.default.parentData,codegen_1._`undefined`),gen.var(names_1.default.parentDataProperty,codegen_1._`undefined`),gen.var(names_1.default.rootData,names_1.default.data),opts.dynamicRef)gen.var(names_1.default.dynamicAnchors,codegen_1._`{}`)})}function topSchemaObjCode(it){let{schema,opts,gen}=it;validateFunction(it,()=>{if(opts.$comment&&schema.$comment)commentKeyword(it);if(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",codegen_1._`${validateName}.evaluated`),gen.if(codegen_1._`${it.evaluated}.dynamicProps`,()=>gen.assign(codegen_1._`${it.evaluated}.props`,codegen_1._`undefined`)),gen.if(codegen_1._`${it.evaluated}.dynamicItems`,()=>gen.assign(codegen_1._`${it.evaluated}.items`,codegen_1._`undefined`))}function funcSourceUrl(schema,opts){let schId=typeof schema=="object"&&schema[opts.schemaId];return schId&&(opts.code.source||opts.code.process)?codegen_1._`/*# sourceURL=${schId} */`:codegen_1.nil}function subschemaCode(it,valid){if(isSchemaObj(it)){if(checkKeywords(it),schemaCxtHasRules(it)){subSchemaObjCode(it,valid);return}}(0,boolSchema_1.boolOrEmptySchema)(it,valid)}function schemaCxtHasRules({schema,self}){if(typeof schema=="boolean")return!schema;for(let key in schema)if(self.RULES.all[key])return!0;return!1}function isSchemaObj(it){return typeof it.schema!="boolean"}function subSchemaObjCode(it,valid){let{schema,gen,opts}=it;if(opts.$comment&&schema.$comment)commentKeyword(it);updateContext(it),checkAsyncSchema(it);let errsCount=gen.const("_errs",names_1.default.errors);typeAndKeywords(it,errsCount),gen.var(valid,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,errSchemaPath,opts,self}=it;if(schema.$ref&&opts.ignoreKeywordsWithRef&&(0,util_1.schemaHasRulesButRef)(schema,self.RULES))self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)}function checkNoDefault(it){let{schema,opts}=it;if(schema.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];if(schId)it.baseId=(0,resolve_1.resolveUrl)(it.opts.uriResolver,it.baseId,schId)}function checkAsyncSchema(it){if(it.schema.$async&&!it.schemaEnv.$async)throw Error("async schema in sync schema")}function commentKeyword({gen,schemaEnv,schema,errSchemaPath,opts}){let msg=schema.$comment;if(opts.$comment===!0)gen.code(codegen_1._`${names_1.default.self}.logger.log(${msg})`);else if(typeof opts.$comment=="function"){let schemaPath=codegen_1.str`${errSchemaPath}/$comment`,rootName=gen.scopeValue("root",{ref:schemaEnv.root});gen.code(codegen_1._`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)}}function returnResults(it){let{gen,schemaEnv,validateName,ValidationError,opts}=it;if(schemaEnv.$async)gen.if(codegen_1._`${names_1.default.errors} === 0`,()=>gen.return(names_1.default.data),()=>gen.throw(codegen_1._`new ${ValidationError}(${names_1.default.vErrors})`));else{if(gen.assign(codegen_1._`${validateName}.errors`,names_1.default.vErrors),opts.unevaluated)assignEvaluated(it);gen.return(codegen_1._`${names_1.default.errors} === 0`)}}function assignEvaluated({gen,evaluated,props,items}){if(props instanceof codegen_1.Name)gen.assign(codegen_1._`${evaluated}.props`,props);if(items instanceof codegen_1.Name)gen.assign(codegen_1._`${evaluated}.items`,items)}function schemaKeywords(it,types,typeErrors,errsCount){let{gen,schema,data,allErrors,opts,self}=it,{RULES}=self;if(schema.$ref&&(opts.ignoreKeywordsWithRef||!(0,util_1.schemaHasRulesButRef)(schema,RULES))){gen.block(()=>keywordCode(it,"$ref",RULES.all.$ref.definition));return}if(!opts.jtd)checkStrictTypes(it,types);gen.block(()=>{for(let group of RULES.rules)groupKeywords(group);groupKeywords(RULES.post)});function groupKeywords(group){if(!(0,applicability_1.shouldUseGroup)(schema,group))return;if(group.type){if(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()}else iterateKeywords(it,group);if(!allErrors)gen.if(codegen_1._`${names_1.default.errors} === ${errsCount||0}`)}}function iterateKeywords(it,group){let{gen,schema,opts:{useDefaults}}=it;if(useDefaults)(0,defaults_1.assignDefaults)(it,group.type);gen.block(()=>{for(let rule of group.rules)if((0,applicability_1.shouldUseRule)(schema,rule))keywordCode(it,rule.keyword,rule.definition,group.type)})}function checkStrictTypes(it,types){if(it.schemaEnv.meta||!it.opts.strictTypes)return;if(checkContextTypes(it,types),!it.opts.allowUnionTypes)checkMultipleTypes(it,types);checkKeywordTypes(it,it.dataTypes)}function checkContextTypes(it,types){if(!types.length)return;if(!it.dataTypes.length){it.dataTypes=types;return}types.forEach((t)=>{if(!includesType(it.dataTypes,t))strictTypesError(it,`type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)}),narrowSchemaTypes(it,types)}function checkMultipleTypes(it,ts){if(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;if(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)if(includesType(withTypes,t))ts.push(t);else if(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 Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);if("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){if(this.gen.if(condition),failAction)failAction();else this.error();if(successAction){if(this.gen.else(),successAction(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(condition,failAction){this.failResult((0,codegen_1.not)(condition),void 0,failAction)}fail(condition){if(condition===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(condition),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(condition){if(!this.$data)return this.fail(condition);let{schemaCode}=this;this.fail(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 Error('add "trackErrors" to keyword definition');(0,errors_1.resetErrorsCount)(this.gen,this.errsCount)}ok(cond){if(!this.allErrors)this.gen.if(cond)}setParams(obj,assign){if(assign)Object.assign(this.params,obj);else 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;if(gen.if((0,codegen_1.or)(codegen_1._`${schemaCode} === undefined`,$dataValid)),valid!==codegen_1.nil)gen.assign(valid,!0);if(schemaType.length||def.validateSchema){if(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 Error("ajv implementation error");let st=Array.isArray(schemaType)?schemaType:[schemaType];return 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 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;if(!it.opts.unevaluated)return;if(it.props!==!0&&schemaCxt.props!==void 0)it.props=util_1.mergeEvaluated.props(gen,schemaCxt.props,it.props,toName);if(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);if("code"in def)def.code(cxt,ruleType);else if(cxt.$data&&def.validate)(0,keyword_1.funcKeywordCode)(cxt,def);else if("macro"in def)(0,keyword_1.macroKeywordCode)(cxt,def);else if(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 Error(`Invalid JSON-pointer: ${$data}`);jsonPointer=$data,data=names_1.default.rootData}else{let matches=RELATIVE_JSON_POINTER.exec($data);if(!matches)throw Error(`Invalid JSON-pointer: ${$data}`);let up=+matches[1];if(jsonPointer=matches[2],jsonPointer==="#"){if(up>=dataLevel)throw Error(errorMsg("property/index",up));return dataPathArr[dataLevel-up]}if(up>dataLevel)throw Error(errorMsg("data",up));if(data=dataNames[dataLevel-up],!jsonPointer)return data}let expr=data,segments=jsonPointer.split("/");for(let segment of segments)if(segment)data=codegen_1._`${data}${(0,codegen_1.getProperty)((0,util_1.unescapeJsonPointer)(segment))}`,expr=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(errors3){super("validation failed");this.errors=errors3,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(env){var _a3;this.refs={},this.dynamicAnchors={};let schema;if(typeof env.schema=="object")schema=env.schema;this.schema=env.schema,this.schemaId=env.schemaId,this.root=env.root||this,this.baseId=(_a3=env.baseId)!==null&&_a3!==void 0?_a3:(0,resolve_1.normalizeId)(schema===null||schema===void 0?void 0:schema[env.schemaId||"$id"]),this.schemaPath=env.schemaPath,this.localRefs=env.localRefs,this.meta=env.meta,this.$async=schema===null||schema===void 0?void 0:schema.$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;if(sch.$async)_ValidationError=gen.scopeValue("Error",{ref:validation_error_1.default,code: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: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();if(sourceCode=`${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`,this.opts.code.process)sourceCode=this.opts.code.process(sourceCode,sch);let validate2=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;if(this.opts.code.source===!0)validate2.source={validateName,validateCode,scopeValues:gen._values};if(this.opts.unevaluated){let{props,items}=schemaCxt;if(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){if(delete sch.validate,delete sch.validateName,sourceCode)this.logger.error("Error compiling schema, function code:",sourceCode);throw e}finally{this._compilations.delete(sch)}}exports.compileSchema=compileSchema;function resolveRef(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 schema=(_a3=root.localRefs)===null||_a3===void 0?void 0:_a3[ref],{schemaId}=this.opts;if(schema)_sch=new SchemaEnv({schema,schemaId,root,baseId})}if(_sch===void 0)return;return root.refs[ref]=inlineOrCompile.call(this,_sch)}exports.resolveRef=resolveRef;function inlineOrCompile(sch){if((0,resolve_1.inlineRef)(sch.schema,this.opts.inlineRefs))return sch.schema;return 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;while(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);if(typeof(sch===null||sch===void 0?void 0:sch.schema)!=="object")return;return getJsonPointer.call(this,p,sch)}if(typeof(schOrRef===null||schOrRef===void 0?void 0:schOrRef.schema)!=="object")return;if(!schOrRef.validate)compileSchema.call(this,schOrRef);if(id===(0,resolve_1.normalizeId)(ref)){let{schema}=schOrRef,{schemaId}=this.opts,schId=schema[schemaId];if(schId)baseId=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schId);return new SchemaEnv({schema,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,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 schema==="boolean")return;let partSchema=schema[(0,util_1.unescapeFragment)(part)];if(partSchema===void 0)return;schema=partSchema;let schId=typeof schema==="object"&&schema[this.opts.schemaId];if(!PREVENT_SCOPE_CHANGE.has(part)&&schId)baseId=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schId)}let env;if(typeof schema!="boolean"&&schema.$ref&&!(0,util_1.schemaHasRulesButRef)(schema,this.RULES)){let $ref=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schema.$ref);env=resolveSchema.call(this,root,$ref)}let{schemaId}=this.opts;if(env=env||new SchemaEnv({schema,schemaId,root,baseId}),env.schema!==env.root.schema)return env}}),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)continue;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==="]")continue;if(cursor===":"){if(endipv6Encountered===!0)endIpv6=!0;if(!consume(buffer,address,output))break;if(++tokenCount>7){output.error=!0;break}if(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}}if(buffer.length)if(consume===consumeIsZone)output.zone=buffer.join("");else if(endIpv6)address.push(buffer.join(""));else address.push(stringArrayToHexStripped(buffer));return output.address=address.join(""),output}function normalizeIPv6(host){if(findToken(host,":")<2)return{host,isIPV6:!1};let ipv62=getIPV6(host);if(!ipv62.error){let{address:newHost,address:escapedHost}=ipv62;if(ipv62.zone)newHost+="%"+ipv62.zone,escapedHost+="%25"+ipv62.zone;return{host:newHost,isIPV6:!0,escapedHost}}else return{host,isIPV6:!1}}function findToken(str,token){let ind=0;for(let i=0;i<str.length;i++)if(str[i]===token)ind++;return ind}function removeDotSegments(path){let input=path,output=[],nextSlash=-1,len=0;while(len=input.length){if(len===1)if(input===".")break;else if(input==="/"){output.push("/");break}else{output.push(input);break}else if(len===2){if(input[0]==="."){if(input[1]===".")break;else if(input[1]==="/"){input=input.slice(2);continue}}else if(input[0]==="/"){if(input[1]==="."||input[1]==="/"){output.push("/");break}}}else if(len===3){if(input==="/.."){if(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]==="/"){if(input[1]==="."){if(input[2]==="/"){input=input.slice(2);continue}else if(input[2]==="."){if(input[3]==="/"){if(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;if(component.scheme!==void 0)component.scheme=func(component.scheme);if(component.userinfo!==void 0)component.userinfo=func(component.userinfo);if(component.host!==void 0)component.host=func(component.host);if(component.path!==void 0)component.path=func(component.path);if(component.query!==void 0)component.query=func(component.query);if(component.fragment!==void 0)component.fragment=func(component.fragment);return component}function recomposeAuthority(component){let uriTokens=[];if(component.userinfo!==void 0)uriTokens.push(component.userinfo),uriTokens.push("@");if(component.host!==void 0){let host=unescape(component.host);if(!isIPv4(host)){let ipV6res=normalizeIPv6(host);if(ipV6res.isIPV6===!0)host=`[${ipV6res.escapedHost}]`;else host=component.host}uriTokens.push(host)}if(typeof component.port==="number"||typeof component.port==="string")uriTokens.push(":"),uriTokens.push(String(component.port));return 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){if(wsComponent.secure===!0)return!0;else if(wsComponent.secure===!1)return!1;else if(wsComponent.scheme)return 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");else return!1}function httpParse(component){if(!component.host)component.error=component.error||"HTTP URIs must have a host.";return component}function httpSerialize(component){let secure=String(component.scheme).toLowerCase()==="https";if(component.port===(secure?443:80)||component.port==="")component.port=void 0;if(!component.path)component.path="/";return 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;if(typeof wsComponent.secure==="boolean")wsComponent.scheme=wsComponent.secure?"wss":"ws",wsComponent.secure=void 0;if(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}`);if(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 Error("URN without nid cannot be serialized");let scheme=options.scheme||urnComponent.scheme||"urn",nid=urnComponent.nid.toLowerCase(),schemeHandler=getSchemeHandler(`${scheme}:${options.nid||nid}`);if(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;if(uuidComponent.uuid=uuidComponent.nss,uuidComponent.nss=void 0,!options.tolerant&&(!uuidComponent.uuid||!isUUID(uuidComponent.uuid)))uuidComponent.error=uuidComponent.error||"UUID is not valid.";return 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){if(typeof uri==="string")uri=serialize(parse4(uri,options),options);else if(typeof uri==="object")uri=parse4(serialize(uri,options),options);return 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,serialize(resolved,schemelessOptions)}function resolveComponent(base,relative,options,skipNormalization){let target={};if(!skipNormalization)base=parse4(serialize(base,options),options),relative=parse4(serialize(relative,options),options);if(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;else{if(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;else{if(!relative.path)if(target.path=base.path,relative.query!==void 0)target.query=relative.query;else target.query=base.query;else{if(relative.path[0]==="/")target.path=removeDotSegments(relative.path);else{if((base.userinfo!==void 0||base.host!==void 0||base.port!==void 0)&&!base.path)target.path="/"+relative.path;else if(!base.path)target.path=relative.path;else target.path=base.path.slice(0,base.path.lastIndexOf("/")+1)+relative.path;target.path=removeDotSegments(target.path)}target.query=relative.query}target.userinfo=base.userinfo,target.host=base.host,target.port=base.port}target.scheme=base.scheme}return target.fragment=relative.fragment,target}function equal(uriA,uriB,options){if(typeof uriA==="string")uriA=unescape(uriA),uriA=serialize(normalizeComponentEncoding(parse4(uriA,options),!0),{...options,skipEscape:!0});else if(typeof uriA==="object")uriA=serialize(normalizeComponentEncoding(uriA,!0),{...options,skipEscape:!0});if(typeof uriB==="string")uriB=unescape(uriB),uriB=serialize(normalizeComponentEncoding(parse4(uriB,options),!0),{...options,skipEscape:!0});else if(typeof uriB==="object")uriB=serialize(normalizeComponentEncoding(uriB,!0),{...options,skipEscape:!0});return uriA.toLowerCase()===uriB.toLowerCase()}function serialize(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);if(schemeHandler&&schemeHandler.serialize)schemeHandler.serialize(component,options);if(component.path!==void 0)if(!options.skipEscape){if(component.path=escape(component.path),component.scheme!==void 0)component.path=component.path.split("%3A").join(":")}else component.path=unescape(component.path);if(options.reference!=="suffix"&&component.scheme)uriTokens.push(component.scheme,":");let authority=recomposeAuthority(component);if(authority!==void 0){if(options.reference!=="suffix")uriTokens.push("//");if(uriTokens.push(authority),component.path&&component.path[0]!=="/")uriTokens.push("/")}if(component.path!==void 0){let s=component.path;if(!options.absolutePath&&(!schemeHandler||!schemeHandler.absolutePath))s=removeDotSegments(s);if(authority===void 0&&s[0]==="/"&&s[1]==="/")s="/%2F"+s.slice(2);uriTokens.push(s)}if(component.query!==void 0)uriTokens.push("?",component.query);if(component.fragment!==void 0)uriTokens.push("#",component.fragment);return 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;if(options.reference==="suffix")if(options.scheme)uri=options.scheme+":"+uri;else 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];if(parsed.host)if(isIPv4(parsed.host)===!1){let ipv6result=normalizeIPv6(parsed.host);parsed.host=ipv6result.host.toLowerCase(),isIP=ipv6result.isIPV6}else isIP=!0;if(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";else if(parsed.scheme===void 0)parsed.reference="relative";else if(parsed.fragment===void 0)parsed.reference="absolute";else parsed.reference="uri";if(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)){if(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}}if(!schemeHandler||schemeHandler&&!schemeHandler.skipNormalize){if(uri.indexOf("%")!==-1){if(parsed.scheme!==void 0)parsed.scheme=unescape(parsed.scheme);if(parsed.host!==void 0)parsed.host=unescape(parsed.host)}if(parsed.path)parsed.path=escape(unescape(parsed.path));if(parsed.fragment)parsed.fragment=encodeURI(decodeURIComponent(parsed.fragment))}if(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,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 Ajv=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;if(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);if(this._addVocabularies(),this._addDefaultMetaSchema(),opts.keywords)addInitialKeywords.call(this,opts.keywords);if(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;if(schemaId==="id")_dataRefSchema={...$dataRefSchema},_dataRefSchema.id=_dataRefSchema.$id,delete _dataRefSchema.$id;if(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 Error(`no schema with key or ref "${schemaKeyRef}"`)}else v=this.compile(schemaKeyRef);let valid=v(data);if(!("$async"in v))this.errors=v.errors;return valid}compile(schema,_meta){let sch=this._addSchema(schema,_meta);return sch.validate||this._compileSchemaEnv(sch)}compileAsync(schema,meta2){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema}=this.opts;return runCompileAsync.call(this,schema,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){if($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 Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)}async function loadMissingSchema(ref){let _schema=await _loadSchema.call(this,ref);if(!this.refs[ref])await loadMetaSchema.call(this,_schema.$schema);if(!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(schema,key,_meta,_validateSchema=this.opts.validateSchema){if(Array.isArray(schema)){for(let sch of schema)this.addSchema(sch,void 0,_meta,_validateSchema);return this}let id;if(typeof schema==="object"){let{schemaId}=this.opts;if(id=schema[schemaId],id!==void 0&&typeof id!="string")throw Error(`schema ${schemaId} must be string`)}return key=(0,resolve_1.normalizeId)(key||id),this._checkUnique(key),this.schemas[key]=this._addSchema(schema,_meta,key,_validateSchema,!0),this}addMetaSchema(schema,key,_validateSchema=this.opts.validateSchema){return this.addSchema(schema,key,!0,_validateSchema),this}validateSchema(schema,throwOrLogError){if(typeof schema=="boolean")return!0;let $schema;if($schema=schema.$schema,$schema!==void 0&&typeof $schema!="string")throw 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,schema);if(!valid&&throwOrLogError){let message="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(message);else throw Error(message)}return valid}getSchema(keyRef){let sch;while(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);if(typeof sch=="object")this._cache.delete(sch.schema);return delete this.schemas[schemaKeyRef],delete this.refs[schemaKeyRef],this}case"object":{let cacheKey=schemaKeyRef;this._cache.delete(cacheKey);let id=schemaKeyRef[this.opts.schemaId];if(id)id=(0,resolve_1.normalizeId)(id),delete this.schemas[id],delete this.refs[id];return this}default:throw 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"){if(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 Error("addKeywords: keyword must be string or non-empty array")}else throw 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);if(i>=0)group.rules.splice(i,1)}return this}addFormat(name,format){if(typeof format=="string")format=new RegExp(format);return this.formats[name]=format,this}errorsText(errors3=this.errors,{separator=", ",dataVar="data"}={}){if(!errors3||errors3.length===0)return"No errors";return errors3.map((e)=>`${dataVar}${e.instancePath} ${e.message}`).reduce((text,msg)=>text+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,schema=keywords[key];if($data&&schema)keywords[key]=schemaOrData(schema)}}return metaSchema}_removeAllSchemas(schemas3,regex){for(let keyRef in schemas3){let sch=schemas3[keyRef];if(!regex||regex.test(keyRef)){if(typeof sch=="string")delete schemas3[keyRef];else if(sch&&!sch.meta)this._cache.delete(sch.schema),delete schemas3[keyRef]}}}_addSchema(schema,meta2,baseId,validateSchema=this.opts.validateSchema,addSchema=this.opts.addUsedSchema){let id,{schemaId}=this.opts;if(typeof schema=="object")id=schema[schemaId];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof schema!="boolean")throw Error("schema must be object or boolean");let sch=this._cache.get(schema);if(sch!==void 0)return sch;baseId=(0,resolve_1.normalizeId)(id||baseId);let localRefs=resolve_1.getSchemaRefs.call(this,schema,baseId);if(sch=new compile_1.SchemaEnv({schema,schemaId,meta:meta2,baseId,localRefs}),this._cache.set(sch.schema,sch),addSchema&&!baseId.startsWith("#")){if(baseId)this._checkUnique(baseId);this.refs[baseId]=sch}if(validateSchema)this.validateSchema(schema,!0);return sch}_checkUnique(id){if(this.schemas[id]||this.refs[id])throw Error(`schema with key or id "${id}" already exists`)}_compileSchemaEnv(sch){if(sch.meta)this._compileMetaSchema(sch);else compile_1.compileSchema.call(this,sch);if(!sch.validate)throw 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}}};Ajv.ValidationError=validation_error_1.default,Ajv.MissingRefError=ref_error_1.default,exports.default=Ajv;function checkOptions(checkOpts,options,msg,log="error"){for(let key in checkOpts){let opt=key;if(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)return;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];if(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];if(!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 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 Error(`Keyword ${kwd} is already defined`);if(!KEYWORD_NAME.test(kwd))throw Error(`Keyword ${kwd} has invalid name`)}),!def)return;if(def.$data&&!(("code"in def)||("validate"in def)))throw Error('$data keyword must have "code" or "validate" function')}function addRule(keyword,definition,dataType){var _a3;let post=definition===null||definition===void 0?void 0:definition.post;if(dataType&&post)throw 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);if(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)}};if(definition.before)addBeforeRule.call(this,ruleGroup,rule,definition.before);else 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);if(i>=0)ruleGroup.rules.splice(i,0,rule);else ruleGroup.rules.push(rule),this.logger.warn(`rule ${before} is not defined`)}function keywordMetaschema(def){let{metaSchema}=def;if(metaSchema===void 0)return;if(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(schema){return{anyOf:[schema,$dataRef]}}}),require_id=__commonJSMin((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});let def={keyword:"id",code(){throw 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:env,validateName,opts,self}=it,{root}=env;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(env===root)return callRef(cxt,validateName,env,env.$async);let rootName=gen.scopeValue("root",{ref:root});return callRef(cxt,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}):codegen_1._`${gen.scopeValue("wrapper",{ref:sch})}.validate`}exports.getValidate=getValidate;function callRef(cxt,v,sch,$async){let{gen,it}=cxt,{allErrors,schemaEnv:env,opts}=it,passCxt=opts.passContext?names_1.default.this:codegen_1.nil;if($async)callAsyncRef();else callSyncRef();function callAsyncRef(){if(!env.$async)throw Error("async schema referenced by sync schema");let valid=gen.let("valid");gen.try(()=>{if(gen.code(codegen_1._`await ${(0,code_1.callValidateCode)(cxt,v,passCxt)}`),addEvaluatedFrom(v),!allErrors)gen.assign(valid,!0)},(e)=>{if(gen.if(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=codegen_1._`${source}.errors`;gen.assign(names_1.default.vErrors,codegen_1._`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`),gen.assign(names_1.default.errors,codegen_1._`${names_1.default.vErrors}.length`)}function addEvaluatedFrom(source){var _a3;if(!it.opts.unevaluated)return;let schEvaluated=(_a3=sch===null||sch===void 0?void 0:sch.validate)===null||_a3===void 0?void 0:_a3.evaluated;if(it.props!==!0)if(schEvaluated&&!schEvaluated.dynamicProps){if(schEvaluated.props!==void 0)it.props=util_1.mergeEvaluated.props(gen,schEvaluated.props,it.props)}else{let props=gen.var("props",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){if(schEvaluated.items!==void 0)it.items=util_1.mergeEvaluated.items(gen,schEvaluated.items,it.items)}else{let items=gen.var("items",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(),core2=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",id_1.default,ref_1.default];exports.default=core2}),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})=>codegen_1.str`must be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>codegen_1._`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`},code(cxt){let{keyword,data,schemaCode}=cxt;cxt.fail$data(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})=>codegen_1.str`must be multiple of ${schemaCode}`,params:({schemaCode})=>codegen_1._`{multipleOf: ${schemaCode}}`},code(cxt){let{gen,data,schemaCode,it}=cxt,prec=it.opts.multipleOfPrecision,res=gen.let("res"),invalid=prec?codegen_1._`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`:codegen_1._`${res} !== parseInt(${res})`;cxt.fail$data(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;while(pos<len)if(length++,value=str.charCodeAt(pos++),value>=55296&&value<=56319&&pos<len){if(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 codegen_1.str`must NOT have ${comp} than ${schemaCode} characters`},params:({schemaCode})=>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?codegen_1._`${data}.length`:codegen_1._`${(0,util_1.useFunc)(cxt.gen,ucs2length_1.default)}(${data})`;cxt.fail$data(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})=>codegen_1.str`must match pattern "${schemaCode}"`,params:({schemaCode})=>codegen_1._`{pattern: ${schemaCode}}`},code(cxt){let{gen,data,$data,schema,schemaCode,it}=cxt,u=it.opts.unicodeRegExp?"u":"";if($data){let{regExp}=it.opts.code,regExpCode=regExp.code==="new RegExp"?codegen_1._`new RegExp`:(0,util_1.useFunc)(gen,regExp),valid=gen.let("valid");gen.try(()=>gen.assign(valid,codegen_1._`${regExpCode}(${schemaCode}, ${u}).test(${data})`),()=>gen.assign(valid,!1)),cxt.fail$data(codegen_1._`!${valid}`)}else{let regExp=(0,code_1.usePattern)(cxt,schema);cxt.fail$data(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 codegen_1.str`must NOT have ${comp} than ${schemaCode} properties`},params:({schemaCode})=>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(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}})=>codegen_1.str`must have required property '${missingProperty}'`,params:({params:{missingProperty}})=>codegen_1._`{missingProperty: ${missingProperty}}`},code(cxt){let{gen,schema,schemaCode,data,$data,it}=cxt,{opts}=it;if(!$data&&schema.length===0)return;let useLoop=schema.length>=opts.loopRequired;if(it.allErrors)allErrorsMode();else exitOnErrorMode();if(opts.strictRequired){let props=cxt.parentSchema.properties,{definedProperties}=cxt.it;for(let requiredKey of schema)if((props===null||props===void 0?void 0: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 schema)(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,schema,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 codegen_1.str`must NOT have ${comp} than ${schemaCode} items`},params:({schemaCode})=>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(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}})=>codegen_1.str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,params:({params:{i,j}})=>codegen_1._`{i: ${i}, j: ${j}}`},code(cxt){let{gen,data,$data,schema,parentSchema,schemaCode,it}=cxt;if(!$data&&!schema)return;let valid=gen.let("valid"),itemTypes=parentSchema.items?(0,dataType_1.getSchemaTypes)(parentSchema.items):[];cxt.block$data(valid,validateUniqueItems,codegen_1._`${schemaCode} === false`),cxt.ok(valid);function validateUniqueItems(){let i=gen.let("i",codegen_1._`${data}.length`),j=gen.let("j");cxt.setParams({i,j}),gen.assign(valid,!0),gen.if(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",codegen_1._`{}`);gen.for(codegen_1._`;${i}--;`,()=>{if(gen.let(item,codegen_1._`${data}[${i}]`),gen.if(wrongType,codegen_1._`continue`),itemTypes.length>1)gen.if(codegen_1._`typeof ${item} == "string"`,codegen_1._`${item} += "_"`);gen.if(codegen_1._`typeof ${indices}[${item}] == "number"`,()=>{gen.assign(j,codegen_1._`${indices}[${item}]`),cxt.error(),gen.assign(valid,!1).break()}).code(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(codegen_1._`;${i}--;`,()=>gen.for(codegen_1._`${j} = ${i}; ${j}--;`,()=>gen.if(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})=>codegen_1._`{allowedValue: ${schemaCode}}`},code(cxt){let{gen,data,$data,schemaCode,schema}=cxt;if($data||schema&&typeof schema=="object")cxt.fail$data(codegen_1._`!${(0,util_1.useFunc)(gen,equal_1.default)}(${data}, ${schemaCode})`);else cxt.fail(codegen_1._`${schema} !== ${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})=>codegen_1._`{allowedValues: ${schemaCode}}`},code(cxt){let{gen,data,$data,schema,schemaCode,it}=cxt;if(!$data&&schema.length===0)throw Error("enum must have non-empty array");let useLoop=schema.length>=it.opts.loopEnum,eql,getEql=()=>eql!==null&&eql!==void 0?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(schema))throw Error("ajv implementation error");let vSchema=gen.const("vSchema",schemaCode);valid=(0,codegen_1.or)(...schema.map((_x,i)=>equalCode(vSchema,i)))}cxt.pass(valid);function loopEnum(){gen.assign(valid,!1),gen.forOf("v",schemaCode,(v)=>gen.if(codegen_1._`${getEql()}(${data}, ${v})`,()=>gen.assign(valid,!0).break()))}function equalCode(vSchema,i){let sch=schema[i];return typeof sch==="object"&&sch!==null?codegen_1._`${getEql()}(${data}, ${vSchema}[${i}])`: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}})=>codegen_1.str`must NOT have more than ${len} items`,params:({params:{len}})=>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,data,keyword,it}=cxt;it.items=!0;let len=gen.const("len",codegen_1._`${data}.length`);if(schema===!1)cxt.setParams({len:items.length}),cxt.pass(codegen_1._`${len} <= ${items.length}`);else if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){let valid=gen.var("valid",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)=>{if(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,it}=cxt;if(Array.isArray(schema))return validateTuple(cxt,"additionalItems",schema);if(it.items=!0,(0,util_1.alwaysValidSchema)(it,schema))return;cxt.ok((0,code_1.validateArray)(cxt))}};function validateTuple(cxt,extraItems,schArr=cxt.schema){let{gen,parentSchema,data,keyword,it}=cxt;if(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",codegen_1._`${data}.length`);schArr.forEach((sch,i)=>{if((0,util_1.alwaysValidSchema)(it,sch))return;gen.if(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}})=>codegen_1.str`must NOT have more than ${len} items`,params:({params:{len}})=>codegen_1._`{limit: ${len}}`},code(cxt){let{schema,parentSchema,it}=cxt,{prefixItems}=parentSchema;if(it.items=!0,(0,util_1.alwaysValidSchema)(it,schema))return;if(prefixItems)(0,additionalItems_1.validateAdditionalItems)(cxt,prefixItems);else 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?codegen_1.str`must contain at least ${min} valid item(s)`:codegen_1.str`must contain at least ${min} and no more than ${max} valid item(s)`,params:({params:{min,max}})=>max===void 0?codegen_1._`{minContains: ${min}}`:codegen_1._`{minContains: ${min}, maxContains: ${max}}`},code(cxt){let{gen,schema,parentSchema,data,it}=cxt,min,max,{minContains,maxContains}=parentSchema;if(it.opts.next)min=minContains===void 0?1:minContains,max=maxContains;else min=1;let len=gen.const("len",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,schema)){let cond=codegen_1._`${len} >= ${min}`;if(max!==void 0)cond=codegen_1._`${cond} && ${len} <= ${max}`;cxt.pass(cond);return}it.items=!0;let valid=gen.name("valid");if(max===void 0&&min===1)validateItems(valid,()=>gen.if(valid,()=>gen.break()));else if(min===0){if(gen.let(valid,!0),max!==void 0)gen.if(codegen_1._`${data}.length > 0`,validateItemsWithCount)}else 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){if(gen.code(codegen_1._`${count}++`),max===void 0)gen.if(codegen_1._`${count} >= ${min}`,()=>gen.assign(valid,!0).break());else if(gen.if(codegen_1._`${count} > ${max}`,()=>gen.assign(valid,!1).break()),min===1)gen.assign(valid,!0);else gen.if(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 codegen_1.str`must have ${property_ies} ${deps} when property ${property} is present`},params:({params:{property,depsCount,deps,missingProperty}})=>codegen_1._`{property: ${property},
67
+ missingProperty: ${missingProperty},
68
+ depsCount: ${depsCount},
69
+ 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}){let propertyDeps={},schemaDeps={};for(let key in schema){if(key==="__proto__")continue;let deps=Array.isArray(schema[key])?propertyDeps:schemaDeps;deps[key]=schema[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);if(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)});else gen.if(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){if((0,util_1.alwaysValidSchema)(it,schemaDeps[prop]))continue;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})=>codegen_1._`{propertyName: ${params.propertyName}}`},code(cxt){let{gen,schema,data,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema))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),()=>{if(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})=>codegen_1._`{additionalProperty: ${params.additionalProperty}}`},code(cxt){let{gen,schema,parentSchema,data,errsCount,it}=cxt;if(!errsCount)throw Error("ajv implementation error");let{allErrors,opts}=it;if(it.props=!0,opts.removeAdditional!=="all"&&(0,util_1.alwaysValidSchema)(it,schema))return;let props=(0,code_1.allSchemaProperties)(parentSchema.properties),patProps=(0,code_1.allSchemaProperties)(parentSchema.patternProperties);checkAdditionalProperties(),cxt.ok(codegen_1._`${errsCount} === ${names_1.default.errors}`);function checkAdditionalProperties(){gen.forIn("key",data,(key)=>{if(!props.length&&!patProps.length)additionalPropertyCode(key);else 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 if(props.length)definedProp=(0,codegen_1.or)(...props.map((p)=>codegen_1._`${key} === ${p}`));else definedProp=codegen_1.nil;if(patProps.length)definedProp=(0,codegen_1.or)(definedProp,...patProps.map((p)=>codegen_1._`${(0,code_1.usePattern)(cxt,p)}.test(${key})`));return(0,codegen_1.not)(definedProp)}function deleteAdditional(key){gen.code(codegen_1._`delete ${data}[${key}]`)}function additionalPropertyCode(key){if(opts.removeAdditional==="all"||opts.removeAdditional&&schema===!1){deleteAdditional(key);return}if(schema===!1){if(cxt.setParams({additionalProperty:key}),cxt.error(),!allErrors)gen.break();return}if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){let valid=gen.name("valid");if(opts.removeAdditional==="failing")applyAdditionalSchema(key,valid,!1),gen.if((0,codegen_1.not)(valid),()=>{cxt.reset(),deleteAdditional(key)});else if(applyAdditionalSchema(key,valid),!allErrors)gen.if((0,codegen_1.not)(valid),()=>gen.break())}}function applyAdditionalSchema(key,valid,errors3){let subschema={keyword:"additionalProperties",dataProp:key,dataPropType:util_1.Type.Str};if(errors3===!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,parentSchema,data,it}=cxt;if(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)(schema);for(let prop of allProps)it.definedProperties.add(prop);if(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,schema[p]));if(properties.length===0)return;let valid=gen.name("valid");for(let prop of properties){if(hasDefault(prop))applyPropertySchema(prop);else{if(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&&schema[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,data,parentSchema,it}=cxt,{opts}=it,patterns=(0,code_1.allSchemaProperties)(schema),alwaysValidPatterns=patterns.filter((p)=>(0,util_1.alwaysValidSchema)(it,schema[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");if(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){if(checkProperties)checkMatchingProperties(pat);if(it.allErrors)validateProperties(pat);else gen.var(valid,!0),validateProperties(pat),gen.if(valid)}}function checkMatchingProperties(pat){for(let prop in checkProperties)if(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(codegen_1._`${(0,code_1.usePattern)(cxt,pat)}.test(${key})`,()=>{let alwaysValid=alwaysValidPatterns.includes(pat);if(!alwaysValid)cxt.subschema({keyword:"patternProperties",schemaProp:pat,dataProp:key,dataPropType:util_2.Type.Str},valid);if(it.opts.unevaluated&&props!==!0)gen.assign(codegen_1._`${props}[${key}]`,!0);else if(!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,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema)){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})=>codegen_1._`{passingSchemas: ${params.passing}}`},code(cxt){let{gen,schema,parentSchema,it}=cxt;if(!Array.isArray(schema))throw Error("ajv implementation error");if(it.opts.discriminator&&parentSchema.discriminator)return;let schArr=schema,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;if((0,util_1.alwaysValidSchema)(it,sch))gen.var(schValid,!0);else schCxt=cxt.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},schValid);if(i>0)gen.if(codegen_1._`${schValid} && ${valid}`).assign(valid,!1).assign(passing,codegen_1._`[${passing}, ${i}]`).else();gen.if(schValid,()=>{if(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,it}=cxt;if(!Array.isArray(schema))throw Error("ajv implementation error");let valid=gen.name("valid");schema.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})=>codegen_1.str`must match "${params.ifClause}" schema`,params:({params})=>codegen_1._`{failingKeyword: ${params.ifClause}}`},code(cxt){let{gen,parentSchema,it}=cxt;if(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 if(hasThen)gen.if(schValid,validateClause("then"));else 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);if(gen.assign(valid,schValid),cxt.mergeValidEvaluated(schCxt,valid),ifClause)gen.assign(ifClause,codegen_1._`${keyword}`);else cxt.setParams({ifClause:keyword})}}}};function hasSchema(it,keyword){let schema=it.schema[keyword];return schema!==void 0&&!(0,util_1.alwaysValidSchema)(it,schema)}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}){if(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];if(draft2020)applicator.push(prefixItems_1.default,items2020_1.default);else applicator.push(additionalItems_1.default,items_1.default);return 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})=>codegen_1.str`must match format "${schemaCode}"`,params:({schemaCode})=>codegen_1._`{format: ${schemaCode}}`},code(cxt,ruleType){let{gen,data,$data,schema,schemaCode,it}=cxt,{opts,errSchemaPath,schemaEnv,self}=it;if(!opts.validateFormats)return;if($data)validate$DataFormat();else validateFormat();function validate$DataFormat(){let fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats}),fDef=gen.const("fDef",codegen_1._`${fmts}[${schemaCode}]`),fType=gen.let("fType"),format=gen.let("format");gen.if(codegen_1._`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,()=>gen.assign(fType,codegen_1._`${fDef}.type || "string"`).assign(format,codegen_1._`${fDef}.validate`),()=>gen.assign(fType,codegen_1._`"string"`).assign(format,fDef)),cxt.fail$data((0,codegen_1.or)(unknownFmt(),invalidFmt()));function unknownFmt(){if(opts.strictSchema===!1)return codegen_1.nil;return codegen_1._`${schemaCode} && !${format}`}function invalidFmt(){let callFormat=schemaEnv.$async?codegen_1._`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`:codegen_1._`${format}(${data})`,validData=codegen_1._`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;return codegen_1._`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`}}function validateFormat(){let formatDef=self.formats[schema];if(!formatDef){unknownFormat();return}if(formatDef===!0)return;let[fmtType,format,fmtRef]=getFormat(formatDef);if(fmtType===ruleType)cxt.pass(validCondition());function unknownFormat(){if(opts.strictSchema===!1){self.logger.warn(unknownMsg());return}throw Error(unknownMsg());function unknownMsg(){return`unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`}}function getFormat(fmtDef){let code=fmtDef instanceof RegExp?(0,codegen_1.regexpCode)(fmtDef):opts.code.formats?codegen_1._`${opts.code.formats}${(0,codegen_1.getProperty)(schema)}`:void 0,fmt=gen.scopeValue("formats",{key:schema,ref:fmtDef,code});if(typeof fmtDef=="object"&&!(fmtDef instanceof RegExp))return[fmtDef.type||"string",fmtDef.validate,codegen_1._`${fmt}.validate`];return["string",fmtDef,fmt]}function validCondition(){if(typeof formatDef=="object"&&!(formatDef instanceof RegExp)&&formatDef.async){if(!schemaEnv.$async)throw Error("async format in sync schema");return codegen_1._`await ${fmtRef}(${data})`}return typeof format=="function"?codegen_1._`${fmtRef}(${data})`: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}})=>codegen_1._`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`},code(cxt){let{gen,data,schema,parentSchema,it}=cxt,{oneOf}=parentSchema;if(!it.opts.discriminator)throw Error("discriminator: requires discriminator option");let tagName=schema.propertyName;if(typeof tagName!="string")throw Error("discriminator: requires propertyName");if(schema.mapping)throw Error("discriminator: mapping is not supported");if(!oneOf)throw Error("discriminator: requires oneOf keyword");let valid=gen.let("valid",!1),tag=gen.const("tag",codegen_1._`${data}${(0,codegen_1.getProperty)(tagName)}`);gen.if(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(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===null||sch===void 0?void 0: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;if(sch===void 0)throw new ref_error_1.default(it.opts.uriResolver,it.baseId,ref)}let propSch=(_a3=sch===null||sch===void 0?void 0:sch.properties)===null||_a3===void 0?void 0:_a3[tagName];if(typeof propSch!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);tagRequired=tagRequired&&(topRequired||hasRequired(sch)),addMappings(propSch,i)}if(!tagRequired)throw 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 Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)}function addMapping(tagValue,i){if(typeof tagValue!="string"||tagValue in oneOfMapping)throw 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 Ajv=class extends core_1.default{_addVocabularies(){if(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=Ajv,module.exports=exports=Ajv,module.exports.Ajv=Ajv,Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=Ajv;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=codegen_1._`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor2)}`,validate2=it.errSchemaPath==="#"?it.validateName:_getValidate(cxt);gen.if(codegen_1._`!${v}`,()=>gen.assign(v,validate2))}exports.dynamicAnchor=dynamicAnchor;function _getValidate(cxt){let{schemaEnv,schema,self}=cxt.it,{root,baseId,localRefs,meta:meta2}=schemaEnv.root,{schemaId}=self.opts,sch=new compile_1.SchemaEnv({schema,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 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",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){if(cxt.schema)(0,dynamicAnchor_1.dynamicAnchor)(cxt,"");else(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}){if(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})=>codegen_1._`{unevaluatedProperty: ${params.unevaluatedProperty}}`},code(cxt){let{gen,schema,data,errsCount,it}=cxt;if(!errsCount)throw Error("ajv implementation error");let{allErrors,props}=it;if(props instanceof codegen_1.Name)gen.if(codegen_1._`${props} !== true`,()=>gen.forIn("key",data,(key)=>gen.if(unevaluatedDynamic(props,key),()=>unevaluatedPropCode(key))));else if(props!==!0)gen.forIn("key",data,(key)=>props===void 0?unevaluatedPropCode(key):gen.if(unevaluatedStatic(props,key),()=>unevaluatedPropCode(key)));it.props=!0,cxt.ok(codegen_1._`${errsCount} === ${names_1.default.errors}`);function unevaluatedPropCode(key){if(schema===!1){if(cxt.setParams({unevaluatedProperty:key}),cxt.error(),!allErrors)gen.break();return}if(!(0,util_1.alwaysValidSchema)(it,schema)){let valid=gen.name("valid");if(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 codegen_1._`!${evaluatedProps} || !${evaluatedProps}[${key}]`}function unevaluatedStatic(evaluatedProps,key){let ps=[];for(let p in evaluatedProps)if(evaluatedProps[p]===!0)ps.push(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}})=>codegen_1.str`must NOT have more than ${len} items`,params:({params:{len}})=>codegen_1._`{limit: ${len}}`},code(cxt){let{gen,schema,data,it}=cxt,items=it.items||0;if(items===!0)return;let len=gen.const("len",codegen_1._`${data}.length`);if(schema===!1)cxt.setParams({len:items}),cxt.fail(codegen_1._`${len} > ${items}`);else if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){let valid=gen.var("valid",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)=>{if(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(),core2=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,core2,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(){if(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;if(!meta2)return;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(),core2=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,core2,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(){if(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;if(!meta2)return;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;if(d1>d2)return 1;if(d1<d2)return-1;return 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;return t1-t2}function compareIsoTime(t1,t2){if(!(t1&&t2))return;let a1=TIME.exec(t1),a2=TIME.exec(t2);if(!(a1&&a2))return;if(t1=a1[1]+a1[2]+a1[3],t2=a2[1]+a2[2]+a2[3],t1>t2)return 1;if(t1<t2)return-1;return 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;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;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=-2147483648,MAX_INT32=2147483647;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(e){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}},error2={message:({keyword,schemaCode})=>codegen_1.str`should be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>codegen_1._`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`};exports.formatLimitDefinition={keyword:Object.keys(KWDs),type:"string",schemaType:"string",$data:!0,error:error2,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");if(fCxt.$data)validate$DataFormat();else validateFormat();function validate$DataFormat(){let fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats}),fmt=gen.const("fmt",codegen_1._`${fmts}[${fCxt.schemaCode}]`);cxt.fail$data((0,codegen_1.or)(codegen_1._`typeof ${fmt} != "object"`,codegen_1._`${fmt} instanceof RegExp`,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 Error(`"${keyword}": format "${format}" does not define "compare" function`);let fmt=gen.scopeValue("formats",{key:format,ref:fmtDef,code:opts.code.formats?codegen_1._`${opts.code.formats}${(0,codegen_1.getProperty)(format)}`:void 0});cxt.fail$data(compareCode(fmt))}function compareCode(fmt){return codegen_1._`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`}},dependencies:["format"]};let formatLimitPlugin=(ajv)=>{return 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 addFormats(ajv,opts,formats_1.fullFormats,fullName),ajv;let[formats,exportName]=opts.mode==="fast"?[formats_1.fastFormats,fastName]:[formats_1.fullFormats,fullName];if(addFormats(ajv,opts.formats||formats_1.formatNames,formats,exportName),opts.keywords)(0,limit_1.default)(ajv);return ajv};formatsPlugin.get=(name,mode="full")=>{let f=(mode==="fast"?formats_1.fastFormats:formats_1.fullFormats)[name];if(!f)throw Error(`Unknown format "${name}"`);return f};function addFormats(ajv,list,fs,exportName){var _a3,_b;(_a3=(_b=ajv.opts.code).formats)!==null&&_a3!==void 0||(_b.formats=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;function createDefaultAjvInstance(engineClass){let ajv=new engineClass({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return addFormats(ajv),ajv}var 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(schema){if(this._userAjv)return this.ajv;let dialect=declaredDialect(schema,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");if(dialect==="2020-12")return this.ajv;if(dialect==="2019-09")return this._ajv2019??=createDefaultAjvInstance(import__2019.Ajv2019);return this._ajvDraft7??=createDefaultAjvInstance(import_ajv.Ajv)}getValidator(schema){let engine=this._engineFor(schema),ajvValidator="$id"in schema&&typeof schema.$id==="string"?engine.getSchema(schema.$id)??engine.compile(schema):engine.compile(schema);return(input)=>{return ajvValidator(input)?{valid:!0,data:input,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:engine.errorsText(ajvValidator.errors)}}}},Ajv=import_ajv.Ajv;var CORS_IS_POSSIBLE=!1;var crypto;crypto=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((m)=>m.webcrypto);async function getRandomValues(size){return(await crypto).getRandomValues(new Uint8Array(size))}async function random(size){let evenDistCutoff=Math.pow(2,8)-Math.pow(2,8)%66,result="";while(result.length<size){let randomBytes=await getRandomValues(size-result.length);for(let randomByte of randomBytes)if(randomByte<evenDistCutoff)result+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[randomByte%66]}return result}async function generateVerifier(length){return await random(length)}async function generateChallenge(code_verifier){let buffer=await(await crypto).subtle.digest("SHA-256",new TextEncoder().encode(code_verifier));return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function pkceChallenge(length){if(!length)length=43;if(length<43||length>128)throw`Expected a length between 43 and 128. Received ${length}.`;let verifier=await generateVerifier(length),challenge=await generateChallenge(verifier);return{code_verifier:verifier,code_challenge:challenge}}class ParseError extends Error{constructor(message,options){super(message),this.name="ParseError",this.type=options.type,this.field=options.field,this.value=options.value,this.line=options.line}}var LF=10,CR=13,SPACE=32;function noop(_arg){}function createParser(config2){if(typeof config2=="function")throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent=noop,onError=noop,onRetry=noop,onComment,maxBufferSize}=config2,pendingFragments=[],pendingFragmentsLength=0,isFirstChunk=!0,id,data="",dataLines=0,eventType,terminated=!1;function feed(chunk){if(terminated)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(isFirstChunk&&(isFirstChunk=!1,chunk.charCodeAt(0)===239&&chunk.charCodeAt(1)===187&&chunk.charCodeAt(2)===191&&(chunk=chunk.slice(3))),pendingFragments.length===0){let trailing2=processLines(chunk);trailing2!==""&&(pendingFragments.push(trailing2),pendingFragmentsLength=trailing2.length),checkBufferSize();return}if(chunk.indexOf(`
70
+ `)===-1&&chunk.indexOf("\r")===-1){pendingFragments.push(chunk),pendingFragmentsLength+=chunk.length,checkBufferSize();return}pendingFragments.push(chunk);let input=pendingFragments.join("");pendingFragments.length=0,pendingFragmentsLength=0;let trailing=processLines(input);trailing!==""&&(pendingFragments.push(trailing),pendingFragmentsLength=trailing.length),checkBufferSize()}function checkBufferSize(){maxBufferSize!==void 0&&(pendingFragmentsLength+data.length<=maxBufferSize||(terminated=!0,pendingFragments.length=0,pendingFragmentsLength=0,id=void 0,data="",dataLines=0,eventType=void 0,onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`,{type:"max-buffer-size-exceeded"}))))}function processLines(chunk){let searchIndex=0;if(chunk.indexOf("\r")===-1){let lfIndex=chunk.indexOf(`
71
+ `,searchIndex);for(;lfIndex!==-1;){if(searchIndex===lfIndex){dataLines>0&&onEvent({id,event:eventType,data}),id=void 0,data="",dataLines=0,eventType=void 0,searchIndex=lfIndex+1,lfIndex=chunk.indexOf(`
72
+ `,searchIndex);continue}let firstCharCode=chunk.charCodeAt(searchIndex);if(isDataPrefix(chunk,searchIndex,firstCharCode)){let valueStart=chunk.charCodeAt(searchIndex+5)===SPACE?searchIndex+6:searchIndex+5,value=chunk.slice(valueStart,lfIndex);if(dataLines===0&&chunk.charCodeAt(lfIndex+1)===LF){onEvent({id,event:eventType,data:value}),id=void 0,data="",eventType=void 0,searchIndex=lfIndex+2,lfIndex=chunk.indexOf(`
73
+ `,searchIndex);continue}data=dataLines===0?value:`${data}
74
+ ${value}`,dataLines++}else isEventPrefix(chunk,searchIndex,firstCharCode)?eventType=chunk.slice(chunk.charCodeAt(searchIndex+6)===SPACE?searchIndex+7:searchIndex+6,lfIndex)||void 0:parseLine(chunk,searchIndex,lfIndex);searchIndex=lfIndex+1,lfIndex=chunk.indexOf(`
75
+ `,searchIndex)}return chunk.slice(searchIndex)}for(;searchIndex<chunk.length;){let crIndex=chunk.indexOf("\r",searchIndex),lfIndex=chunk.indexOf(`
76
+ `,searchIndex),lineEnd=-1;if(crIndex!==-1&&lfIndex!==-1?lineEnd=crIndex<lfIndex?crIndex:lfIndex:crIndex!==-1?crIndex===chunk.length-1?lineEnd=-1:lineEnd=crIndex:lfIndex!==-1&&(lineEnd=lfIndex),lineEnd===-1)break;parseLine(chunk,searchIndex,lineEnd),searchIndex=lineEnd+1,chunk.charCodeAt(searchIndex-1)===CR&&chunk.charCodeAt(searchIndex)===LF&&searchIndex++}return chunk.slice(searchIndex)}function parseLine(chunk,start,end){if(start===end){dispatchEvent();return}let firstCharCode=chunk.charCodeAt(start);if(isDataPrefix(chunk,start,firstCharCode)){let valueStart=chunk.charCodeAt(start+5)===SPACE?start+6:start+5,value2=chunk.slice(valueStart,end);data=dataLines===0?value2:`${data}
77
+ ${value2}`,dataLines++;return}if(isEventPrefix(chunk,start,firstCharCode)){eventType=chunk.slice(chunk.charCodeAt(start+6)===SPACE?start+7:start+6,end)||void 0;return}if(firstCharCode===105&&chunk.charCodeAt(start+1)===100&&chunk.charCodeAt(start+2)===58){let value2=chunk.slice(chunk.charCodeAt(start+3)===SPACE?start+4:start+3,end);value2.includes("\x00")||(id=value2);return}if(firstCharCode===58){if(onComment){let line2=chunk.slice(start,end);onComment(line2.slice(chunk.charCodeAt(start+1)===SPACE?2:1))}return}let line=chunk.slice(start,end),fieldSeparatorIndex=line.indexOf(":");if(fieldSeparatorIndex===-1){processField(line,"",line);return}let field=line.slice(0,fieldSeparatorIndex),offset=line.charCodeAt(fieldSeparatorIndex+1)===SPACE?2:1,value=line.slice(fieldSeparatorIndex+offset);processField(field,value,line)}function processField(field,value,line){switch(field){case"event":eventType=value||void 0;break;case"data":data=dataLines===0?value:`${data}
78
+ ${value}`,dataLines++;break;case"id":value.includes("\x00")||(id=value);break;case"retry":/^\d+$/.test(value)?onRetry(parseInt(value,10)):onError(new ParseError(`Invalid \`retry\` value: "${value}"`,{type:"invalid-retry",value,line}));break;default:onError(new ParseError(`Unknown field "${field.length>20?`${field.slice(0,20)}…`:field}"`,{type:"unknown-field",field,value,line}));break}}function dispatchEvent(){dataLines>0&&onEvent({id,event:eventType,data}),id=void 0,data="",dataLines=0,eventType=void 0}function reset(options={}){if(options.consume&&pendingFragments.length>0){let incompleteLine=pendingFragments.join("");parseLine(incompleteLine,0,incompleteLine.length)}isFirstChunk=!0,id=void 0,data="",dataLines=0,eventType=void 0,pendingFragments.length=0,pendingFragmentsLength=0,terminated=!1}return{feed,reset}}function isDataPrefix(chunk,i,firstCharCode){return firstCharCode===100&&chunk.charCodeAt(i+1)===97&&chunk.charCodeAt(i+2)===116&&chunk.charCodeAt(i+3)===97&&chunk.charCodeAt(i+4)===58}function isEventPrefix(chunk,i,firstCharCode){return firstCharCode===101&&chunk.charCodeAt(i+1)===118&&chunk.charCodeAt(i+2)===101&&chunk.charCodeAt(i+3)===110&&chunk.charCodeAt(i+4)===116&&chunk.charCodeAt(i+5)===58}class EventSourceParserStream extends TransformStream{constructor({onError,onRetry,onComment,maxBufferSize}={}){let parser;super({start(controller){parser=createParser({onEvent:(event)=>{controller.enqueue(event)},onError(error2){typeof onError=="function"&&onError(error2),(onError==="terminate"||error2.type==="max-buffer-size-exceeded")&&controller.error(error2)},onRetry,onComment,maxBufferSize})},transform(chunk){parser.feed(chunk)}})}}var OAuthClientFlowError=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!=="function")throw 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(message){super(message);this.name=new.target.name,stampErrorBrands(this,new.target)}},IssuerMismatchError=class extends OAuthClientFlowError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(kind,expected,received){super(`Issuer mismatch in ${kind==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(expected)}, received ${JSON.stringify(received)}`);this.kind=kind,this.expected=expected,this.received=received}},RegistrationRejectedError=class extends OAuthClientFlowError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(args){super(`Dynamic Client Registration rejected (HTTP ${args.status}): ${args.body}`);this.status=args.status,this.body=args.body,this.submittedMetadata=args.submittedMetadata}},InsecureTokenEndpointError=class extends OAuthClientFlowError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(tokenEndpoint){super(`Refusing to send credentials to non-https token endpoint '${tokenEndpoint}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=tokenEndpoint}},AuthorizationServerMismatchError=class extends OAuthClientFlowError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(recordedIssuer,currentIssuer){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(recordedIssuer)} but this call resolved ${JSON.stringify(currentIssuer)}; refusing to present them to a different authorization server`);this.recordedIssuer=recordedIssuer,this.currentIssuer=currentIssuer}},InsufficientScopeError=class extends OAuthClientFlowError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(init){super(`Insufficient scope${init.requiredScope?`: required "${init.requiredScope}"`:""}`);this.requiredScope=init.requiredScope,this.resourceMetadataUrl=init.resourceMetadataUrl,this.errorDescription=init.errorDescription}};function discardIfIssuerMismatch(stored,issuer,opts){if(!stored)return;if(typeof stored.issuer!=="string"){if(opts?.canPersistStamp!==!1)console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.");return stored.issuer===void 0?stored:{...stored,issuer:void 0}}return issuersMatch(stored.issuer,issuer)?stored:void 0}function issuersMatch(a,b){return a===b||a.endsWith("/")&&a.slice(0,-1)===b||b.endsWith("/")&&b.slice(0,-1)===a}function isOAuthClientProvider(provider){if(provider==null)return!1;let p=provider;return typeof p.tokens==="function"&&typeof p.clientInformation==="function"}async function handleOAuthUnauthorized(provider,ctx,extraAuthOptions){let{resourceMetadataUrl,scope}=extractWWWAuthenticateParams(ctx.response);if(await auth(provider,{serverUrl:ctx.serverUrl,resourceMetadataUrl,scope,fetchFn:ctx.fetchFn,...extraAuthOptions})!=="AUTHORIZED")throw new UnauthorizedError}function adaptOAuthProvider(provider,extraAuthOptions){return{token:async()=>{return(await provider.tokens())?.access_token},onUnauthorized:async(ctx)=>handleOAuthUnauthorized(provider,ctx,extraAuthOptions)}}var UnauthorizedError=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!=="function")throw 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(message){super(message??"Unauthorized");this.name="UnauthorizedError",stampErrorBrands(this,new.target)}};function isIssParameterSupported(metadata){return metadata?.authorization_response_iss_parameter_supported===!0}function validateAuthorizationResponseIssuer({iss,expectedIssuer,issParameterSupported}){if(expectedIssuer===void 0)return;if(iss===void 0){if(issParameterSupported)throw new IssuerMismatchError("authorization_response",expectedIssuer,void 0);return}if(iss!==expectedIssuer)throw new IssuerMismatchError("authorization_response",expectedIssuer,iss)}function computeScopeUnion(...scopes){let seen=new Set;for(let scope of scopes){if(!scope)continue;for(let token of scope.split(/\s+/))if(token)seen.add(token)}return seen.size>0?[...seen].join(" "):void 0}function isStrictScopeSuperset(union2,current){if(!union2)return!1;let currentSet=new Set((current??"").split(/\s+/).filter(Boolean));for(let token of union2.split(/\s+/))if(token&&!currentSet.has(token))return!0;return!1}async function resolveAuthorizationCallbackParams(codeOrParams,iss,provider,serverUrl,opts){if(typeof codeOrParams==="string")return{authorizationCode:codeOrParams,iss};let issParam=codeOrParams.get("iss")??void 0,code=codeOrParams.get("code");if(code)return{authorizationCode:code,iss:issParam};let metadata=(await provider.discoveryState?.())?.authorizationServerMetadata;if(!metadata)try{metadata=(await discoverOAuthServerInfo(serverUrl,opts)).authorizationServerMetadata}catch{metadata=void 0}if(!metadata)throw new UnauthorizedError("Authorization callback failed and the issuer could not be verified");validateAuthorizationResponseIssuer({iss:issParam,expectedIssuer:metadata.issuer,issParameterSupported:isIssParameterSupported(metadata)});let error2=codeOrParams.get("error");if(error2)throw new OAuthError(error2,codeOrParams.get("error_description")??error2,codeOrParams.get("error_uri")??void 0);throw new UnauthorizedError("Authorization callback contained neither `code` nor `error`")}function isClientAuthMethod(method){return["client_secret_basic","client_secret_post","none"].includes(method)}var AUTHORIZATION_CODE_RESPONSE_TYPE="code",AUTHORIZATION_CODE_CHALLENGE_METHOD="S256";function selectClientAuthMethod(clientInformation,supportedMethods){let hasClientSecret=clientInformation.client_secret!==void 0;if("token_endpoint_auth_method"in clientInformation&&clientInformation.token_endpoint_auth_method&&isClientAuthMethod(clientInformation.token_endpoint_auth_method)&&(supportedMethods.length===0||supportedMethods.includes(clientInformation.token_endpoint_auth_method)))return clientInformation.token_endpoint_auth_method;if(supportedMethods.length===0)return hasClientSecret?"client_secret_basic":"none";if(hasClientSecret&&supportedMethods.includes("client_secret_basic"))return"client_secret_basic";if(hasClientSecret&&supportedMethods.includes("client_secret_post"))return"client_secret_post";if(supportedMethods.includes("none"))return"none";return hasClientSecret?"client_secret_post":"none"}function applyClientAuthentication(method,clientInformation,headers,params){let{client_id,client_secret}=clientInformation;switch(method){case"client_secret_basic":applyBasicAuth(client_id,client_secret,headers);return;case"client_secret_post":applyPostAuth(client_id,client_secret,params);return;case"none":applyPublicAuth(client_id,params);return;default:throw Error(`Unsupported client authentication method: ${method}`)}}function applyBasicAuth(clientId,clientSecret,headers){if(!clientSecret)throw Error("client_secret_basic authentication requires a client_secret");let credentials=btoa(`${clientId}:${clientSecret}`);headers.set("Authorization",`Basic ${credentials}`)}function applyPostAuth(clientId,clientSecret,params){if(params.set("client_id",clientId),clientSecret)params.set("client_secret",clientSecret)}function applyPublicAuth(clientId,params){params.set("client_id",clientId)}function isLoopbackHost(hostname){return hostname==="localhost"||hostname.endsWith(".localhost")||hostname==="127.0.0.1"||hostname==="[::1]"||hostname==="::1"}function assertSecureTokenEndpoint(tokenEndpoint){let url2=new URL(String(tokenEndpoint));if(url2.protocol!=="https:"&&!isLoopbackHost(url2.hostname))throw new InsecureTokenEndpointError(url2.href);return url2}function deriveApplicationType(redirectUris){for(let raw of redirectUris??[]){let url2;try{url2=new URL(raw)}catch{continue}if(url2.protocol!=="http:"&&url2.protocol!=="https:")return"native";if(isLoopbackHost(url2.hostname))return"native"}return"web"}function resolveClientMetadata(provider){let clientMetadata=provider.clientMetadata;return{...clientMetadata,grant_types:clientMetadata.grant_types??(provider.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:clientMetadata.application_type??deriveApplicationType(clientMetadata.redirect_uris)}}async function parseErrorResponse(input){let statusCode=input instanceof Response?input.status:void 0,body=input instanceof Response?await input.text():input;try{let result=OAuthErrorResponseSchema.parse(JSON.parse(body));return OAuthError.fromResponse(result)}catch(error2){let errorMessage=`${statusCode?`HTTP ${statusCode}: `:""}Invalid OAuth error response: ${error2}. Raw body: ${body}`;return new OAuthError(OAuthErrorCode.ServerError,errorMessage)}}function warnCredentialInvalidation(provider,error2,invalidated){let action=provider.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${invalidated} (provider implements no invalidateCredentials())`:`invalidating the stored ${invalidated} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(error2.code)} — ${action}. Cause: ${JSON.stringify(error2.message)}`)}async function auth(provider,options){try{return await authInternal(provider,options)}catch(error2){if(error2 instanceof OAuthError){if(error2.code===OAuthErrorCode.InvalidClient||error2.code===OAuthErrorCode.UnauthorizedClient)return warnCredentialInvalidation(provider,error2,"client credentials and tokens"),await provider.invalidateCredentials?.("client"),await provider.invalidateCredentials?.("tokens"),await authInternal(provider,options);else if(error2.code===OAuthErrorCode.InvalidGrant||error2.code===OAuthErrorCode.InvalidDpopProof)return warnCredentialInvalidation(provider,error2,"tokens"),await provider.invalidateCredentials?.("tokens"),await authInternal(provider,options)}throw error2}}function determineScope(options){let{requestedScope,resourceMetadata,authServerMetadata,clientMetadata}=options,effectiveScope=requestedScope||resourceMetadata?.scopes_supported?.join(" ")||clientMetadata.scope;if(effectiveScope&&authServerMetadata?.scopes_supported?.includes("offline_access")&&!effectiveScope.split(" ").includes("offline_access")&&clientMetadata.grant_types?.includes("refresh_token"))effectiveScope=`${effectiveScope} offline_access`;return effectiveScope}async function authInternal(provider,{serverUrl,authorizationCode,iss,scope,resourceMetadataUrl,fetchFn,skipIssuerMetadataValidation,forceReauthorization}){let clientMetadata=resolveClientMetadata(provider),cachedState=await provider.discoveryState?.(),resourceMetadata,authorizationServerUrl,metadata,freshDiscoveryState,effectiveResourceMetadataUrl=resourceMetadataUrl;if(!effectiveResourceMetadataUrl&&cachedState?.resourceMetadataUrl)effectiveResourceMetadataUrl=new URL(cachedState.resourceMetadataUrl);if(cachedState?.authorizationServerUrl){if(authorizationServerUrl=cachedState.authorizationServerUrl,resourceMetadata=cachedState.resourceMetadata,metadata=cachedState.authorizationServerMetadata??await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn,skipIssuerValidation:skipIssuerMetadataValidation}),!resourceMetadata)try{resourceMetadata=await discoverOAuthProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:effectiveResourceMetadataUrl},fetchFn)}catch(error2){if(error2 instanceof TypeError)throw error2}if(metadata!==cachedState.authorizationServerMetadata||resourceMetadata!==cachedState.resourceMetadata)await provider.saveDiscoveryState?.({authorizationServerUrl:String(authorizationServerUrl),resourceMetadataUrl:effectiveResourceMetadataUrl?.toString(),resourceMetadata,authorizationServerMetadata:metadata})}else{let serverInfo=await discoverOAuthServerInfo(serverUrl,{resourceMetadataUrl:effectiveResourceMetadataUrl,fetchFn,skipIssuerMetadataValidation});authorizationServerUrl=serverInfo.authorizationServerUrl,metadata=serverInfo.authorizationServerMetadata,resourceMetadata=serverInfo.resourceMetadata,freshDiscoveryState={authorizationServerUrl:String(authorizationServerUrl),resourceMetadataUrl:effectiveResourceMetadataUrl?.toString(),resourceMetadata,authorizationServerMetadata:metadata}}let issuer=metadata?.issuer??String(authorizationServerUrl),infoCtx={issuer};if(await provider.saveAuthorizationServerUrl?.(issuer),authorizationCode!==void 0){let recordedIssuer=cachedState?.authorizationServerMetadata?.issuer??cachedState?.authorizationServerUrl;if(recordedIssuer===void 0){if(provider.saveDiscoveryState!==void 0)throw new AuthorizationServerMismatchError("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",issuer);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.")}else if(!issuersMatch(recordedIssuer,issuer))throw new AuthorizationServerMismatchError(recordedIssuer,issuer)}if(freshDiscoveryState)await provider.saveDiscoveryState?.(freshDiscoveryState);let selectedResource=await selectResourceURL(serverUrl,provider,resourceMetadata),resource=selectedResource&&resourceMetadata&&!provider.validateResourceURL?resourceMetadata.resource:selectedResource;if(resource)await provider.saveResourceUrl?.(resourceIndicatorToString(resource));let resolvedScope=determineScope({requestedScope:scope,resourceMetadata,authServerMetadata:metadata,clientMetadata:provider.clientMetadata}),rawClientInfo=await Promise.resolve(provider.clientInformation(infoCtx)),clientInformation=discardIfIssuerMismatch(rawClientInfo,issuer,{canPersistStamp:provider.saveClientInformation!==void 0});if(clientInformation===void 0&&rawClientInfo?.issuer&&provider.saveClientInformation===void 0)throw new AuthorizationServerMismatchError(rawClientInfo.issuer,issuer);if(clientInformation&&clientInformation.issuer===void 0)clientInformation={...clientInformation,issuer},await provider.saveClientInformation?.(clientInformation,infoCtx);if(!clientInformation){if(authorizationCode!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let supportsUrlBasedClientId=metadata?.client_id_metadata_document_supported===!0,clientMetadataUrl=provider.clientMetadataUrl;if(clientMetadataUrl&&!isHttpsUrl(clientMetadataUrl))throw new OAuthError(OAuthErrorCode.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);if(supportsUrlBasedClientId&&clientMetadataUrl)clientInformation={client_id:clientMetadataUrl,issuer},await provider.saveClientInformation?.(clientInformation,infoCtx);else{if(!provider.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");clientInformation={...await registerClient(authorizationServerUrl,{metadata,clientMetadata,scope:resolvedScope,fetchFn}),issuer},await provider.saveClientInformation(clientInformation,infoCtx)}}let nonInteractiveFlow=!provider.redirectUrl;if(authorizationCode!==void 0||nonInteractiveFlow){if(authorizationCode!==void 0)validateAuthorizationResponseIssuer({iss,expectedIssuer:metadata?.issuer,issParameterSupported:isIssParameterSupported(metadata)});let tokens$1=await fetchToken(provider,authorizationServerUrl,{metadata,resource,authorizationCode,iss,scope:resolvedScope,fetchFn});return await provider.saveTokens({...tokens$1,issuer},infoCtx),"AUTHORIZED"}let tokens=discardIfIssuerMismatch(await provider.tokens(infoCtx),issuer);if(tokens&&tokens.issuer===void 0)tokens={...tokens,issuer},await provider.saveTokens(tokens,infoCtx);if(tokens?.refresh_token&&!forceReauthorization){let newTokens;try{newTokens=await refreshAuthorization(authorizationServerUrl,{metadata,clientInformation,refreshToken:tokens.refresh_token,resource,addClientAuthentication:provider.addClientAuthentication,dpop:await provider.dpop?.(),fetchFn})}catch(error2){if(error2 instanceof InsecureTokenEndpointError)throw error2;if(!(error2 instanceof OAuthError)||error2.code===OAuthErrorCode.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(error2 instanceof Error?error2.message:String(error2))}`);else throw error2}if(newTokens)return await provider.saveTokens({...newTokens,issuer},infoCtx),"AUTHORIZED"}let state=provider.state?await provider.state():void 0,{authorizationUrl,codeVerifier}=await startAuthorization(authorizationServerUrl,{metadata,clientInformation,state,redirectUrl:provider.redirectUrl,scope:resolvedScope,resource});return await provider.saveCodeVerifier(codeVerifier),await provider.redirectToAuthorization(authorizationUrl),"REDIRECT"}function isHttpsUrl(value){if(!value)return!1;try{let url2=new URL(value);return url2.protocol==="https:"&&url2.pathname!=="/"}catch{return!1}}async function selectResourceURL(serverUrl,provider,resourceMetadata){let defaultResource=resourceUrlFromServerUrl(serverUrl);if(provider.validateResourceURL)return await provider.validateResourceURL(defaultResource,resourceMetadata?.resource);if(!resourceMetadata)return;if(!checkResourceAllowed({requestedResource:defaultResource,configuredResource:resourceMetadata.resource}))throw Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);return new URL(resourceMetadata.resource)}var RECOGNIZED_CHALLENGE_SCHEMES=new Set(["bearer","dpop"]);function extractWWWAuthenticateParams(res){let authenticateHeader=res.headers.get("WWW-Authenticate");if(!authenticateHeader)return{};let[type,scheme]=authenticateHeader.split(" ");if(!type||!RECOGNIZED_CHALLENGE_SCHEMES.has(type.toLowerCase())||!scheme)return{};let resourceMetadataMatch=extractFieldFromWwwAuth(res,"resource_metadata")||void 0,resourceMetadataUrl;if(resourceMetadataMatch)try{resourceMetadataUrl=new URL(resourceMetadataMatch)}catch{}let scope=extractFieldFromWwwAuth(res,"scope")||void 0,error2=extractFieldFromWwwAuth(res,"error")||void 0,errorDescription=extractFieldFromWwwAuth(res,"error_description")||void 0;return{resourceMetadataUrl,scope,error:error2,errorDescription}}function extractFieldFromWwwAuth(response,fieldName){let wwwAuthHeader=response.headers.get("WWW-Authenticate");if(!wwwAuthHeader)return null;let pattern=new RegExp(String.raw`${fieldName}=(?:"([^"]+)"|([^\s,]+))`),match=wwwAuthHeader.match(pattern);if(match){let result=match[1]||match[2];if(result)return result}return null}async function discoverOAuthProtectedResourceMetadata(serverUrl,opts,fetchFn=fetch){let response=await discoverMetadataWithFallback(serverUrl,"oauth-protected-resource",fetchFn,{protocolVersion:opts?.protocolVersion,metadataUrl:opts?.resourceMetadataUrl});if(!response||response.status===404)throw await response?.text?.().catch(()=>{}),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!response.ok)throw await response.text?.().catch(()=>{}),Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);return OAuthProtectedResourceMetadataSchema.parse(await response.json())}async function fetchWithCorsRetry(url2,headers,fetchFn=fetch){let withinOrigin=fetchWithinOrigin(fetchFn);try{return await withinOrigin(url2,{headers})}catch(error2){if(!(error2 instanceof TypeError)||!CORS_IS_POSSIBLE)throw error2;if(headers)try{return await withinOrigin(url2,{})}catch(retryError){if(!(retryError instanceof TypeError))throw retryError;return}return}}function buildWellKnownPath(wellKnownPrefix,pathname="",options={}){if(pathname.endsWith("/"))pathname=pathname.slice(0,-1);return options.prependPathname?`${pathname}/.well-known/${wellKnownPrefix}`:`/.well-known/${wellKnownPrefix}${pathname}`}async function tryMetadataDiscovery(url2,protocolVersion,fetchFn=fetch){return await fetchWithCorsRetry(url2,{"MCP-Protocol-Version":protocolVersion},fetchFn)}function shouldAttemptFallback(response,pathname){if(!response)return!0;if(pathname==="/")return!1;return!response.ok&&response.status<500||response.status===502}async function discoverMetadataWithFallback(serverUrl,wellKnownType,fetchFn,opts){let issuer=new URL(serverUrl),protocolVersion=opts?.protocolVersion??LATEST_PROTOCOL_VERSION,url2;if(opts?.metadataUrl)url2=new URL(opts.metadataUrl);else{let wellKnownPath=buildWellKnownPath(wellKnownType,issuer.pathname);url2=new URL(wellKnownPath,opts?.metadataServerUrl??issuer),url2.search=issuer.search}let response=await tryMetadataDiscovery(url2,protocolVersion,fetchFn);if(!opts?.metadataUrl&&shouldAttemptFallback(response,issuer.pathname))response=await tryMetadataDiscovery(new URL(`/.well-known/${wellKnownType}`,issuer),protocolVersion,fetchFn);return response}function buildDiscoveryUrls(authorizationServerUrl){let url2=typeof authorizationServerUrl==="string"?new URL(authorizationServerUrl):authorizationServerUrl,hasPath=url2.pathname!=="/",urlsToTry=[];if(!hasPath)return urlsToTry.push({url:new URL("/.well-known/oauth-authorization-server",url2.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",url2.origin),type:"oidc"}),urlsToTry;let pathname=url2.pathname;if(pathname.endsWith("/"))pathname=pathname.slice(0,-1);return urlsToTry.push({url:new URL(`/.well-known/oauth-authorization-server${pathname}`,url2.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${pathname}`,url2.origin),type:"oidc"},{url:new URL(`${pathname}/.well-known/openid-configuration`,url2.origin),type:"oidc"}),urlsToTry}async function discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn=fetch,protocolVersion=LATEST_PROTOCOL_VERSION,skipIssuerValidation=!1}={}){let headers={"MCP-Protocol-Version":protocolVersion,Accept:"application/json"},urlsToTry=buildDiscoveryUrls(authorizationServerUrl);for(let{url:endpointUrl,type}of urlsToTry){let response=await fetchWithCorsRetry(endpointUrl,headers,fetchFn);if(!response)continue;if(!response.ok){if(await response.text?.().catch(()=>{}),response.status<500||response.status===502)continue;throw Error(`HTTP ${response.status} trying to load ${type==="oauth"?"OAuth":"OpenID provider"} metadata from ${endpointUrl}`)}let parsed=type==="oauth"?OAuthMetadataSchema.parse(await response.json()):OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());if(!skipIssuerValidation){let expectedIssuer=typeof authorizationServerUrl==="string"?authorizationServerUrl:authorizationServerUrl.href;if(!(parsed.issuer===expectedIssuer||expectedIssuer.endsWith("/")&&parsed.issuer===expectedIssuer.slice(0,-1)))throw new IssuerMismatchError("metadata",expectedIssuer,parsed.issuer)}return parsed}}async function discoverOAuthServerInfo(serverUrl,opts){let resourceMetadata,authorizationServerUrl;try{if(resourceMetadata=await discoverOAuthProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:opts?.resourceMetadataUrl},opts?.fetchFn),resourceMetadata.authorization_servers&&resourceMetadata.authorization_servers.length>0)authorizationServerUrl=resourceMetadata.authorization_servers[0]}catch(error2){if(error2 instanceof TypeError)throw error2}if(!authorizationServerUrl)authorizationServerUrl=String(new URL("/",serverUrl));let authorizationServerMetadata=await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn:opts?.fetchFn,skipIssuerValidation:opts?.skipIssuerMetadataValidation});return{authorizationServerUrl,authorizationServerMetadata,resourceMetadata}}function resourceIndicatorToString(resource){return typeof resource==="string"?resource:resource.href}async function startAuthorization(authorizationServerUrl,{metadata,clientInformation,redirectUrl,scope,state,resource}){let authorizationUrl;if(metadata){if(authorizationUrl=new URL(metadata.authorization_endpoint),!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE))throw Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);if(metadata.code_challenge_methods_supported&&!metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD))throw Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`)}else authorizationUrl=new URL("/authorize",authorizationServerUrl);let challenge=await pkceChallenge(),codeVerifier=challenge.code_verifier,codeChallenge=challenge.code_challenge;if(authorizationUrl.searchParams.set("response_type",AUTHORIZATION_CODE_RESPONSE_TYPE),authorizationUrl.searchParams.set("client_id",clientInformation.client_id),authorizationUrl.searchParams.set("code_challenge",codeChallenge),authorizationUrl.searchParams.set("code_challenge_method",AUTHORIZATION_CODE_CHALLENGE_METHOD),authorizationUrl.searchParams.set("redirect_uri",String(redirectUrl)),state)authorizationUrl.searchParams.set("state",state);if(scope)authorizationUrl.searchParams.set("scope",scope);if(scope?.split(" ").includes("offline_access"))authorizationUrl.searchParams.append("prompt","consent");if(resource)authorizationUrl.searchParams.set("resource",resourceIndicatorToString(resource));return{authorizationUrl,codeVerifier}}function prepareAuthorizationCodeRequest(authorizationCode,codeVerifier,redirectUri){return new URLSearchParams({grant_type:"authorization_code",code:authorizationCode,code_verifier:codeVerifier,redirect_uri:String(redirectUri)})}async function executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication,resource,dpop,fetchFn}){let tokenUrl=assertSecureTokenEndpoint(metadata?.token_endpoint??new URL("/token",authorizationServerUrl)),headers=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(resource)tokenRequestParams.set("resource",resourceIndicatorToString(resource));if(!addClientAuthentication&&clientInformation)applyClientAuthentication(selectClientAuthMethod(clientInformation,metadata?.token_endpoint_auth_methods_supported??[]),clientInformation,headers,tokenRequestParams);let requestOnce=async()=>{let requestHeaders=new Headers(headers);if(addClientAuthentication)await addClientAuthentication(requestHeaders,tokenRequestParams,tokenUrl,metadata);if(dpop)requestHeaders.set("DPoP",await dpop.buildProof({htm:"POST",htu:tokenUrl}));return fetchWithinOrigin(fetchFn??fetch)(tokenUrl,{method:"POST",headers:requestHeaders,body:tokenRequestParams})},response=await requestOnce();if(dpop&&response.status===400){if((await response.clone().json().catch(()=>{}))?.error===OAuthErrorCode.UseDpopNonce)dpop.observeNonce(response,tokenUrl),response=await requestOnce()}if(dpop?.observeNonce(response,tokenUrl),!response.ok)throw await parseErrorResponse(response);let json=await response.json();try{return OAuthTokensSchema.parse(withoutIssuer(json))}catch(parseError){if(typeof json==="object"&&json!==null&&"error"in json)throw await parseErrorResponse(JSON.stringify(json));throw parseError}}async function refreshAuthorization(authorizationServerUrl,{metadata,clientInformation,refreshToken,resource,addClientAuthentication,dpop,fetchFn}){return{refresh_token:refreshToken,...await executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:refreshToken}),clientInformation,addClientAuthentication,resource,dpop,fetchFn})}}async function fetchToken(provider,authorizationServerUrl,{metadata,resource,authorizationCode,iss,scope,fetchFn}={}){if(authorizationCode!==void 0)validateAuthorizationResponseIssuer({iss,expectedIssuer:metadata?.issuer,issParameterSupported:isIssParameterSupported(metadata)});let issuer=metadata?.issuer??String(authorizationServerUrl),readClientInformation=async()=>{let rawClientInfo=await provider.clientInformation({issuer}),checked=discardIfIssuerMismatch(rawClientInfo,issuer,{canPersistStamp:!1});if(rawClientInfo&&checked===void 0)throw new AuthorizationServerMismatchError(String(rawClientInfo.issuer),issuer);return checked},clientInformation=await readClientInformation(),effectiveScope=scope??provider.clientMetadata.scope,tokenRequestParams;if(provider.prepareTokenRequest)tokenRequestParams=await provider.prepareTokenRequest(effectiveScope);if(!tokenRequestParams){if(!authorizationCode)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!provider.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");tokenRequestParams=prepareAuthorizationCodeRequest(authorizationCode,await provider.codeVerifier(),provider.redirectUrl)}return clientInformation??=await readClientInformation(),executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication:provider.addClientAuthentication,resource,dpop:await provider.dpop?.(),fetchFn})}async function registerClient(authorizationServerUrl,{metadata,clientMetadata,scope,fetchFn}){let registrationUrl;if(metadata){if(!metadata.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");registrationUrl=new URL(metadata.registration_endpoint)}else registrationUrl=new URL("/register",authorizationServerUrl);let submittedMetadata={...clientMetadata,...scope===void 0?{}:{scope}},response=await fetchWithinOrigin(fetchFn??fetch)(registrationUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(submittedMetadata)});if(!response.ok)throw new RegistrationRejectedError({status:response.status,body:await response.text(),submittedMetadata});return OAuthClientInformationFullSchema.parse(withoutIssuer(await response.json()))}var CAP_EXEMPT_METHODS=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),InMemoryResponseCacheStore=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(options){this._maxEntries=options?.maxEntries??512}get size(){return this._entries.size}get(key){return this._entries.get(keyOf(key))}set(key,entry){let k=keyOf(key),exempt=CAP_EXEMPT_METHODS.has(key.method),isNew=!this._entries.has(k);if(!exempt&&isNew&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let oldKey of this._entries.keys())if(!CAP_EXEMPT_METHODS.has(oldKey.slice(0,oldKey.indexOf("\x00")))){this._entries.delete(oldKey),this._cappedSize--;break}}let stamp=++this._stamp;if(this._entries.set(k,{...entry,stamp}),isNew&&!exempt)this._cappedSize++;return stamp}delete(key){if(this._entries.delete(keyOf(key))&&!CAP_EXEMPT_METHODS.has(key.method))this._cappedSize--}evict(method){let prefix=`${method}\x00`,exempt=CAP_EXEMPT_METHODS.has(method);for(let k of this._entries.keys())if(k.startsWith(prefix)){if(this._entries.delete(k),!exempt)this._cappedSize--}}clear(){this._entries.clear(),this._cappedSize=0}};function keyOf(key){return`${key.method}\x00${JSON.stringify([key.partition??"",key.params??""])}`}function genKey(method,params){return params===void 0?method:`${method}\x00${params}`}var MAX_CACHE_TTL_MS=86400000,ClientResponseCache=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(_store,_isUserSupplied,_reportError=()=>{},_cachePartition="",_now=Date.now){this._store=_store,this._isUserSupplied=_isUserSupplied,this._reportError=_reportError,this._cachePartition=_cachePartition,this._now=_now}now(){return this._now()}setServerIdentity(identity){this._serverIdentity=identity}_partitionFor(scope){return JSON.stringify([this._serverIdentity,scope==="public"?"":this._cachePartition])}async _probe(method,params){let key={method,params:params??""},ownPartition=this._partitionFor("private"),own2=await this._store.get({...key,partition:ownPartition});if(own2!==void 0)return own2;let sharedPartition=this._partitionFor("public");if(sharedPartition===ownPartition)return;let shared=await this._store.get({...key,partition:sharedPartition});return shared?.scope==="public"?shared:void 0}async evict(method){this._evictionGeneration.set(method,(this._evictionGeneration.get(method)??0)+1),await this._deleteBoth(method,"")}async _deleteBoth(method,params){let ownPartition=this._partitionFor("private"),sharedPartition=this._partitionFor("public");try{await this._store.delete({method,params,partition:ownPartition})}catch(error2){this._reportError(error2)}if(sharedPartition!==ownPartition)try{await this._store.delete({method,params,partition:sharedPartition})}catch(error2){this._reportError(error2)}}async evictKey(method,params){let gk=genKey(method,params),current=this._evictionGeneration.get(gk);if(current!==void 0)this._evictionGeneration.set(gk,current+1);await this._deleteBoth(method,params)}captureGeneration(method,params){let gk=genKey(method,params),current=this._evictionGeneration.get(gk)??0;return this._evictionGeneration.set(gk,current),current}async write(method,value,capturedGen,freshness){if((this._evictionGeneration.get(genKey(method,freshness?.params))??0)!==capturedGen)return;let params=freshness?.params??"",ownPartition=this._partitionFor("private"),sharedPartition=this._partitionFor("public"),partition=(freshness?.scope??"private")==="public"?sharedPartition:ownPartition;try{await this._store.set({method,params,partition},{value:encodeCacheValue(value),expiresAt:freshness?.expiresAt,scope:freshness?.scope})}catch(error2){this._reportError(error2)}if(sharedPartition!==ownPartition)try{await this._store.delete({method,params,partition:partition===ownPartition?sharedPartition:ownPartition})}catch(error2){this._reportError(error2)}}async read(method,params){let entry=await this._probe(method,params);if(entry?.expiresAt===void 0||!(entry.expiresAt>this.now()))return;try{let parsed=JSON.parse(entry.value);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))throw TypeError("cached document is not an object");return{value:parsed}}catch(error2){this._reportError(error2),await this._deleteBoth(method,params??"");return}}resetForReconnect(){if(!this._isUserSupplied)this._store.clear();this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(name){let entry=await this._probe("tools/list");if(entry===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==entry.stamp){let list=this._decodeListTools(entry),byName=new Map;if(list!==void 0)for(let tool of list.tools)byName.set(tool.name,tool);this._toolIndex={stamp:entry.stamp,byName}}return this._toolIndex.byName.get(name)}async outputValidator(name,compile3){let entry=await this._probe("tools/list");if(entry===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==entry.stamp){let list=this._decodeListTools(entry)??{tools:[]},byName=new Map;for(let tool of list.tools){let compiled=compile3(tool);if(compiled!==void 0)byName.set(tool.name,compiled)}this._toolOutputValidatorIndex={stamp:entry.stamp,byName}}return this._toolOutputValidatorIndex.byName.get(name)}_decodeListTools(entry){try{let parsed=JSON.parse(entry.value);if(!Array.isArray(parsed?.tools)||!parsed.tools.every((t)=>t!==null&&typeof t==="object"))throw TypeError("cached tools/list document has a malformed tools array");return parsed}catch(error2){this._reportError(error2);return}}};function encodeCacheValue(value){let json;try{json=JSON.stringify(value)}catch(error2){throw TypeError(`cache value is not JSON-serializable: ${error2 instanceof Error?error2.message:String(error2)}`)}if(typeof json!=="string")throw TypeError("cache value is not JSON-serializable: it has no JSON representation");return json}var AUTH_SEAM=Symbol.for("mcp.authSeamEscape");function markAuthSeamEscape(error2){if(typeof error2==="object"&&error2!==null||typeof error2==="function")try{Object.defineProperty(error2,AUTH_SEAM,{value:!0,configurable:!0})}catch{}return error2}function isAuthSeamEscape(error2){return(typeof error2==="object"&&error2!==null||typeof error2==="function")&&error2[AUTH_SEAM]===!0}var UNSUPPORTED_PROTOCOL_VERSION=-32022,NOT_PROBE_RECOGNIZED=new Set([-32001,-32020,-32021]);function classifyProbeOutcome(outcome,context){switch(outcome.kind){case"result":return classifyResult(outcome.result,context);case"rpc-error":return classifyRpcError(outcome,context);case"http-error":return classifyHttpError(outcome,context);case"network-error":return classifyNetworkError(outcome.error,context);case"unusable-reply":return{kind:"error",error:new SdkError(SdkErrorCode.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${describeError(outcome.error)})`,{cause:outcome.error},{cause:outcome.error})};case"auth-required":return{kind:"error",error:outcome.error};case"closed":if(context.transportKind==="stdio")return{kind:"legacy"};return classifyNetworkError(Error("Connection closed during the version negotiation probe"),context);case"timeout":if(context.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new SdkError(SdkErrorCode.RequestTimeout,`Version negotiation probe timed out after ${outcome.timeoutMs}ms`,{timeout:outcome.timeoutMs})}}}function classifyResult(result,context){let parsed=codecForVersion(MODERN_WIRE_REVISION).validateResult("server/discover",result);if(!parsed.ok)return{kind:"legacy"};let supportedVersions=parsed.value.supportedVersions,overlap=context.clientModernVersions.find((version2)=>supportedVersions.includes(version2));if(overlap!==void 0)return{kind:"modern",version:overlap,discover:parsed.value};if(context.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new UnsupportedProtocolVersionError({supported:[...supportedVersions],requested:context.requestedVersion})}}function classifyRpcError(outcome,context){let{code,message,data}=outcome;if(code===UNSUPPORTED_PROTOCOL_VERSION){let supported=parseSupportedList(data);if(supported===void 0)return{kind:"legacy"};let error2=new UnsupportedProtocolVersionError({supported,requested:parseRequested(data)??context.requestedVersion},message),supportedModern=modernProtocolVersions(supported),mutual=context.clientModernVersions.find((version2)=>supportedModern.includes(version2));if(mutual!==void 0)return{kind:"corrective",version:mutual,error:error2};if(supportedModern.length>0)return{kind:"error",error:error2};return context.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:error2}}if(NOT_PROBE_RECOGNIZED.has(code))return{kind:"legacy"};return{kind:"legacy"}}function classifyHttpError(outcome,context){if(outcome.status===401||outcome.status===403){let isDenial=outcome.status===403;return{kind:"error",error:new SdkHttpError(isDenial?SdkErrorCode.ClientHttpForbidden:SdkErrorCode.ClientHttpAuthentication,`Version negotiation failed: ${isDenial?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:outcome.status,statusText:outcome.statusText,text:outcome.body})}}if(outcome.status>=500)return{kind:"error",error:new SdkHttpError(SdkErrorCode.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${outcome.status}`,{status:outcome.status,statusText:outcome.statusText,text:outcome.body})};let rpcError=parseJsonRpcErrorBody(outcome.body);if(rpcError!==void 0)return classifyRpcError(rpcError,context);return{kind:"legacy"}}function classifyNetworkError(error2,context){if(context.environment==="browser"&&isOpaqueFetchTypeError(error2))return{kind:"legacy"};return{kind:"error",error:new SdkError(SdkErrorCode.EraNegotiationFailed,`Version negotiation probe failed: ${describeError(error2)}`,{cause:error2},{cause:error2})}}function isOpaqueFetchTypeError(error2){return error2 instanceof TypeError||error2 instanceof Error&&error2.name==="TypeError"}function describeError(error2){return error2 instanceof Error?error2.message:String(error2)}function parseSupportedList(data){if(typeof data!=="object"||data===null)return;let supported=data.supported;if(!Array.isArray(supported)||supported.length===0||!supported.every((v)=>typeof v==="string"))return;return supported}function parseRequested(data){if(typeof data!=="object"||data===null)return;let requested=data.requested;return typeof requested==="string"?requested:void 0}function parseJsonRpcErrorBody(body){if(body===void 0||body==="")return;let parsed;try{parsed=JSON.parse(body)}catch{return}if(typeof parsed!=="object"||parsed===null)return;let error2=parsed.error;if(typeof error2!=="object"||error2===null)return;let{code,message,data}=error2;if(typeof code!=="number")return;return{code,message:typeof message==="string"?message:"",data}}var DEFAULT_VERSION_NEGOTIATION_MODE="legacy";function resolveVersionNegotiation(options,supportedProtocolVersionsOption){let mode=options?.mode??DEFAULT_VERSION_NEGOTIATION_MODE;if(mode==="legacy")return{kind:"legacy"};let probe=options?.probe??{};if(typeof mode==="object"){if(!isModernProtocolVersion(mode.pin))throw TypeError(`versionNegotiation: { pin: '${mode.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:mode.pin,probe}}let explicitModern=supportedProtocolVersionsOption?modernProtocolVersions(supportedProtocolVersionsOption):[];return{kind:"auto",modernVersions:explicitModern.length>0?explicitModern:[...SUPPORTED_MODERN_PROTOCOL_VERSIONS],fallbackAvailable:supportedProtocolVersionsOption?legacyProtocolVersions(supportedProtocolVersionsOption).length>0:!0,probe}}function detectProbeEnvironment(){let g=globalThis;return g.window!==void 0&&g.document!==void 0?"browser":"node"}function detectProbeTransportKind(transport){return"stderr"in transport&&"pid"in transport?"stdio":"http"}var ProbeWindow=class ProbeWindow2{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(_transport){this._transport=_transport,this._savedOnMessage=_transport.onmessage,this._savedOnError=_transport.onerror,this._savedOnClose=_transport.onclose}static async open(transport){let window=new ProbeWindow2(transport);transport.onmessage=(message)=>{let pending=window._pending;if(pending!==void 0&&(isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message))&&message.id===pending.id){if(window._pending=void 0,isJSONRPCResultResponse(message))pending.resolve({kind:"response",result:message.result});else pending.resolve({kind:"response",error:message.error});return}},transport.onerror=(error2)=>{window._savedOnError?.(error2)},transport.onclose=()=>{let pending=window._pending;if(pending!==void 0)window._pending=void 0,pending.resolve({kind:"closed"});window._closeDelivered=!0,window._savedOnClose?.()};try{await transport.start()}catch(error2){throw window.detach(),error2}return window}async exchange(buildRequest,timeoutMs){let id=`server-discover-probe-${++this._probeCounter}`;return new Promise((resolve)=>{let settled=!1,settle2=(reply)=>{if(settled)return;if(settled=!0,clearTimeout(timer),this._pending?.id===id)this._pending=void 0;resolve(reply)},timer=setTimeout(()=>settle2({kind:"timeout"}),timeoutMs);this._pending={id,resolve:settle2},this._transport.send(buildRequest(id)).catch((error2)=>settle2({kind:"send-error",error:error2}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let saved=this._savedOnClose,transport=this._transport,spent=!1,wrapper=()=>{if(!spent){spent=!0;return}saved()};transport.onclose=wrapper,pendingSpentCloseGuards.set(transport,()=>{if(transport.onclose===wrapper)transport.onclose=saved})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let transport=this._transport,originalStart=transport.start,armed=!0;transport.start=async function(){if(armed){armed=!1,transport.start=originalStart;return}return originalStart.call(transport)}}},pendingSpentCloseGuards=new WeakMap;function disarmSpentCloseGuard(transport){let disarm=pendingSpentCloseGuards.get(transport);pendingSpentCloseGuards.delete(transport),disarm?.()}function buildProbeRequest(id,protocolVersion,clientInfo,capabilities){return{jsonrpc:"2.0",id,method:"server/discover",params:{_meta:codecForVersion(protocolVersion).outboundEnvelope({protocolVersion,clientInfo,clientCapabilities:capabilities})}}}function isUnusableReplyError(error2){if(error2 instanceof SdkError&&error2.code===SdkErrorCode.ClientHttpUnexpectedContent)return!0;return error2 instanceof Error&&error2.name==="SyntaxError"}function normalizeReply(reply,timeoutMs){switch(reply.kind){case"response":return reply.error===void 0?{kind:"result",result:reply.result}:{kind:"rpc-error",...reply.error};case"send-error":{let error2=reply.error;if(isAuthSeamEscape(error2)||error2 instanceof UnauthorizedError||error2 instanceof Error&&error2.name==="UnauthorizedError")return{kind:"auth-required",error:error2};if(error2 instanceof SdkHttpError){let text=error2.data?.text;return{kind:"http-error",status:error2.data.status,body:typeof text==="string"?text:void 0,statusText:error2.data.statusText}}if(isUnusableReplyError(error2))return{kind:"unusable-reply",error:error2};return{kind:"network-error",error:error2}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs}}}async function negotiateEra(negotiation,deps){let timeoutMs=negotiation.probe.timeoutMs??deps.defaultTimeoutMs,maxRetries=Math.max(0,negotiation.probe.maxRetries??0),clientModernVersions=negotiation.kind==="pin"?[negotiation.version]:negotiation.modernVersions,fallbackAvailable=negotiation.kind==="auto"&&negotiation.fallbackAvailable,window=await ProbeWindow.open(deps.transport),probe=async()=>{let requestedVersion=clientModernVersions[0],correctiveUsed=!1,timeoutRetriesRemaining=maxRetries;for(;;){let reply=await window.exchange((id)=>buildProbeRequest(id,requestedVersion,deps.clientInfo,deps.capabilities),timeoutMs);if(reply.kind==="timeout"&&timeoutRetriesRemaining>0){timeoutRetriesRemaining--;continue}let outcome=normalizeReply(reply,timeoutMs),verdict=classifyProbeOutcome(outcome,{clientModernVersions,requestedVersion,fallbackAvailable,environment:deps.environment,transportKind:deps.transportKind});switch(verdict.kind){case"modern":return{era:"modern",version:verdict.version,discover:verdict.discover};case"corrective":if(correctiveUsed)throw verdict.error;correctiveUsed=!0,requestedVersion=verdict.version;continue;case"legacy":{let closedCause=outcome.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(negotiation.kind==="pin")throw new SdkError(SdkErrorCode.EraNegotiationFailed,closedCause===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${negotiation.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${closedCause} before the server offered pinned protocol version ${negotiation.version} (no fallback in pin mode)`);if(!negotiation.fallbackAvailable)throw new SdkError(SdkErrorCode.EraNegotiationFailed,closedCause===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${closedCause} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(closedCause!==void 0&&deps.disposableProbe!==!0)throw new SdkError(SdkErrorCode.EraNegotiationFailed,`Version negotiation failed: ${closedCause} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw verdict.error}}},result;try{result=await probe()}catch(error2){throw window.detach(),error2}return window.release(),result}function readStdioServerParams(transport){let proto=Object.getPrototypeOf(transport);if(proto===null||!Object.prototype.hasOwnProperty.call(proto,"_dispose"))return;let params=transport._serverParams;return typeof params==="object"&&params!==null&&typeof params.command==="string"?params:void 0}async function negotiateStdioViaSibling(negotiation,sessionTransport,params,deps){let sibling=new sessionTransport.constructor({...params,stderr:"ignore"}),originalClose=sessionTransport.close,callerClosed=!1,signalClosed,closedSignal=new Promise((_,reject)=>{signalClosed=()=>reject(callerCloseAbortError())});sessionTransport.close=async function(){return callerClosed=!0,signalClosed?.(),originalClose.call(sessionTransport)};let result;try{let negotiated=negotiateEra(negotiation,{...deps,transport:sibling,transportKind:"stdio",disposableProbe:!0});negotiated.catch(()=>{}),result=await Promise.race([negotiated,closedSignal])}finally{await disposeSibling(sibling),sessionTransport.close=originalClose}if(callerClosed)throw callerCloseAbortError();return result}function callerCloseAbortError(){return new SdkError(SdkErrorCode.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function disposeSibling(sibling){try{let dispose=sibling._dispose;await(typeof dispose==="function"?dispose.call(sibling):sibling.close())}catch{}}function serverInfoFromDiscover(discover){let fromMeta=discover._meta?.[SERVER_INFO_META_KEY];return isSpecType.Implementation(fromMeta)?fromMeta:void 0}function applyElicitationDefaults(schema,data){if(!schema||data===null||typeof data!=="object")return;if(schema.type==="object"&&schema.properties&&typeof schema.properties==="object"){let obj=data,props=schema.properties;for(let key of Object.keys(props)){let propSchema=props[key];if(obj[key]===void 0&&Object.prototype.hasOwnProperty.call(propSchema,"default"))obj[key]=propSchema.default;if(obj[key]!==void 0)applyElicitationDefaults(propSchema,obj[key])}}if(Array.isArray(schema.anyOf)){for(let sub of schema.anyOf)if(typeof sub!=="boolean")applyElicitationDefaults(sub,data)}if(Array.isArray(schema.oneOf)){for(let sub of schema.oneOf)if(typeof sub!=="boolean")applyElicitationDefaults(sub,data)}}function getSupportedElicitationModes(capabilities){if(!capabilities)return{supportsFormMode:!1,supportsUrlMode:!1};let hasFormCapability=capabilities.form!==void 0,hasUrlCapability=capabilities.url!==void 0;return{supportsFormMode:hasFormCapability||!hasFormCapability&&!hasUrlCapability,supportsUrlMode:hasUrlCapability}}function validatePrior(prior){if(typeof prior==="object"&&prior!==null){if(prior.kind==="legacy"&&!("supportedVersions"in prior)&&!("discover"in prior))return prior;if(prior.kind==="modern"&&DiscoverResultSchema.safeParse(prior.discover).success)return prior}throw new SdkError(SdkErrorCode.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var LIST_CHANGED_EVICTIONS={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},DEFAULT_LIST_MAX_PAGES=64,Client=class extends Protocol{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let reason=new SdkError(SdkErrorCode.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let entry of this._listenState.values())entry.settle({cause:"remote",error:reason})}this._listenState.clear();for(let timer of this._listChangedDebounceTimers.values())clearTimeout(timer);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(_clientInfo,options){super(options);if(this._clientInfo=_clientInfo,this._capabilities=options?.capabilities?{...options.capabilities}:{},this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this._enforceStrictCapabilities=options?.enforceStrictCapabilities??!1,this._versionNegotiation=options?.versionNegotiation,this._supportedProtocolVersionsOption=options?.supportedProtocolVersions,this._inputRequiredDriverConfig=resolveInputRequiredDriverConfig(options?.inputRequired),this._cache=new ClientResponseCache(options?.responseCacheStore??new InMemoryResponseCacheStore,options?.responseCacheStore!==void 0,(error2)=>this._reportStoreError(error2),options?.cachePartition??""),this._defaultCacheTtlMs=options?.defaultCacheTtlMs??0,this._listMaxPages=options?.listMaxPages??DEFAULT_LIST_MAX_PAGES,options?.listChanged)this._listChangedConfig=options.listChanged}buildContext(ctx,_transportInfo){return ctx}_shouldDropInbound(message){if(this._negotiatedProtocolVersion!==void 0&&isModernProtocolVersion(this._negotiatedProtocolVersion)&&isJSONRPCRequest(message))return"drop"}_outboundMetaEnvelope(){let version2=this._negotiatedProtocolVersion;if(version2===void 0)return;return this._wireCodec().outboundEnvelope({protocolVersion:version2,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(decoded,flow){if(!this._inputRequiredDriverConfig.autoFulfill)return Promise.reject(new SdkError(SdkErrorCode.UnsupportedResultType,`Unsupported result type 'input_required' for ${flow.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:flow.request.method}));return runInputRequiredFlow({getRequestHandler:(method)=>this._getRequestHandler(method),buildContext:(baseCtx)=>this.buildContext(baseCtx,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,decoded,flow)}_setupListChangedHandlers(config2){if(config2.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools","notifications/tools/list_changed",config2.tools,async()=>{return(await this.listTools(void 0,{cacheMode:"refresh"})).tools});if(config2.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts","notifications/prompts/list_changed",config2.prompts,async()=>{return(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts});if(config2.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources","notifications/resources/list_changed",config2.resources,async()=>{return(await this.listResources(void 0,{cacheMode:"refresh"})).resources})}registerCapabilities(capabilities){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setVersionNegotiation(options){if(this.transport)throw Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=options}_wrapHandler(method,handler){if(method==="elicitation/create")return async(request,ctx)=>{let codec=codecForVersion(this._negotiatedProtocolVersion),validatedRequest=codec.validateRequest("elicitation/create",request);if(!validatedRequest.ok&&validatedRequest.reason==="not-in-era")validatedRequest=codec.validateInputRequest("elicitation/create",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 elicitation/create in the resolved era":`Invalid elicitation request: ${validatedRequest.message}`);let{params}=validatedRequest.value;params.mode=params.mode??"form";let{supportsFormMode,supportsUrlMode}=getSupportedElicitationModes(this._capabilities.elicitation);if(params.mode==="form"&&!supportsFormMode)throw new ProtocolError(ProtocolErrorCode.InvalidParams,"Client does not support form-mode elicitation requests");if(params.mode==="url"&&!supportsUrlMode)throw new ProtocolError(ProtocolErrorCode.InvalidParams,"Client does not support URL-mode elicitation requests");let result=await handler(request,ctx),validationResult=codec.validateResult("elicitation/create",result);if(!validationResult.ok&&validationResult.reason==="not-in-era")validationResult=codec.validateInputResponse("elicitation/create",result);if(!validationResult.ok)throw new ProtocolError(validationResult.reason==="not-in-era"?ProtocolErrorCode.InternalError:ProtocolErrorCode.InvalidParams,validationResult.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${validationResult.message}`);let validatedResult=validationResult.value,requestedSchema=params.mode==="form"?params.requestedSchema:void 0;if(params.mode==="form"&&validatedResult.action==="accept"&&validatedResult.content&&requestedSchema&&this._capabilities.elicitation?.form?.applyDefaults)try{applyElicitationDefaults(requestedSchema,validatedResult.content)}catch{}return validatedResult};if(method==="sampling/createMessage")return async(request,ctx)=>{let codec=codecForVersion(this._negotiatedProtocolVersion),validatedRequest=codec.validateRequest("sampling/createMessage",request);if(!validatedRequest.ok&&validatedRequest.reason==="not-in-era")validatedRequest=codec.validateInputRequest("sampling/createMessage",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 sampling/createMessage in the resolved era":`Invalid sampling request: ${validatedRequest.message}`);let{params}=validatedRequest.value,result=await handler(request,ctx),hasTools=Boolean(params.tools||params.toolChoice),validatedResult=codec.samplingResultVariant(hasTools,result);if(!validatedResult.ok&&validatedResult.reason==="not-in-era")validatedResult=codec.validateInputResponse("sampling/createMessage",result);if(!validatedResult.ok)throw new ProtocolError(validatedResult.reason==="not-in-era"?ProtocolErrorCode.InternalError:ProtocolErrorCode.InvalidParams,validatedResult.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${validatedResult.message}`);return validatedResult.value};return handler}assertCapability(capability,method){if(!this._serverCapabilities?.[capability])throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support ${capability} (required for ${method})`)}async connect(transport,options){if(options?.prior!=null)return this._connectFromPrior(transport,validatePrior(options.prior),options);let negotiation=resolveVersionNegotiation(this._versionNegotiation,this._supportedProtocolVersionsOption);if(negotiation.kind!=="legacy")return this._connectNegotiated(transport,negotiation,options);return this._connectPlainLegacy(transport,options)}async _connectPlainLegacy(transport,options){if(await super.connect(transport),transport.sessionId!==void 0){let negotiatedProtocolVersion=this._negotiatedProtocolVersion;if(negotiatedProtocolVersion!==void 0)transport.setProtocolVersion?.(negotiatedProtocolVersion);return}this._resetConnectionState(),await this._legacyHandshake(transport,options)}async _legacyHandshake(transport,options){let legacyVersions=legacyProtocolVersions(this._supportedProtocolVersions);try{let offeredVersion=legacyVersions[0];if(offeredVersion===void 0)throw new SdkError(SdkErrorCode.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let result=await this.request({method:"initialize",params:{protocolVersion:offeredVersion,capabilities:this._capabilities,clientInfo:this._clientInfo}},options);if(result===void 0)throw Error(`Server sent invalid initialize result: ${result}`);if(!legacyVersions.includes(result.protocolVersion))throw Error(`Server's protocol version is not supported: ${result.protocolVersion}`);if(this._serverCapabilities=result.capabilities,this._serverVersion=result.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(transport)),transport.setProtocolVersion)transport.setProtocolVersion(result.protocolVersion);if(this._instructions=result.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=result.protocolVersion,this._listChangedConfig)this._setupListChangedHandlers(this._listChangedConfig)}catch(error2){throw this.close(),error2}}async _connectNegotiated(transport,negotiation,options){if(transport.sessionId!==void 0){await super.connect(transport);let negotiatedProtocolVersion=this._negotiatedProtocolVersion;if(negotiatedProtocolVersion!==void 0&&transport.setProtocolVersion)transport.setProtocolVersion(negotiatedProtocolVersion);return}this._resetConnectionState();let result;try{let transportKind=detectProbeTransportKind(transport),baseDeps={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:detectProbeEnvironment(),defaultTimeoutMs:options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC},stdioParams=transportKind==="stdio"?readStdioServerParams(transport):void 0;result=stdioParams===void 0?await negotiateEra(negotiation,{...baseDeps,transport,transportKind}):await negotiateStdioViaSibling(negotiation,transport,stdioParams,baseDeps)}catch(error2){throw await transport.close().catch(()=>{}),disarmSpentCloseGuard(transport),error2}if(disarmSpentCloseGuard(transport),await super.connect(transport),result.era==="legacy"){await this._legacyHandshake(transport,options);return}if(this._serverCapabilities=result.discover.capabilities,this._serverVersion=serverInfoFromDiscover(result.discover),this._cache.setServerIdentity(this._deriveServerIdentity(transport)),this._instructions=result.discover.instructions,this._discoverResult=result.discover,this._negotiatedProtocolVersion=result.version,transport.setProtocolVersion)transport.setProtocolVersion(result.version);if(this._listChangedConfig){let config2=this._listChangedConfig,advertised=this._serverCapabilities,effective={...config2.tools&&advertised?.tools?.listChanged&&{tools:config2.tools},...config2.prompts&&advertised?.prompts?.listChanged&&{prompts:config2.prompts},...config2.resources&&advertised?.resources?.listChanged&&{resources:config2.resources}},handlersRegistered=!0;try{this._setupListChangedHandlers(effective)}catch(error2){handlersRegistered=!1,this.onerror?.(error2 instanceof Error?error2:Error(String(error2)))}let filter=handlersRegistered?{...effective.tools&&{toolsListChanged:!0},...effective.prompts&&{promptsListChanged:!0},...effective.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(filter).length>0){let ackAbort=new AbortController,onConnectAbort=()=>ackAbort.abort(options?.signal?.reason);if(options?.signal?.aborted)onConnectAbort();options?.signal?.addEventListener("abort",onConnectAbort);try{this._autoOpenedSubscription=await this.listen(filter,{timeout:options?.timeout,signal:ackAbort.signal})}catch(error2){if(options?.signal?.aborted)throw await this.close().catch(()=>{}),error2;this.onerror?.(error2 instanceof Error?error2:Error(String(error2)))}finally{options?.signal?.removeEventListener("abort",onConnectAbort)}}}}async _connectFromPrior(transport,prior,options){if(prior.kind==="legacy")return this._connectPlainLegacy(transport,options);let discover=prior.discover;this._resetConnectionState();let explicit=this._supportedProtocolVersionsOption,version2=(explicit&&modernProtocolVersions(explicit).length>0?modernProtocolVersions(explicit):SUPPORTED_MODERN_PROTOCOL_VERSIONS).find((v)=>discover.supportedVersions.includes(v));if(version2===void 0)throw new SdkError(SdkErrorCode.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(transport),this._discoverResult=discover,this._serverCapabilities=discover.capabilities,this._serverVersion=serverInfoFromDiscover(discover),this._cache.setServerIdentity(this._deriveServerIdentity(transport)),this._instructions=discover.instructions,this._negotiatedProtocolVersion=version2,transport.setProtocolVersion?.(version2),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(error2){this.onerror?.(error2 instanceof Error?error2:Error(String(error2)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(transport){let v=this._serverVersion;if(v!==void 0)return`${v.name}@${v.version}`;return transport.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let version2=this._negotiatedProtocolVersion;if(version2===void 0)return;return isModernProtocolVersion(version2)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(method){switch(method){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.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":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support resources (required for ${method})`);if(method==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support tools (required for ${method})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support completions (required for ${method})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${method})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){switch(method){case"sampling/createMessage":if(!this._capabilities.sampling)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support sampling capability (required for ${method})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support elicitation capability (required for ${method})`);break;case"roots/list":if(!this._capabilities.roots)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support roots capability (required for ${method})`);break;case"ping":break}}async ping(options){return this.request({method:"ping"},options)}async discover(options){let result=await this._requestWithSchema({method:"server/discover"},DiscoverResultSchema,options);return this._discoverResult=result,result}async complete(params,options){return this.request({method:"completion/complete",params},options)}async setLoggingLevel(level,options){return this.request({method:"logging/setLevel",params:{level}},options)}async getPrompt(params,options){return this.request({method:"prompts/get",params},options)}async listPrompts(params,options){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(params?.cursor!==void 0)return this.request({method:"prompts/list",params},options);let hit=await this._serveFromCache("prompts/list",void 0,options);if(hit!==void 0)return hit;return this._listAllPages("prompts/list",params,options,(r)=>r.prompts)}async listResources(params,options){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(params?.cursor!==void 0)return this.request({method:"resources/list",params},options);let hit=await this._serveFromCache("resources/list",void 0,options);if(hit!==void 0)return hit;return this._listAllPages("resources/list",params,options,(r)=>r.resources)}async listResourceTemplates(params,options){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(params?.cursor!==void 0)return this.request({method:"resources/templates/list",params},options);let hit=await this._serveFromCache("resources/templates/list",void 0,options);if(hit!==void 0)return hit;return this._listAllPages("resources/templates/list",params,options,(r)=>r.resourceTemplates)}async _listAllPages(method,baseParams,options,items,finalize2){let bypass=options?.cacheMode==="bypass",generation=this._cache.captureGeneration(method),acc=await this.request({method,...baseParams&&{params:{...baseParams}}},options),cursor=acc.nextCursor,previous=acc,pages=1;while(cursor!==void 0){if(this._listMaxPages!==0&&pages>=this._listMaxPages)throw new SdkError(SdkErrorCode.ListPaginationExceeded,`${method}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method,listMaxPages:this._listMaxPages});let page=await this.request({method,params:{...baseParams,cursor}},options);if(page.nextCursor===cursor&&JSON.stringify(items(page))===JSON.stringify(items(previous)))break;items(acc).push(...items(page)),previous=page,cursor=page.nextCursor,pages++}if(delete acc.nextCursor,finalize2?.(acc),bypass)return acc;return await this._cache.write(method,acc,generation,this._freshness(acc)),acc}_freshness(result,params){let body=result,ttlMs=typeof body.ttlMs==="number"?body.ttlMs:this._defaultCacheTtlMs,scope=body.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,ttlMs),MAX_CACHE_TTL_MS),scope,params}}async _serveFromCache(method,params,options){if(options?.cacheMode==="bypass"||options?.cacheMode==="refresh")return;let hit=await this._cache.read(method,params).catch((error2)=>void this._reportStoreError(error2));if(hit!==void 0){if(options?.signal?.aborted){let reason=options.signal.reason;throw reason instanceof SdkError?reason:new SdkError(SdkErrorCode.RequestTimeout,String(reason))}return hit.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(tool){if(!tool.outputSchema)return;try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(tool.outputSchema)}}catch(error2){return{ok:!1,compileError:error2}}}async _resolveXMcpHeaderScan(name,override){let tool=override??await this._cache.toolDefinition(name);return tool===void 0?void 0:scanXMcpHeaderDeclarations(tool.inputSchema)}async readResource(params,options){let hit=await this._serveFromCache("resources/read",params.uri,options);if(hit!==void 0)return hit;let generation=this._cache.captureGeneration("resources/read",params.uri),result=await this.request({method:"resources/read",params},options);if(options?.cacheMode!=="bypass"){let freshness=this._freshness(result,params.uri);if(freshness.expiresAt>this._cache.now())await this._cache.write("resources/read",result,generation,freshness);else if(options?.cacheMode==="refresh")await this._cache.evictKey("resources/read",params.uri)}return result}async subscribeResource(params,options){return this.request({method:"resources/subscribe",params},options)}async unsubscribeResource(params,options){return this.request({method:"resources/unsubscribe",params},options)}async listen(filter,options){if(this.transport===void 0)throw new SdkError(SdkErrorCode.NotConnected,"Not connected");let negotiated=this._negotiatedProtocolVersion;if(negotiated===void 0||!isModernProtocolVersion(negotiated))throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${negotiated??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:negotiated});if(options?.signal?.aborted){let reason=options.signal.reason;throw reason instanceof SdkError?reason:new SdkError(SdkErrorCode.RequestTimeout,String(reason))}let requestAbort=new AbortController,listenId=`listen:${this._nextListenId++}`,state="opening",ackTimer,onCallerAbort,resolveOpening,rejectOpening,opening=new Promise((resolve,reject)=>{resolveOpening=resolve,rejectOpening=reject}),resolveClosed,closed=new Promise((resolve)=>{resolveClosed=resolve}),settle2=(outcome)=>{if(state==="closed")return;let wasOpening=state==="opening";if(ackTimer!==void 0)clearTimeout(ackTimer),ackTimer=void 0;if("ack"in outcome){state="open",resolveOpening(outcome.ack);return}if(state="closed",onCallerAbort!==void 0)options?.signal?.removeEventListener("abort",onCallerAbort);if(this._listenState.delete(listenId),requestAbort.abort(),resolveClosed(outcome.cause),wasOpening)rejectOpening(outcome.error??new SdkError(SdkErrorCode.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},wireTeardown=async()=>{requestAbort.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:listenId}}).catch(()=>{})},close=async()=>{if(state==="closed")return;settle2({cause:"local"}),await wireTeardown()};this._listenState.set(listenId,{settle:settle2});let ackTimeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC;if(ackTimer=setTimeout(()=>{settle2({cause:"remote",error:new SdkError(SdkErrorCode.RequestTimeout,"subscriptions/listen ack timed out",{timeout:ackTimeout})}),wireTeardown().catch(()=>{})},ackTimeout),options?.signal){let callerSignal=options.signal;onCallerAbort=()=>{if(state==="closed")return;let reason=callerSignal.reason;settle2({cause:"local",error:reason instanceof Error?reason:Error(String(reason??"Aborted"))}),wireTeardown().catch(()=>{})},callerSignal.addEventListener("abort",onCallerAbort,{once:!0})}let jsonrpcRequest={jsonrpc:"2.0",id:listenId,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:filter}},routeSendFailure=(error2)=>{settle2({cause:"remote",error:error2 instanceof Error?error2:Error(String(error2))})};try{this.transport.send(jsonrpcRequest,{requestSignal:requestAbort.signal,onRequestStreamEnd:()=>settle2({cause:"remote",error:Error("subscriptions/listen: stream ended")})}).catch(routeSendFailure)}catch(error2){routeSendFailure(error2)}return{honoredFilter:await opening,close,closed}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(raw,extra){let evicted=Object.hasOwn(LIST_CHANGED_EVICTIONS,raw.method)?LIST_CHANGED_EVICTIONS[raw.method]:void 0;if(raw.method==="notifications/resources/updated"){let uri=raw.params?.uri;if(typeof uri==="string")this._cache.evictKey("resources/read",uri)}else if(evicted!==void 0)for(let method of evicted)this._cache.evict(method);if(raw.method==="notifications/subscriptions/acknowledged"){let subscriptionId=raw.params?._meta?.[SUBSCRIPTION_ID_META_KEY],entry=typeof subscriptionId==="string"?this._listenState.get(subscriptionId):void 0;if(entry!==void 0){let honored=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",raw);entry.settle({ack:honored.ok?honored.value.params.notifications:{}});return}}if(raw.method==="notifications/cancelled"){let cancelledId=raw.params?.requestId,entry=typeof cancelledId==="string"?this._listenState.get(cancelledId):void 0;if(entry!==void 0){entry.settle({cause:"remote",error:Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(raw,extra)}_onresponse(response){let id=response.id,entry=typeof id==="string"?this._listenState.get(id):void 0;if(entry!==void 0){if(isJSONRPCErrorResponse(response))entry.settle({cause:"remote",error:ProtocolError.fromError(response.error.code,response.error.message,response.error.data)});else entry.settle({cause:"graceful",error:new SdkError(SdkErrorCode.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(response)}_onclose(){if(this._listenState.size>0){let reason=new SdkError(SdkErrorCode.ConnectionClosed,"Connection closed");for(let entry of this._listenState.values())entry.settle({cause:"remote",error:reason});this._listenState.clear()}super._onclose()}async callTool(params,options){let mirroringActive=this.getProtocolEra()==="modern"&&detectProbeEnvironment()!=="browser",buildSendOptions=async()=>{if(!mirroringActive)return options;let scan;try{scan=await this._resolveXMcpHeaderScan(params.name,options?.toolDefinition)}catch(error2){this._reportStoreError(error2)}if(!scan?.valid||scan.declarations.length===0)return options;let paramHeaders=buildMcpParamHeaders(scan.declarations,params.arguments);return Object.keys(paramHeaders).length===0?options:{...options,headers:{...options?.headers,...paramHeaders}}},compiled=options?.toolDefinition===void 0?await this._cache.outputValidator(params.name,(tool)=>this._compileOutputValidator(tool)).catch((error2)=>void this._reportStoreError(error2)):this._compileOutputValidator(options.toolDefinition),assertCompiled=()=>{if(compiled===void 0||compiled.ok)return;let err=compiled.compileError,message=(err instanceof Error?err.message:String(err)).slice(0,200);throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Tool '${params.name}' has an invalid outputSchema: ${message}`)};assertCompiled();let result;try{result=await this.request({method:"tools/call",params},await buildSendOptions())}catch(error2){let isHeaderMismatch=error2 instanceof ProtocolError&&error2.code===HEADER_MISMATCH_ERROR_CODE;if(!mirroringActive||!isHeaderMismatch||options?.toolDefinition!==void 0)throw error2;let refreshOptions={signal:options?.signal,timeout:options?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,refreshOptions).catch((error_)=>this._reportStoreError(error_)),compiled=await this._cache.outputValidator(params.name,(tool)=>this._compileOutputValidator(tool)).catch((error_)=>void this._reportStoreError(error_)),assertCompiled(),result=await this.request({method:"tools/call",params},await buildSendOptions())}let validator=compiled!==void 0&&compiled.ok?compiled.validator:void 0;if(validator){if(result.structuredContent===void 0&&!result.isError)throw new ProtocolError(ProtocolErrorCode.InvalidRequest,`Tool ${params.name} has an output schema but did not return structured content`);if(result.structuredContent!==void 0&&!result.isError)try{let validationResult=validator(result.structuredContent);if(!validationResult.valid)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)}catch(error2){if(error2 instanceof ProtocolError)throw error2;throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Failed to validate structured content: ${error2 instanceof Error?error2.message:String(error2)}`)}}return result}async listTools(params,options){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(params?.cursor!==void 0){let page=await this.request({method:"tools/list",params},options);return this._excludeInvalidXMcpHeaderTools(page),page}let hit=await this._serveFromCache("tools/list",void 0,options);if(hit!==void 0)return hit;return this._listAllPages("tools/list",params,options,(r)=>r.tools,(acc)=>this._excludeInvalidXMcpHeaderTools(acc))}_excludeInvalidXMcpHeaderTools(result){if(this.getProtocolEra()!=="modern"||!this.transport||detectProbeTransportKind(this.transport)==="stdio")return;let filtered=result.tools.filter((tool)=>{let scan=scanXMcpHeaderDeclarations(tool.inputSchema);if(!scan.valid)return console.warn(`[mcp-sdk] excluding tool '${tool.name}' from tools/list: invalid x-mcp-header declaration — ${scan.reason}`),!1;return!0});if(filtered.length!==result.tools.length)result.tools=filtered}_setupListChangedHandler(listType,notificationMethod,options,fetcher){let parseResult=parseSchema(ListChangedOptionsBaseSchema,options);if(!parseResult.success)throw Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);if(typeof options.onChanged!=="function")throw TypeError(`Invalid ${listType} listChanged options: onChanged must be a function`);let{autoRefresh,debounceMs}=parseResult.data,{onChanged}=options,refresh=async()=>{if(!autoRefresh){onChanged(null,null);return}try{onChanged(null,await fetcher())}catch(error2){onChanged(error2 instanceof Error?error2:Error(String(error2)),null)}},handler=()=>{if(debounceMs){let existingTimer=this._listChangedDebounceTimers.get(listType);if(existingTimer)clearTimeout(existingTimer);let timer=setTimeout(refresh,debounceMs);this._listChangedDebounceTimers.set(listType,timer)}else refresh()};this.setNotificationHandler(notificationMethod,handler)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function hasDpopChallenge(wwwAuthenticate){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(wwwAuthenticate)}function isDpopNonceChallenge(response){if(response.status!==401)return!1;let wwwAuthenticate=response.headers.get("www-authenticate")??"";return hasDpopChallenge(wwwAuthenticate)&&/use_dpop_nonce/i.test(wwwAuthenticate)}var withDpop=(session,getToken)=>(next)=>{let resolveSession=typeof session==="function"?session:()=>session;return async(input,init)=>{let method=(init?.method??"GET").toUpperCase(),url2=new URL(input.toString()),activeSession=await resolveSession();if(!activeSession)return next(input,init);let makeRequest=async()=>{let accessToken=await getToken();if(!accessToken)return next(input,init);let headers=new Headers(init?.headers),proof=await activeSession.buildProof({htm:method,htu:url2,accessToken});return headers.set("Authorization",`DPoP ${accessToken}`),headers.set("DPoP",proof),next(input,{...init,headers})},response=await makeRequest();if(isDpopNonceChallenge(response)&&response.headers.has("dpop-nonce"))activeSession.observeNonce(response,url2),await response.text?.().catch(()=>{}),response=await makeRequest();return activeSession.observeNonce(response,url2),response}},withDpopFromProvider=(provider)=>withDpop(async()=>{try{return await provider.dpop?.()}catch(error2){throw markAuthSeamEscape(error2)}},async()=>{let tokens;try{tokens=await provider.tokens()}catch(error2){throw markAuthSeamEscape(error2)}return tokens?.token_type?.toLowerCase()==="dpop"?tokens.access_token:void 0});var SseError=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!=="function")throw 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,event){super(`SSE error: ${message}`);this.code=code,this.event=event,stampErrorBrands(this,new.target)}};var DEFAULT_MAX_STEP_UP_RETRIES=1,DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},RESERVED_REQUEST_HEADER_NAMES=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function anySignal(a,b){if(typeof AbortSignal.any==="function")return AbortSignal.any([a,b]);let controller=new AbortController;if(a.aborted)return controller.abort(a.reason),controller.signal;if(b.aborted)return controller.abort(b.reason),controller.signal;let cleanup=()=>{a.removeEventListener("abort",onA),b.removeEventListener("abort",onB)};function onA(){cleanup(),controller.abort(a.reason)}function onB(){cleanup(),controller.abort(b.reason)}return a.addEventListener("abort",onA,{once:!0}),b.addEventListener("abort",onB,{once:!0}),controller.signal}var StreamableHTTPClientTransport=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(url2,opts){if(this._url=url2,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=opts?.requestInit,this._skipIssuerMetadataValidation=opts?.skipIssuerMetadataValidation,this._fetch=opts?.fetch,isOAuthClientProvider(opts?.authProvider)){if(this._oauthProvider=opts.authProvider,this._authProvider=adaptOAuthProvider(opts.authProvider,{skipIssuerMetadataValidation:opts.skipIssuerMetadataValidation}),opts.authProvider.dpop)this._fetch=withDpopFromProvider(opts.authProvider)(opts.fetch??fetch)}else this._authProvider=opts?.authProvider;if(this._redirectPolicy=opts?.redirectPolicy,this._fetchWithInit=createFetchWithInit(opts?.fetch,opts?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=fetchLeavingRedirects(this._fetchWithInit);this._sessionId=opts?.sessionId,this._protocolVersion=opts?.protocolVersion,this._reconnectionOptions=opts?.reconnectionOptions??DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS,this._reconnectionScheduler=opts?.reconnectionScheduler,this._onInsufficientScope=opts?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,opts?.maxStepUpRetries??DEFAULT_MAX_STEP_UP_RETRIES)}async _stepUpAuthorize(challenge,stepUpRetries){try{return await this._stepUpAuthorizeInner(challenge,stepUpRetries)}catch(error2){throw markAuthSeamEscape(error2)}}async _stepUpAuthorizeInner(challenge,stepUpRetries){if(this._onInsufficientScope==="throw")throw new InsufficientScopeError({requiredScope:challenge.scope,resourceMetadataUrl:challenge.resourceMetadataUrl,errorDescription:challenge.errorDescription});if(!this._oauthProvider)throw new InsufficientScopeError({requiredScope:challenge.scope,resourceMetadataUrl:challenge.resourceMetadataUrl,errorDescription:challenge.errorDescription});if(stepUpRetries>=this._maxStepUpRetries)throw new SdkHttpError(SdkErrorCode.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:challenge.statusText??"Forbidden",text:challenge.text});if(challenge.resourceMetadataUrl)this._resourceMetadataUrl=challenge.resourceMetadataUrl;let tokens=await this._oauthProvider.tokens(),unionScope=computeScopeUnion(this._scope,tokens?.scope,challenge.scope);this._scope=unionScope;let forceReauthorization=isStrictScopeSuperset(unionScope,tokens?.scope);return auth(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:unionScope,forceReauthorization,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(baseFetch){return this._redirectPolicy==="follow"?baseFetch:fetchWithinOrigin(baseFetch)}_unfollowedRedirect(url2,response){let text=this._redirectPolicy==="follow"?void 0:unfollowedRedirect(url2,response);return text&&`${text} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let headers=new Headers(this._requestInit?.headers||void 0),token;try{token=await this._authProvider?.token()}catch(error2){throw markAuthSeamEscape(error2)}if(token)headers.set("Authorization",`Bearer ${token}`);if(this._sessionId)headers.set("mcp-session-id",this._sessionId);if(this._protocolVersion)headers.set("mcp-protocol-version",this._protocolVersion);return headers}_applyBodyDerivedHeaders(headers,message){if(Array.isArray(message)||!isJSONRPCRequest(message))return;let envelopeVersion=message.params?._meta?.[PROTOCOL_VERSION_META_KEY];if(typeof envelopeVersion!=="string")return;headers.set("mcp-protocol-version",envelopeVersion),headers.set("mcp-method",message.method);let source=mcpNameSource(message.method,message.params);if(source?.value!==void 0)headers.set("mcp-name",encodeMcpParamValue(source.value))}_isModernEnvelopedRequest(message){if(Array.isArray(message)||!isJSONRPCRequest(message))return!1;let v=message.params?._meta?.[PROTOCOL_VERSION_META_KEY];return typeof v==="string"&&isModernProtocolVersion(v)}async _startOrAuthSse(options,isAuthRetry=!1,stepUpRetries=0){let{resumptionToken,requestSignal}=options,isIntentionalAbort=()=>this._abortController?.signal.aborted===!0||requestSignal?.aborted===!0;try{let headers=await this._commonHeaders(),types=[...headers.get("accept")?.split(",").map((s)=>s.trim().toLowerCase())??[],"text/event-stream"];if(headers.set("accept",[...new Set(types)].join(", ")),resumptionToken)headers.set("last-event-id",resumptionToken);let transportSignal=this._abortController?.signal,signal=requestSignal!==void 0&&transportSignal!==void 0?anySignal(transportSignal,requestSignal):requestSignal??transportSignal,response=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers,signal});if(!response.ok){if(response.status===401&&this._authProvider){if(response.headers.has("www-authenticate")){let{resourceMetadataUrl,scope}=extractWWWAuthenticateParams(response);this._resourceMetadataUrl=resourceMetadataUrl,this._scope=computeScopeUnion(this._scope,scope)}if(this._authProvider.onUnauthorized&&!isAuthRetry){try{await this._authProvider.onUnauthorized({response,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(error2){throw markAuthSeamEscape(error2)}return await response.text?.().catch(()=>{}),this._startOrAuthSse(options,!0,stepUpRetries)}if(await response.text?.().catch(()=>{}),isAuthRetry)throw markAuthSeamEscape(new SdkHttpError(SdkErrorCode.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:response.statusText}));throw markAuthSeamEscape(new UnauthorizedError)}if(response.status===403){let{resourceMetadataUrl,scope,error:error2,errorDescription}=extractWWWAuthenticateParams(response);if(error2==="insufficient_scope"){let text=await response.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope,resourceMetadataUrl,errorDescription,statusText:response.statusText,text},stepUpRetries)!=="AUTHORIZED")throw markAuthSeamEscape(new UnauthorizedError);return this._startOrAuthSse(options,isAuthRetry,stepUpRetries+1)}}if(await response.text?.().catch(()=>{}),response.status===405){options.onRequestStreamEnd?.();return}let reason=this._unfollowedRedirect(this._url,response)??response.statusText;throw new SdkHttpError(SdkErrorCode.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${reason}`,{status:response.status,statusText:response.statusText})}this._handleSseStream(response.body,options,!0)}catch(error2){if(!isIntentionalAbort())this.onerror?.(error2);throw error2}}_getNextReconnectionDelay(attempt){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let initialDelay=this._reconnectionOptions.initialReconnectionDelay,growFactor=this._reconnectionOptions.reconnectionDelayGrowFactor,maxDelay=this._reconnectionOptions.maxReconnectionDelay;return Math.min(initialDelay*Math.pow(growFactor,attempt),maxDelay)}_scheduleReconnection(options,attemptCount=0){let maxRetries=this._reconnectionOptions.maxRetries;if(attemptCount>=maxRetries){this.onerror?.(Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)),options.onRequestStreamEnd?.();return}let delay=this._getNextReconnectionDelay(attemptCount),reconnect=()=>{if(this._cancelReconnection=void 0,this._abortController?.signal.aborted||options.requestSignal?.aborted)return;this._startOrAuthSse(options).catch((error2)=>{if(this._abortController?.signal.aborted||options.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${error2 instanceof Error?error2.message:String(error2)}`));try{this._scheduleReconnection(options,attemptCount+1)}catch(scheduleError){this.onerror?.(scheduleError instanceof Error?scheduleError:Error(String(scheduleError)))}})};if(this._reconnectionScheduler){let cancel=this._reconnectionScheduler(reconnect,delay,attemptCount);this._cancelReconnection=typeof cancel==="function"?cancel:void 0}else{let handle=setTimeout(reconnect,delay);this._cancelReconnection=()=>clearTimeout(handle)}}_handleSseStream(stream,options,isReconnectable){if(!stream){options.onRequestStreamEnd?.();return}let{onresumptiontoken,replayMessageId,requestSignal,onRequestStreamEnd}=options,isIntentionalAbort=()=>this._abortController?.signal.aborted===!0||requestSignal?.aborted===!0,lastEventId,hasPrimingEvent=!1,receivedResponse=!1;(async()=>{try{let reader=stream.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream({onRetry:(retryMs)=>{this._serverRetryMs=retryMs}})).getReader();while(!0){let{value:event,done}=await reader.read();if(done)break;if(event.id)lastEventId=event.id,hasPrimingEvent=!0,onresumptiontoken?.(event.id);if(!event.data)continue;if(!event.event||event.event==="message")try{let message=JSONRPCMessageSchema.parse(JSON.parse(event.data));if(isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)){if(receivedResponse=!0,replayMessageId!==void 0)message.id=replayMessageId}this.onmessage?.(message)}catch(error2){this.onerror?.(error2)}}if((isReconnectable||hasPrimingEvent)&&!receivedResponse&&this._abortController&&!isIntentionalAbort())this._scheduleReconnection({resumptionToken:lastEventId,onresumptiontoken,replayMessageId,requestSignal,onRequestStreamEnd},0);else if(!isIntentionalAbort())onRequestStreamEnd?.()}catch(error2){if(isIntentionalAbort())return;if(this.onerror?.(Error(`SSE stream disconnected: ${error2}`)),(isReconnectable||hasPrimingEvent)&&!receivedResponse&&this._abortController&&!isIntentionalAbort())try{this._scheduleReconnection({resumptionToken:lastEventId,onresumptiontoken,replayMessageId,requestSignal,onRequestStreamEnd},0)}catch(error$1){this.onerror?.(Error(`Failed to reconnect: ${error$1 instanceof Error?error$1.message:String(error$1)}`)),onRequestStreamEnd?.()}else onRequestStreamEnd?.()}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(codeOrParams,iss){if(!this._oauthProvider)throw new UnauthorizedError("finishAuth requires an OAuthClientProvider");let{authorizationCode,iss:issParam}=await resolveAuthorizationCallbackParams(codeOrParams,iss,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await auth(this._oauthProvider,{serverUrl:this._url,authorizationCode,iss:issParam,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new UnauthorizedError("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(message,options){return this._send(message,options,!1)}async _send(message,options,isAuthRetry,stepUpRetries=0){try{let{resumptionToken,onresumptiontoken}=options||{};if(resumptionToken){this._startOrAuthSse({resumptionToken,replayMessageId:isJSONRPCRequest(message)?message.id:void 0,requestSignal:options?.requestSignal}).catch((error2)=>this.onerror?.(error2));return}let headers=await this._commonHeaders();this._applyBodyDerivedHeaders(headers,message);let isHandshake=Array.isArray(message)?message.some((m)=>isInitializeRequest(m)):isInitializeRequest(message);if(isHandshake)headers.delete("mcp-session-id");if(options?.headers!==void 0)for(let[name,value]of Object.entries(options.headers)){if(RESERVED_REQUEST_HEADER_NAMES.has(name.toLowerCase()))continue;headers.set(name,value)}headers.set("content-type","application/json");let types=[...headers.get("accept")?.split(",").map((s)=>s.trim().toLowerCase())??[],"application/json","text/event-stream"];headers.set("accept",[...new Set(types)].join(", "));let transportSignal=this._abortController?.signal,signal=options?.requestSignal!==void 0&&transportSignal!==void 0?anySignal(transportSignal,options.requestSignal):options?.requestSignal??transportSignal,init={...this._requestInit,method:"POST",headers,body:JSON.stringify(message),signal},response=await this._redirects(this._fetch??fetch)(this._url,init);if(isHandshake&&response.ok)this._sessionId=response.headers.get("mcp-session-id")||void 0;if(!response.ok){if(response.status===401&&this._authProvider){if(response.headers.has("www-authenticate")){let{resourceMetadataUrl,scope}=extractWWWAuthenticateParams(response);this._resourceMetadataUrl=resourceMetadataUrl,this._scope=computeScopeUnion(this._scope,scope)}if(this._authProvider.onUnauthorized&&!isAuthRetry){try{await this._authProvider.onUnauthorized({response,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(error2){throw markAuthSeamEscape(error2)}return await response.text?.().catch(()=>{}),this._send(message,options,!0,stepUpRetries)}if(await response.text?.().catch(()=>{}),isAuthRetry)throw markAuthSeamEscape(new SdkHttpError(SdkErrorCode.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:response.statusText}));throw markAuthSeamEscape(new UnauthorizedError)}let text=await response.text?.().catch(()=>null);if(response.status===403){let{resourceMetadataUrl,scope,error:error2,errorDescription}=extractWWWAuthenticateParams(response);if(error2==="insufficient_scope"){if(await this._stepUpAuthorize({scope,resourceMetadataUrl,errorDescription,statusText:response.statusText,text},stepUpRetries)!=="AUTHORIZED")throw markAuthSeamEscape(new UnauthorizedError);return this._send(message,options,isAuthRetry,stepUpRetries+1)}}if(response.status===400&&typeof text==="string"&&this._isModernEnvelopedRequest(message))try{let parsed=JSONRPCMessageSchema.parse(JSON.parse(text)),requests=(Array.isArray(message)?message:[message]).filter((m)=>isJSONRPCRequest(m));if(isJSONRPCErrorResponse(parsed)&&requests.some((r)=>r.id===parsed.id)){this.onmessage?.(parsed);return}}catch{}let reason=this._unfollowedRedirect(this._url,response)??text;throw new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented,`Error POSTing to endpoint: ${reason}`,{status:response.status,statusText:response.statusText,text})}if(response.status===202){if(await response.text?.().catch(()=>{}),isInitializedNotification(message))this._startOrAuthSse({resumptionToken:void 0}).catch((error2)=>this.onerror?.(error2));return}let hasRequests=(Array.isArray(message)?message:[message]).some((msg)=>("method"in msg)&&("id"in msg)&&msg.id!==void 0),contentType=response.headers.get("content-type"),responseMediaType=mediaTypeEssence(contentType);if(hasRequests)if(responseMediaType==="text/event-stream")this._handleSseStream(response.body,{onresumptiontoken,requestSignal:options?.requestSignal,onRequestStreamEnd:options?.onRequestStreamEnd},!1);else if(responseMediaType==="application/json"){let data=await response.json(),responseMessages=Array.isArray(data)?data.map((msg)=>JSONRPCMessageSchema.parse(msg)):[JSONRPCMessageSchema.parse(data)];for(let msg of responseMessages)this.onmessage?.(msg)}else throw await response.text?.().catch(()=>{}),new SdkError(SdkErrorCode.ClientHttpUnexpectedContent,`Unexpected content type: ${contentType}`,{contentType});else await response.text?.().catch(()=>{})}catch(error2){if(options?.requestSignal?.aborted!==!0)this.onerror?.(error2);throw error2}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let headers=await this._commonHeaders(),init={...this._requestInit,method:"DELETE",headers,signal:this._abortController?.signal},response=await this._redirects(this._fetch??fetch)(this._url,init);if(await response.text?.().catch(()=>{}),!response.ok&&response.status!==405)throw new SdkHttpError(SdkErrorCode.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,response)??response.statusText}`,{status:response.status,statusText:response.statusText});this._sessionId=void 0}catch(error2){throw this.onerror?.(error2),error2}}setProtocolVersion(version2){this._protocolVersion=version2}get protocolVersion(){return this._protocolVersion}async resumeStream(lastEventId,options){await this._startOrAuthSse({resumptionToken:lastEventId,onresumptiontoken:options?.onresumptiontoken})}};import{randomBytes as randomBytes3}from"node:crypto";import{execFile}from"node:child_process";import{randomBytes}from"node:crypto";import{chmodSync,closeSync,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFileSync,renameSync,statSync,unlinkSync,utimesSync,writeFileSync,writeSync}from"node:fs";import{createServer}from"node:http";import{homedir}from"node:os";import{dirname,join}from"node:path";function safeUrl(url2){try{let u=new URL(String(url2));return u.username="",u.password="",u.search="",u.hash="",u.toString()}catch{return"(not a URL)"}}function isLoopback(hostname){let h=hostname.replace(/^\[|\]$/g,"").toLowerCase();return h==="localhost"||h==="::1"||/^127(\.\d{1,3}){3}$/.test(h)}function checkKolabUrl(url2){let u;try{u=new URL(url2)}catch{throw Error(`${safeUrl(url2)} isn't a URL: set KONJIR_URL or --url to Kolab's MCP URL, such as https://kolab.konjir.com/mcp`)}if(u.protocol==="https:")return u;if(u.protocol==="http:"&&isLoopback(u.hostname))return u;if(u.protocol==="http:")throw Error(`konjir signs in to Kolab only over https, or http on this machine: ${safeUrl(url2)} is http to another host, where the network could read your sign-in. Use its https URL`);throw Error(`konjir signs in to Kolab only over https, or http on this machine: ${safeUrl(url2)} is ${u.protocol.replace(/:$/,"")}`)}function checkAuthorizeUrl(u,kolabUrl){let kolab=checkKolabUrl(kolabUrl);if(!(u.protocol==="https:"||u.protocol==="http:"&&isLoopback(u.hostname))||u.origin!==kolab.origin||u.pathname!=="/oauth/authorize"||u.username||u.password)throw Error(`Kolab at ${safeUrl(kolabUrl)} sent its sign-in to ${safeUrl(u)}, which isn't its own ${kolab.origin}/oauth/authorize, so konjir opens nothing. Check KONJIR_URL`);return u}var REDIRECT="http://127.0.0.1/callback";function credentialsPath(env=process.env){if(env.KONJIR_CREDENTIALS)return env.KONJIR_CREDENTIALS;return join(env.XDG_CONFIG_HOME||join(homedir(),".config"),"konjir","credentials.json")}function agentCredentialsPath(agent,env=process.env){if(!/^[a-z0-9][a-z0-9-]{0,63}$/.test(agent))throw Error(`KONJIR_AGENT ${JSON.stringify(agent)} isn't an agent's id: lowercase letters, digits and -`);return join(dirname(credentialsPath(env)),"agents",`${agent}.json`)}function agentCredentials(agent,env=process.env){let file=agentCredentialsPath(agent,env),dir=dirname(file);mkdirSync(dirname(dir),{recursive:!0,mode:448});try{mkdirSync(dir,{mode:448})}catch(e){if(codeOf(e)!=="EEXIST")throw e}let st=lstatSync(dir);if(st.isSymbolicLink()||!st.isDirectory())throw Error(`${dir} isn't a folder of konjir's (it is a symbolic link, or not a folder), so konjir won't keep an agent's sign-in there: remove it`);if(process.getuid&&st.uid!==process.getuid())throw Error(`${dir} belongs to someone else, so konjir won't keep an agent's sign-in there: remove it, or set KONJIR_CREDENTIALS to a file in a folder of your own`);if((st.mode&511)!==448)chmodSync(dir,448);return file}var sleep2=(ms)=>new Promise((r)=>setTimeout(r,ms)),LOCK_STALE_MS=30000,LOCK_TOUCH_MS=1e4,LOCK_WAIT_MS=40000,LOCK_MAX_HOLD_MS=30000,codeOf=(e)=>e?.code,held=new Map;process.once("exit",()=>{for(let[path,h]of held)try{if(readFileSync(path,"utf8")===h.owner)unlinkSync(path)}catch{}});class FileLock{path;waitMs;maxHoldMs;constructor(path,waitMs=LOCK_WAIT_MS,maxHoldMs=LOCK_MAX_HOLD_MS){this.path=path;this.waitMs=waitMs;this.maxHoldMs=maxHoldMs}ownerOnDisk(){let st;try{st=lstatSync(this.path)}catch(e){if(codeOf(e)==="ENOENT")return;throw e}if(st.isSymbolicLink())throw Error(`${this.path} is a symbolic link, so konjir won't use it as its lock: remove it`);try{return readFileSync(this.path,"utf8")}catch(e){if(codeOf(e)==="ENOENT")return;throw e}}async acquire(owner){if(this.holds(owner))return;let end=Date.now()+this.waitMs,why="another konjir holds it";for(;;){try{mkdirSync(dirname(this.path),{recursive:!0,mode:448});let fd=openSync(this.path,"wx",384);try{writeSync(fd,owner)}finally{closeSync(fd)}let since=Date.now(),touch=setInterval(()=>{if(Date.now()-since>=this.maxHoldMs){this.release(owner);return}try{if(this.holds(owner)){let t=new Date;utimesSync(this.path,t,t)}}catch{}},Math.min(LOCK_TOUCH_MS,this.maxHoldMs));touch.unref();let before=held.get(this.path);if(before)clearInterval(before.touch);held.set(this.path,{owner,touch});return}catch(e){if(process.platform==="win32"&&["EPERM","EACCES","EBUSY"].includes(codeOf(e)??"")){if(Date.now()>end)throw Error(`konjir couldn't take ${this.path} (${codeOf(e)}): if no konjir is running, remove that file`);await sleep2(15+Math.random()*35);continue}if(codeOf(e)!=="EEXIST")throw Error(`konjir couldn't take ${this.path} (${codeOf(e)??e}); check that folder is yours to write in`)}let st;try{st=lstatSync(this.path)}catch(e){if(codeOf(e)==="ENOENT")continue;why=`konjir can't read it (${codeOf(e)??e})`}if(st?.isSymbolicLink())throw Error(`${this.path} is a symbolic link, so konjir won't use it as its lock: remove it`);if(st&&Date.now()-st.mtimeMs>LOCK_STALE_MS){let broke2=this.breakStale(st.mtimeMs);if(broke2===!0)continue;if(broke2)why=broke2}if(Date.now()>end)throw Error(`konjir couldn't take ${this.path}: ${why}. If no konjir is running, remove that file`);await sleep2(15+Math.random()*35)}}breakStale(staleMtime){let aside=`${this.path}.${randomBytes(8).toString("hex")}.stale`;try{renameSync(this.path,aside)}catch(e){if(codeOf(e)==="ENOENT")return!0;return`its stale lock can't be removed (${codeOf(e)??e})`}let moved;try{moved=lstatSync(aside)}catch(e){return`konjir moved its stale lock aside to ${aside} but can't read it (${codeOf(e)??e})`}if(moved.mtimeMs!==staleMtime)try{linkSync(aside,this.path)}catch(e){if(codeOf(e)==="EEXIST"){try{unlinkSync(aside)}catch{}return!0}try{lstatSync(this.path)}catch(f){if(codeOf(f)==="ENOENT")try{return renameSync(aside,this.path),!0}catch{}}return`konjir moved a live lock aside to ${aside} and couldn't put it back (${codeOf(e)??e})`}try{unlinkSync(aside)}catch{}return!0}release(owner){let h=held.get(this.path);if(h?.owner!==owner)return;clearInterval(h.touch),held.delete(this.path);try{if(this.ownerOnDisk()===owner)unlinkSync(this.path)}catch{}}holds(owner){if(held.get(this.path)?.owner!==owner)return!1;try{if(this.ownerOnDisk()===owner)return!0}catch{}let h=held.get(this.path);return clearInterval(h.touch),held.delete(this.path),!1}thinksHeld(owner){return held.get(this.path)?.owner===owner}}class Store{path;managed;lock;constructor(path,managed,lockWaitMs,lockMaxHoldMs){this.path=path;this.managed=managed;this.lock=new FileLock(`${path}.lock`,lockWaitMs,lockMaxHoldMs)}warned=!1;all(){if(!existsSync(this.path))return{};let parsed;try{parsed=JSON.parse(readFileSync(this.path,"utf8"))}catch{parsed=void 0}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw Error(`${this.path} isn't konjir's credentials (not valid JSON), so konjir won't touch it: fix it or move it away, then run konjir login`);return parsed}get(url2){return this.all()[url2]??{}}async set(url2,change,owner){let own2=owner!==void 0&&this.lock.holds(owner),me=own2?owner:`w_${randomBytes(12).toString("hex")}`;if(!own2)await this.lock.acquire(me);try{let all=this.all(),next=change(all[url2]??{});if(next)all[url2]=next;else delete all[url2];let dir=dirname(this.path);if(mkdirSync(dir,{recursive:!0,mode:448}),this.managed)try{chmodSync(dir,448)}catch{}else if(!this.warned){this.warned=!0;try{if(statSync(dir).mode&18)console.error(`warning: others may write in ${dir}, which holds your konjir sign-in (${this.path}); konjir leaves the folder as it is`)}catch{}}let tmp=`${this.path}.${randomBytes(8).toString("hex")}.tmp`;writeFileSync(tmp,JSON.stringify(all,null,2),{mode:384,flag:"wx"}),renameSync(tmp,this.path)}finally{if(!own2)this.lock.release(me)}}}function bearerOf(init){let v=new Headers(init?.headers).get("authorization");return v?.startsWith("Bearer ")?v.slice(7):void 0}class StoredLogin{url;opts;store;verifier="";owner=`p${process.pid}_${randomBytes(12).toString("hex")}`;refreshing;savedOwn=!1;ownClient;yielded=!1;expectedState=randomBytes(24).toString("base64url");constructor(url2,opts={}){this.url=url2;this.opts=opts;if(!opts.skipUrlCheck)checkKolabUrl(url2);this.store=new Store(opts.path??credentialsPath(),!opts.path&&!process.env.KONJIR_CREDENTIALS,opts.lockWaitMs,opts.lockMaxHoldMs)}get redirectUrl(){return this.opts.redirectUrl??REDIRECT}get clientMetadata(){return{client_name:this.opts.clientName??"konjir CLI",redirect_uris:[REDIRECT],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}state(){return this.expectedState}clientInformation(){return this.ownClient??this.store.get(this.url).client}withTokens(s,tokens){return{...s,tokens,...this.ownClient?{client:this.ownClient}:{}}}saveClientInformation(client){return this.ownClient=client,this.store.set(this.url,(s)=>({...s,client}),this.owner)}get file(){return this.store.path}async tokens(ctx){if(this.opts.fresh&&!this.savedOwn)return;if(ctx===void 0)return this.store.get(this.url).tokens;if(!this.store.get(this.url).tokens?.refresh_token)return this.store.get(this.url).tokens;await this.store.lock.acquire(this.owner);let t=this.store.get(this.url).tokens;if(this.refreshing=t?.refresh_token,!t)this.store.lock.release(this.owner);return t}async saveTokens(tokens){this.savedOwn=!0;let was=this.refreshing;if(was!==void 0&&!this.store.lock.holds(this.owner)){if(this.refreshing=void 0,this.store.get(this.url).tokens?.refresh_token!==was)return;await this.store.set(this.url,(s)=>this.withTokens(s,tokens));return}if(was!==void 0&&tokens.refresh_token===was){await this.store.set(this.url,(s)=>this.withTokens(s,tokens),this.owner);return}if(this.opts.fresh&&this.opts.yieldTo!==void 0&&was===void 0){let lost=!1;if(await this.store.set(this.url,(s)=>{let now=s.tokens?.refresh_token;if(now&&now!==this.opts.yieldTo)return lost=!0,s;return this.withTokens(s,tokens)},this.owner),lost){this.yielded=!0;let client=this.ownClient??this.store.get(this.url).client;await revoke(this.url,{client,tokens}).catch(()=>{return})}return}try{await this.store.set(this.url,(s)=>this.withTokens(s,tokens),this.owner)}finally{this.refreshing=void 0,this.store.lock.release(this.owner)}}releaseLock(){this.refreshing=void 0,this.store.lock.release(this.owner)}releaseIdleLock(){if(this.refreshing===void 0)this.store.lock.release(this.owner)}async locked(fn){await this.store.lock.acquire(this.owner);try{return await fn(this.owner)}finally{this.store.lock.release(this.owner)}}async redirectToAuthorization(u){if(this.store.lock.release(this.owner),!this.opts.onAuthorize)throw Error(`your sign-in to ${safeUrl(this.url)} has ended or was revoked: run konjir login`);await this.opts.onAuthorize(u)}saveCodeVerifier(v){this.verifier=v}codeVerifier(){return this.verifier}saveDiscoveryState(discovery){return this.store.set(this.url,(s)=>({...s,discovery}),this.owner)}discoveryState(){return this.store.get(this.url).discovery}invalidateCredentials(scope){if(scope==="verifier"){this.verifier="";return}let failed=this.refreshing;return this.store.set(this.url,(s)=>{if(scope==="all")return;let{client,tokens,discovery}=s,dropTokens=scope==="client"||scope==="tokens"&&(failed===void 0||tokens?.refresh_token===failed);return{client:scope==="client"?void 0:client,tokens:dropTokens?void 0:tokens,discovery:scope==="discovery"?void 0:discovery}},this.owner)}get fetch(){return this.fetchWith(fetch)}fetchWith(inner){return async(url2,init)=>{let res=await inner(url2,init),sent=bearerOf(init);if(res.status!==401||!sent)return res;let waiter=`f_${randomBytes(12).toString("hex")}`;await this.store.lock.acquire(waiter),this.store.lock.release(waiter);let now=this.store.get(this.url).tokens?.access_token;if(!now||now===sent)return res;await res.text().catch(()=>{return});let headers=new Headers(init?.headers);return headers.set("authorization",`Bearer ${now}`),inner(url2,{...init,headers})}}get signedIn(){return!!this.store.get(this.url).tokens?.refresh_token}secrets(){let t=this.store.get(this.url).tokens;return[t?.access_token,t?.refresh_token].filter((x)=>!!x)}saved(){return this.store.get(this.url)}forget(owner){return this.store.set(this.url,()=>{return},owner)}}function browserCommand(u,platform=process.platform){if(platform==="darwin")return["open",[u.toString()]];if(platform==="win32")return["rundll32",["url.dll,FileProtocolHandler",u.toString()]];return["xdg-open",[u.toString()]]}function openBrowser(u,kolabUrl,run=(cmd,args)=>{try{execFile(cmd,args,{windowsHide:!0},()=>{return}).unref()}catch{}}){checkAuthorizeUrl(u,kolabUrl);let[cmd,args]=browserCommand(u);run(cmd,args)}var done=(ok,text)=>`<!doctype html><meta charset="utf-8"><title>konjir</title><p>${ok?"Signed in.":"Sign-in stopped."} ${text.replace(/[&<>"']/g,"")}</p>`;async function revoke(url2,saved){let refresh=saved.tokens?.refresh_token,client=saved.client?.client_id;if(!refresh||!client)return"nothing";let endpoint=new URL("/oauth/revoke",url2).toString(),post=(token,hint)=>fetch(endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token,token_type_hint:hint,client_id:client}).toString()}),res;try{res=await post(refresh,"refresh_token")}catch(e){throw Error(`couldn't reach Kolab at ${safeUrl(endpoint)} (${String(e.cause?.code??e.message)})`)}if(!res.ok)throw Error(`Kolab answered ${res.status} at ${safeUrl(endpoint)}`);if(saved.tokens?.access_token)await post(saved.tokens.access_token,"access_token").catch(()=>{return});return"revoked"}async function signInWithBrowser(url2,make,opts){let log=opts.log??((l)=>console.error(l)),server=createServer();await new Promise((resolve,reject)=>server.once("error",reject).listen(0,"127.0.0.1",()=>resolve()));let port=server.address().port;try{let provider=make(`http://127.0.0.1:${port}/callback`,async(u)=>{if(opts.scope)u.searchParams.set("scope",opts.scope);checkAuthorizeUrl(u,url2),log(`Opening your browser to sign in to Kolab. If it doesn't open, go to:
79
+ ${u.toString()}`),await(opts.open??((v)=>openBrowser(v,url2)))(u)}),back=new Promise((resolve,reject)=>{let timer=setTimeout(()=>reject(Error(`the sign-in took too long; ${opts.again??"run konjir login again"}`)),opts.timeoutMs??300000);timer.unref(),server.on("request",(req,res)=>{let u=new URL(req.url??"/",`http://127.0.0.1:${port}`);if(u.pathname!=="/callback"){res.writeHead(404).end();return}if(u.searchParams.get("state")!==provider.expectedState){res.writeHead(400,{"content-type":"text/html"}).end(done(!1,"That answer was for another sign-in."));return}clearTimeout(timer);let error2=u.searchParams.get("error");if(res.writeHead(error2?400:200,{"content-type":"text/html","cache-control":"no-store","referrer-policy":"no-referrer"}).end(done(!error2,error2?"Return to your terminal.":"You can close this tab and return to your terminal.")),error2)reject(Error(`Kolab didn't sign you in: ${u.searchParams.get("error_description")??error2}`));else resolve(u.searchParams)})});back.catch(()=>{return});let first=new StreamableHTTPClientTransport(new URL(url2),{authProvider:provider}),probe=new Client({name:"konjir-cli",version:"0.6.0"},{versionNegotiation:{mode:"auto"}});try{await probe.connect(first),await probe.close()}catch(e){if(!(e instanceof UnauthorizedError))throw e;await first.finishAuth(await back)}return provider}finally{server.close()}}async function login(url2,opts={}){checkKolabUrl(url2);let log=opts.log??((l)=>console.error(l)),before=new StoredLogin(url2,{path:opts.path}).saved(),provider=await signInWithBrowser(url2,(redirectUrl,onAuthorize)=>new StoredLogin(url2,{path:opts.path,redirectUrl,fresh:!0,clientName:opts.clientName,yieldTo:opts.yieldTo,onAuthorize}),opts),kept=new StoredLogin(url2,{path:opts.path}),client=new Client({name:"konjir-cli",version:"0.6.0"},{versionNegotiation:{mode:"auto"}});await client.connect(new StreamableHTTPClientTransport(new URL(url2),{authProvider:kept,fetch:kept.fetch}));let me;try{me=(await client.callTool({name:"konjir_whoami",arguments:{}})).structuredContent}finally{await client.close()}if(!provider.yielded&&before.tokens?.refresh_token&&before.tokens.refresh_token!==kept.saved().tokens?.refresh_token)await revoke(url2,before).catch((e)=>log(`warning: the sign-in this one replaces wasn't revoked: ${e.message}. It lapses within 30 days unused.`));return{...me,yielded:provider.yielded}}class MemoryLogin{opts;client;kept;discovery;verifier="";expectedState=randomBytes(24).toString("base64url");constructor(opts){this.opts=opts}get redirectUrl(){return this.opts.redirectUrl}get clientMetadata(){return{client_name:"konjir CLI",redirect_uris:[REDIRECT],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}state(){return this.expectedState}clientInformation(){return this.client}saveClientInformation(c){this.client=c}tokens(){return this.kept}saveTokens(t){this.kept=t}async redirectToAuthorization(u){if(!this.opts.onAuthorize)throw Error("this sign-in has ended");await this.opts.onAuthorize(u)}saveCodeVerifier(v){this.verifier=v}codeVerifier(){return this.verifier}saveDiscoveryState(d){this.discovery=d}discoveryState(){return this.discovery}invalidateCredentials(scope){if(scope==="all"||scope==="client")this.client=void 0;if(scope==="all"||scope==="tokens")this.kept=void 0;if(scope==="all"||scope==="verifier")this.verifier="";if(scope==="all"||scope==="discovery")this.discovery=void 0}async revoke(url2){let saved={client:this.client,tokens:this.kept};this.kept=void 0,await revoke(url2,saved)}}function ephemeralLogin(url2,opts={}){return checkKolabUrl(url2),signInWithBrowser(url2,(redirectUrl,onAuthorize)=>new MemoryLogin({redirectUrl,onAuthorize}),{again:"run konjir connect again",...opts})}async function logout(url2,opts={}){let refused;try{checkKolabUrl(url2)}catch(e){refused=e.message}if(refused&&!opts.forget)throw Error(`${refused}. To drop the sign-in kept for it without contacting Kolab, run konjir logout --forget`);let provider=new StoredLogin(url2,{path:opts.path,skipUrlCheck:!!refused});if(refused)return provider.locked(async(owner)=>{let had=!!provider.saved().tokens;return await provider.forget(owner),{had,revoked:!1,why:"konjir doesn't contact Kolab over http to another host"}});return provider.locked(async(owner)=>{let saved=provider.saved();if(!saved.tokens)return await provider.forget(owner),{had:!1,revoked:!1};let revoked=!1;try{revoked=await revoke(url2,saved)==="revoked"}catch(e){if(!opts.forget)throw Error(`${e.message}, so your sign-in to ${safeUrl(url2)} wasn't revoked and is still kept: run konjir logout again, or konjir logout --forget to drop it anyway`)}return await provider.forget(owner),{had:!0,revoked}})}import{spawn}from"node:child_process";import{randomBytes as randomBytes2}from"node:crypto";import{closeSync as closeSync2,constants,existsSync as existsSync2,fstatSync,lstatSync as lstatSync2,mkdirSync as mkdirSync2,openSync as openSync2,readSync,readlinkSync,realpathSync,renameSync as renameSync2,statSync as statSync2,unlinkSync as unlinkSync2,writeFileSync as writeFileSync2}from"node:fs";import{homedir as homedir2}from"node:os";import{basename,dirname as dirname2,join as join2,sep}from"node:path";import{createInterface}from"node:readline/promises";import{fileURLToPath}from"node:url";class JsoncError extends Error{what;offset;constructor(what,offset,text){super(`${what} on line ${text.slice(0,offset).split(`
80
+ `).length}`);this.what=what;this.offset=offset}}var MAX_DEPTH=512;function*tokens(text,start=0,end=text.length,opts={}){let i=start;while(i<end){let c=text[i];if(c===" "||c==="\t"||c===`
81
+ `||c==="\r"||c==="\uFEFF"){i++;continue}if(c==="/"&&text[i+1]==="/"){let from=i;while(i<end&&text[i]!==`
82
+ `)i++;if(opts.comments)yield{kind:"comment",offset:from,end:i};continue}if(c==="/"&&text[i+1]==="*"){let close=text.indexOf("*/",i+2);if(close<0||close+2>end)throw new JsoncError("an unclosed comment",i,text);if(opts.comments)yield{kind:"comment",offset:i,end:close+2};i=close+2;continue}if("{}[]:,".includes(c)){yield{kind:c,offset:i,end:i+1},i++;continue}if(c==='"'){let j=i+1;while(j<end&&text[j]!=='"'){if(text[j]==="\\")j++;if(text[j]===`
83
+ `)break;j++}if(j>=end||text[j]!=='"')throw new JsoncError("an unclosed string",i,text);let value;try{value=JSON.parse(text.slice(i,j+1))}catch{throw new JsoncError("a malformed string",i,text)}yield{kind:"string",offset:i,end:j+1,value},i=j+1;continue}let m=/^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/.exec(text.slice(i,end));if(m&&m[0]){yield{kind:"number",offset:i,end:i+m[0].length,value:Number(m[0])},i+=m[0].length;continue}let w=/^(true|false|null)\b/.exec(text.slice(i,end));if(w){yield{kind:"word",offset:i,end:i+w[0].length,value:w[0]==="null"?null:w[0]==="true"},i+=w[0].length;continue}throw new JsoncError(`an unexpected ${JSON.stringify(c)}`,i,text)}yield{kind:"eof",offset:end,end}}function parseTree(text){let it=tokens(text),current=it.next().value,next=()=>{current=it.next().value},tok=()=>current,value=(depth=0)=>{let start=tok();if(depth>MAX_DEPTH)throw new JsoncError(`nesting deeper than ${MAX_DEPTH} levels`,start.offset,text);if(start.kind==="string"||start.kind==="number")return next(),{type:start.kind,offset:start.offset,length:start.end-start.offset,value:start.value};if(tok().kind==="word")return next(),{type:start.value===null?"null":"boolean",offset:start.offset,length:start.end-start.offset,value:start.value};if(tok().kind==="{"||tok().kind==="["){let object2=tok().kind==="{",close=object2?"}":"]",children=[];next();while(tok().kind!==close){if(object2){if(tok().kind!=="string")throw new JsoncError("a property name expected",tok().offset,text);let key={type:"string",offset:tok().offset,length:tok().end-tok().offset,value:tok().value};if(next(),tok().kind!==":")throw new JsoncError("a colon expected",tok().offset,text);next();let v=value(depth+1);children.push({type:"property",offset:key.offset,length:v.offset+v.length-key.offset,value:key.value,children:[key,v]})}else children.push(value(depth+1));if(tok().kind===","){next();continue}if(tok().kind!==close)throw new JsoncError(`a comma or ${close} expected`,tok().offset,text)}let end=tok().end;return next(),{type:object2?"object":"array",offset:start.offset,length:end-start.offset,children}}throw new JsoncError(tok().kind==="eof"?"an unexpected end":"a value expected",tok().offset,text)},root=value();if(tok().kind!=="eof")throw new JsoncError("an end expected",tok().offset,text);return root}function valueOf(n){if(n.type==="object")return Object.fromEntries((n.children??[]).map((p)=>[p.value,valueOf(p.children[1])]));if(n.type==="array")return(n.children??[]).map(valueOf);return n.value}var member=(obj,key)=>obj.type==="object"?obj.children?.filter((p)=>p.value===key).at(-1)?.children?.[1]:void 0,commentsOf=(text)=>[...tokens(text,0,text.length,{comments:!0})].filter((t)=>t.kind==="comment").map((t)=>text.slice(t.offset,t.end));var HARNESSES=["opencode","claude"],ROLES=["product","engineer"],LABEL=/^[a-z0-9][a-z0-9-]{0,23}$/;function parseAgents(values){if(!values.length)return ROLES.map((r)=>({label:r,role:r}));let out=[];for(let v of values){let[label,role,extra]=v.split(":");if(extra!==void 0||!LABEL.test(label??""))throw Error(`--agent ${v}: give <label>[:<role>], the label up to 24 lowercase letters, digits and '-'`);let r=role??(ROLES.includes(label)?label:void 0);if(!r||!ROLES.includes(r))throw Error(`--agent ${v}: say the agent's role, ${ROLES.map((x)=>`${label}:${x}`).join(" or ")}`);if(out.some((a)=>a.label===label))throw Error(`--agent ${label} is named twice`);out.push({label,role:r})}return out}function mcpUrl(url2){let u=new URL(url2);if(u.protocol!=="https:"&&u.protocol!=="http:")throw Error(`--url ${url2}: give Kolab's https URL`);if(u.username||u.password)throw Error("--url: give Kolab's URL without a user name or password in it; konjir connect writes it into your harness's config");if(u.search||u.hash)throw Error("--url: give Kolab's URL without a query or fragment");if(u.pathname==="/"||u.pathname==="")u.pathname="/mcp";return u.toString()}var entryScope=(kolab,role,agent)=>`konjir kolab:${kolab} role:${role} agent:${agent}`,opencodeEntry=(e)=>({type:"remote",url:e.url,oauth:{scope:entryScope(e.kolab,e.role,e.agent)}}),claudeEntry=(e)=>({type:"http",url:e.url,oauth:{scopes:entryScope(e.kolab,e.role,e.agent)}}),claudeBridgeEntry=(e,command)=>({type:"stdio",command,args:[],env:{KONJIR_URL:e.url,KONJIR_TOKEN:"",KONJIR_AGENT:e.agent,KONJIR_SCOPE:entryScope(e.kolab,e.role,e.agent)}}),CHANNEL_CLIENT_NAME="konjir channel (Claude Code)";function bridgeCommand(moduleUrl=import.meta.url){try{let self=realpathSync(fileURLToPath(moduleUrl)),where=dirname2(self);if(!["src","dist"].includes(basename(where))||basename(dirname2(where))!=="cli"||basename(dirname2(dirname2(where)))!=="apps")return;let root=dirname2(dirname2(dirname2(where))),json=(path)=>JSON.parse(readText(path)||"{}"),workspace=json(join2(root,"package.json"));if(workspace.name!=="kolab"||!Array.isArray(workspace.workspaces))return;if(!existsSync2(join2(root,".git")))return;if(json(join2(root,"apps","cli","package.json")).name!=="konjir")return;if(json(join2(root,"apps","channel-bridge","package.json")).name!=="@konjir/channel-bridge")return;let start=realpathSync(join2(root,"apps","channel-bridge","scripts","start.sh"));if(!inside(self,realpathSync(join2(root,"apps","cli")))||!inside(start,realpathSync(join2(root,"apps","channel-bridge"))))return;return start}catch{return}}function opencodePath(opts){let dir=opts.global?join2(opts.env.XDG_CONFIG_HOME||join2(opts.env.HOME||homedir2(),".config"),"opencode"):opts.cwd,json=join2(dir,"opencode.json"),withComments=join2(dir,"opencode.jsonc");return!existsSync2(json)&&existsSync2(withComments)?withComments:json}var claudeUserConfig=(env)=>join2(env.CLAUDE_CONFIG_DIR||env.HOME||homedir2(),".claude.json");function mergeOpencode(path,before,entries,force){let text=before.trim()?before:`{
84
+ "$schema": "https://opencode.ai/config.json"
85
+ }
86
+ `,root=parseOrRefuse(path,text,"OpenCode");if(root.type!=="object")throw Error(`${path} isn't an OpenCode configuration (not a JSON object), so konjir connect won't touch it`);let mcp=member(root,"mcp");if(mcp&&mcp.type!=="object")throw Error(`${path}: its "mcp" is ${mcp.type==="null"?"null":"not an object"}, so konjir connect won't touch it: make it {} or remove it, then run konjir connect again`);refuseTaken(path,entries,Object.keys(mcp?valueOf(mcp):{}),force);let after=setEntries(text,"mcp",entries.map((e)=>[e.name,opencodeEntry(e)]));return checkMerge(path,text,after,"mcp",entries.map((e)=>[e.name,opencodeEntry(e)])),after}function mergeClaude(path,before,entries,force,make=claudeEntry){let set=entries.map((e)=>[e.name,make(e)]);if(!before.trim())return JSON.stringify({mcpServers:Object.fromEntries(set)},null,2);let config2;try{config2=JSON.parse(before)}catch(e){throw Error(`${path} isn't JSON (${e.message}), so konjir connect won't touch it: fix it, then run konjir connect again`)}if(!config2||typeof config2!=="object"||Array.isArray(config2))throw Error(`${path} isn't a Claude Code MCP configuration (not a JSON object), so konjir connect won't touch it`);let raw=config2,servers="mcpServers"in raw?raw.mcpServers:{};if(!servers||typeof servers!=="object"||Array.isArray(servers))throw Error(`${path}: its "mcpServers" is ${servers===null?"null":"not an object"}, so konjir connect won't touch it: make it {} or remove it, then run konjir connect again`);refuseTaken(path,entries,Object.keys(servers),force);let after=setEntries(before,"mcpServers",set);checkMerge(path,before,after,"mcpServers",set);try{JSON.parse(after)}catch{throw Error(`konjir connect couldn't merge into ${path} safely, so nothing is written: add the entries by hand`)}return after}function parseOrRefuse(path,text,reader){try{return parseTree(text)}catch(e){if(!(e instanceof JsoncError))throw e;throw Error(`${path} isn't JSON that ${reader} reads (${e.message}), so konjir connect won't touch it: fix it, then run konjir connect again`)}}function setEntries(text,section,set){for(let[key,value]of set){let tree=parseTree(text),servers=member(tree,section);text=servers?setMember(text,servers,key,value):setMember(text,tree,section,{[key]:value})}return text}var canonical=(v)=>JSON.stringify(v,(_k,x)=>x&&typeof x==="object"&&!Array.isArray(x)?Object.fromEntries(Object.entries(x).sort(([a],[b])=>a<b?-1:a>b?1:0)):x);function checkMerge(path,before,after,section,set){let refuse=(why)=>Error(`konjir connect couldn't merge into ${path} safely (${why}), so nothing is written: add the entries by hand, or tell us at github.com/konjir/kolab`),got;try{got=valueOf(parseTree(after))}catch{throw refuse("the result wouldn't parse")}let was=valueOf(parseTree(before.trim()?before:"{}")),want={...was,[section]:{...was[section]??{},...Object.fromEntries(set)}};if(canonical(got)!==canonical(want))throw refuse("the result would differ from the file with just the entries added");let kept=commentsOf(after),k=0;for(let c of commentsOf(before)){while(k<kept.length&&kept[k]!==c)k++;if(k++>=kept.length)throw refuse("a comment would be lost")}}var indentUnit=(text)=>{let first=/\n([ \t]+)"/.exec(text)?.[1];return first?.startsWith("\t")?"\t":first||" "},indentAt=(text,offset)=>/^[ \t]*/.exec(text.slice(text.lastIndexOf(`
87
+ `,offset-1)+1))[0],sameLine=(text,a,b)=>!text.slice(a,b).includes(`
88
+ `);function setMember(text,obj,key,value){let eol=text.includes(`\r
89
+ `)?`\r
90
+ `:`
91
+ `,unit=indentUnit(text),show=(v,base2)=>JSON.stringify(v,null,unit).split(`
92
+ `).join(eol+base2),members2=obj.children??[],copies=members2.filter((p)=>p.value===key);if(copies.length){for(let p of[...copies].reverse()){let v=p.children[1];text=text.slice(0,v.offset)+show(value,indentAt(text,p.offset))+text.slice(v.offset+v.length)}return text}let close=obj.offset+obj.length-1,objIndent=indentAt(text,obj.offset),last=members2.at(-1),from=last?last.offset+last.length:obj.offset+1,after=[...tokens(text,from,close,{comments:!0})].filter((t)=>t.kind!=="eof"),at=after.length?after.at(-1).end:from;if(after.at(-1)?.kind==="comment"&&text[at-1]==="\r")at--;let comma=after.some((t)=>t.kind===","),base=last&&!sameLine(text,obj.offset,last.offset)?indentAt(text,last.offset):objIndent+unit,tail=sameLine(text,at,close)?`${eol}${objIndent}`:"",line=`${eol}${base}${JSON.stringify(key)}: ${show(value,base)}${last&&comma?",":""}${tail}`;return`${last&&!comma?`${text.slice(0,from)},${text.slice(from,at)}`:text.slice(0,at)}${line}${text.slice(at)}`}function refuseTaken(where,entries,names,force){let taken=entries.filter((e)=>names.includes(e.name)).map((e)=>e.name);if(taken.length&&!force)throw Error(`${where} already has ${taken.join(", ")}. konjir connect won't overwrite ${taken.length===1?"it":"them"}: pass --force to replace ${taken.length===1?"it":"them"}, or choose other labels with --agent`)}function unifiedDiff(path,before,after,exists){let a=before?before.split(`
93
+ `):[],b=after.split(`
94
+ `),n=a.length,m=b.length,lcs=Array.from({length:n+1},()=>Array(m+1).fill(0));for(let i2=n-1;i2>=0;i2--)for(let j2=m-1;j2>=0;j2--)lcs[i2][j2]=a[i2]===b[j2]?lcs[i2+1][j2+1]+1:Math.max(lcs[i2+1][j2],lcs[i2][j2+1]);let ops=[],i=0,j=0;while(i<n||j<m)if(i<n&&j<m&&a[i]===b[j])ops.push({t:" ",s:a[i],i,j}),i++,j++;else if(i<n&&(j>=m||lcs[i+1][j]>=lcs[i][j+1]))ops.push({t:"-",s:a[i],i,j}),i++;else ops.push({t:"+",s:b[j],i,j}),j++;let out=[`--- ${exists?path:"/dev/null"}`,`+++ ${path}`],changed=ops.map((o,k)=>o.t!==" "?k:-1).filter((k)=>k>=0);for(let k=0;k<changed.length;){let start=Math.max(0,changed[k]-3),end=changed[k];while(k<changed.length&&changed[k]<=end+6)end=changed[k],k++;let stop=Math.min(ops.length-1,end+3),hunk=ops.slice(start,stop+1),aLen=hunk.filter((o)=>o.t!=="+").length,bLen=hunk.filter((o)=>o.t!=="-").length;out.push(`@@ -${aLen?hunk[0].i+1:hunk[0].i},${aLen} +${bLen?hunk[0].j+1:hunk[0].j},${bLen} @@`);for(let o of hunk)out.push(`${o.t}${o.s}`)}return out.join(`
95
+ `)}function writeAtomically(path,text,opts={}){let target=path,link=linkTarget(path);if(link){if(!link.real)throw Error(`${path} is a link to ${link.to}, which isn't there; konjir won't write through it`);target=link.real}let dir=dirname2(target);mkdirSync2(dir,{recursive:!0});let mode=420;try{mode=statSync2(target).mode&511}catch{}let tmp=join2(dir,`.${basename(target)}.${randomBytes2(6).toString("hex")}.tmp`);writeFileSync2(tmp,text,{mode,flag:"wx"});try{if(opts.within!==void 0){let now=linkTarget(path),real=join2(realpathSync(dirname2(target)),basename(target));if((link?now?.real!==target:!!now)||!inside(real,opts.within))throw Error(`${path} changed while konjir connect wrote it, or leads outside ${opts.within}; nothing written`)}if(existsSync2(target)&&!lstatSync2(target).isFile())throw Error(`${target} isn't a regular file; nothing written`);renameSync2(tmp,target)}catch(e){try{unlinkSync2(tmp)}catch{}throw e}}var MAX_CONFIG_BYTES=1048576;function readText(path){let fd;try{fd=openSync2(path,constants.O_RDONLY|(constants.O_NONBLOCK??0))}catch(e){if(e.code==="ENOENT")return"";throw Error(`konjir connect can't read ${path} (${e.code??e})`)}try{let st=fstatSync(fd);if(!st.isFile())throw Error(`${path} isn't a regular file, so konjir connect won't read or write it`);if(st.size>MAX_CONFIG_BYTES)throw Error(`${path} is over ${MAX_CONFIG_BYTES/1024/1024} MiB, far more than a harness's config; konjir connect won't read it`);let buf=Buffer.alloc(st.size+1),n=0;for(let r;n<buf.length&&(r=readSync(fd,buf,n,buf.length-n,n))>0;)n+=r;if(n>st.size)throw Error(`${path} grew while konjir connect read it; run konjir connect again`);return buf.subarray(0,n).toString("utf8")}finally{closeSync2(fd)}}var terminalIO=(person,signInAgent)=>({log:(line)=>console.log(line),interactive:!!process.stdin.isTTY,async confirm(question){let rl=createInterface({input:process.stdin,output:process.stderr});try{return/^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim())}finally{rl.close()}},run:(cmd,args,opts)=>new Promise((resolve)=>{let child=spawn(cmd,args,{cwd:opts.cwd,stdio:"inherit"});child.on("error",()=>resolve(-1)),child.on("exit",(code)=>resolve(code??-1))}),person,signInAgent});function channelSteps(entries,cwd,global,signedIn){return[`Start Claude Code with the Konjir channel${global?"":`, from ${cwd}`}:`,` claude --dangerously-load-development-channels ${entries.map((e)=>`server:${e.name}`).join(" ")}`," Channels need Claude Code signed in with a claude.ai account (not an API key); without one the tools still work, and no channel messages arrive.",...global?[]:[" Claude Code asks first whether to use the servers in this project's .mcp.json: approve the konjir- ones."," These entries name this checkout's absolute path, so they work only on this machine: don't commit them (or use --global)."],' At the warning, choose "I am using this for local development".',signedIn?" Each entry is one Konjir server: Kolab's tools and its channel, on its agent's sign-in. Don't also add Kolab's HTTP server as the same agent: one session each (ENF4).":` On first start each entry signs in by itself in your browser, as its own agent: Kolab's page arrives with ${entries.map((e)=>e.agent).join(" and ")} chosen in turn. Check them, then Allow.`]}function signInSteps(harness,entries,cwd,global){if(harness==="opencode")return[`Sign each entry in, one at a time${global?"":`, from ${cwd}`}:`,...entries.map((e)=>` opencode mcp auth ${e.name} # Kolab's page arrives with ${e.agent}, kolab ${e.kolab} and ${e.role} chosen: check them, then Allow`)];return[`Sign each entry in, one at a time, from Claude Code${global?"":` started in ${cwd}`}:`," 1. Run claude, and type /mcp.",...global?[]:[" Claude Code asks first whether to use the servers in this project's .mcp.json: approve the konjir- ones."],...entries.map((e,k)=>` ${k+2}. Choose ${e.name}, then Authenticate. Kolab's page arrives with ${e.agent}, kolab ${e.kolab} and ${e.role} chosen: check them, then Allow.`)]}async function connectHarness(opts,io){if(opts.kolab!==void 0&&!/^[a-z0-9][a-z0-9-]*$/.test(opts.kolab))throw Error("--kolab names a kolab: lowercase letters, digits and -");if(opts.http&&opts.harness!=="claude")throw Error("--http is for Claude Code: OpenCode's entries are always its remote MCP server");let channel=opts.harness==="claude"&&!opts.http,bridge=channel?opts.bridge??bridgeCommand():void 0;if(channel&&!bridge)throw Error("konjir connect claude sets up the Konjir channel, Claude Code's one Konjir server, which runs from a checkout of github.com/konjir/kolab, and this konjir isn't running from one. Run it as <checkout>/bin/konjir connect claude, or pass --http for Claude Code's plain HTTP entry (no channel)");let claudeMake=bridge?(e)=>claudeBridgeEntry(e,bridge):claudeEntry,session=await io.person(),closed=!1,onSignal=(signal)=>{closeSession().finally(()=>{process.kill(process.pid,signal)})},closeSession=async()=>{if(closed)return;closed=!0,process.off("SIGINT",onSignal),process.off("SIGTERM",onSignal),await session.close()};process.once("SIGINT",onSignal),process.once("SIGTERM",onSignal);try{let{me}=session;if(me.kind!=="person")throw Error(`konjir connect makes agents as you, and the token it was given (KONJIR_TOKEN or --token) works as ${me.actor}${me.owner?`, an agent of ${me.owner}'s`:""}. Unset it, and konjir connect signs you in as yourself for a moment, in your browser`);let kolab=opts.kolab??me.kolab,entries=opts.agents.map((a)=>({name:`konjir-${a.label}`,agent:`${me.actor}-${a.label}`,label:a.label,role:a.role,kolab,url:opts.url})),change,commands=[];if(opts.harness==="opencode"){let path=opencodePath(opts),before=readText(path);change={path,before,after:mergeOpencode(path,before,entries,opts.force),exists:existsSync2(path)}}else if(!opts.global){let path=join2(opts.cwd,".mcp.json"),before=readText(path);change={path,before,after:mergeClaude(path,before,entries,opts.force,claudeMake),exists:existsSync2(path)}}else{let path=claudeUserConfig(opts.env),servers={},parsed;try{parsed=JSON.parse(readText(path)||"{}")}catch{throw Error(`${path} isn't JSON, so konjir connect can't tell which servers Claude Code already has: fix it, then run konjir connect again`)}let s=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed.mcpServers??{}:null;if(!s||typeof s!=="object"||Array.isArray(s))throw Error(`${path}: its "mcpServers" isn't an object, so konjir connect can't tell which servers Claude Code already has`);servers=s,refuseTaken(`Claude Code's user settings (${path})`,entries,Object.keys(servers),opts.force),commands=entries.flatMap((e)=>[...e.name in servers?[["claude","mcp","remove","--scope","user",e.name]]:[],["claude","mcp","add-json","--scope","user",e.name,JSON.stringify(claudeMake(e))]])}io.log(`konjir connect ${opts.harness}: ${entries.length} ${entries.length===1?"entry":"entries"} for kolab ${kolab} at ${opts.url}, one agent each:`);for(let e of entries)io.log(` ${e.name} as ${e.agent}, ${e.role}`);if(io.log(""),change){let target=linkTarget(change.path);if(target){let root=opts.global?dirname2(change.path):opts.cwd;if(!target.real)throw Error(`${change.path} is a link to ${target.to}, which isn't there; konjir connect won't write through it. Remove the link, then run konjir connect again`);if(!inside(target.real,root)&&!opts.forcePath)throw Error(`${change.path} is a link to ${target.real}, outside ${root}; konjir connect won't write there. Pass --force-path if you mean it to`);io.log(`${change.path} is a link to ${target.real}, which konjir connect would change.`)}if(change.before===change.after)io.log(`${change.path} already says exactly this.`);else io.log(unifiedDiff(change.path,change.before,change.after,change.exists))}else{io.log("Claude Code's own command will write them to your user settings:");for(let c of commands)io.log(` ${c.map(shellWord).join(" ")}`)}if(io.log(""),!opts.yes){if(!io.interactive)throw Error("konjir connect asks before it writes anything: run it in a terminal, or pass --yes");if(!await io.confirm(change?`Make ${entries.length===1?"this agent":"these agents"} and write ${change.path}?`:"Make these agents and run those commands?"))return io.log("Nothing written, and no agent made."),[]}for(let e of entries){let r=await session.call("create_agent",{label:e.label});if(r.agent!==e.agent)throw Error(`Kolab made ${r.agent}, not ${e.agent}; nothing written`);io.log(r.created?`Made your agent ${r.agent}.`:`Using your agent ${r.agent}.`)}if(await closeSession(),change){if(readText(change.path)!==change.before)throw Error(`${change.path} changed while konjir connect was waiting; nothing written. Run konjir connect again`);writeAtomically(change.path,change.after,opts.forcePath?{}:{within:opts.global?dirname2(change.path):opts.cwd}),io.log(`Wrote ${change.path}. It holds no token: each entry signs in by itself.`)}else{for(let c of commands)if(await io.run(c[0],c.slice(1),{cwd:opts.cwd})!==0)throw Error(`${c.slice(0,3).join(" ")} didn't succeed${c[0]==="claude"?" (is Claude Code installed, and claude on your PATH?)":""}`);io.log("Claude Code has them in your user settings. They hold no token: each entry signs in by itself.")}if(channel){let signed=0;if(opts.auth&&io.signInAgent)for(let e of entries){io.log(`Signing ${e.name} in as ${e.agent}, in your browser. Kolab's page arrives with ${e.agent}, kolab ${e.kolab} and ${e.role} chosen: check them, then Allow.`);try{let actor=await io.signInAgent(e,agentCredentials(e.agent,opts.env));if(actor!==e.agent)throw Error(`it worked as ${actor}, not ${e.agent}`);io.log(`${e.name} is signed in as ${e.agent}.`),signed++}catch(err){io.log(`${e.name} didn't sign in (${err.message}). It signs in by itself, in your browser, when Claude Code first starts it.`)}}for(let line of channelSteps(entries,opts.cwd,opts.global,signed===entries.length))io.log(line);return entries}if(opts.harness==="opencode"&&opts.auth){for(let[k,e]of entries.entries()){io.log(`Signing ${e.name} in as ${e.agent}. Kolab's page arrives with ${e.agent}, kolab ${e.kolab} and ${e.role} chosen: check them, then Allow.`);let code=await io.run("opencode",["mcp","auth",e.name],{cwd:opts.cwd});if(code!==0){io.log(`opencode mcp auth ${e.name} didn't finish${code===-1?" (is OpenCode installed, and opencode on your PATH?)":""}.`);for(let line of signInSteps("opencode",entries.slice(k),opts.cwd,opts.global))io.log(line);return entries}}io.log(`Connected: each entry works as its own agent in ${kolab}.`)}else for(let line of signInSteps(opts.harness,entries,opts.cwd,opts.global))io.log(line);return entries}finally{await closeSession()}}function linkTarget(path){let st;try{st=lstatSync2(path)}catch{return}if(!st.isSymbolicLink())return;let to=readlinkSync(path);try{return{to,real:realpathSync(path)}}catch{return{to}}}function inside(path,root){let r=root;try{r=realpathSync(root)}catch{}return path===r||path.startsWith(r.endsWith(sep)?r:r+sep)}var shellWord=(w)=>/^[A-Za-z0-9_./:=@-]+$/.test(w)?w:`'${w.replace(/'/g,"'\\''")}'`;var ROLES2=["product","engineer"];class ClientOnly extends Error{}var server=()=>import("@konjir/server").catch((e)=>{let err=e;if(err?.code==="ERR_MODULE_NOT_FOUND"&&/^Cannot find (package|module) '@konjir\/server'/.test(String(err.message)))throw new ClientOnly("this konjir is the client only, so it has no serve. Run `bin/konjir serve` from a Kolab checkout (github.com/konjir/kolab), or point KONJIR_URL at a running Kolab.");throw e}),toolName=(verb)=>verb.startsWith("konjir_")?verb:`konjir_${verb}`;async function connect(url2,auth2){let client=new Client({name:"konjir-cli",version:"0.6.0"},{versionNegotiation:{mode:"auto"}});if(await client.connect(new StreamableHTTPClientTransport(new URL(url2),typeof auth2==="string"?{requestInit:{headers:{Authorization:`Bearer ${auth2}`}}}:{authProvider:auth2,...auth2 instanceof StoredLogin?{fetch:auth2.fetch}:{}})),auth2 instanceof StoredLogin)client.onerror=()=>auth2.releaseIdleLock();return client}async function watch(client,onUpdate){let me=await call(client,"whoami"),read=async(uri)=>{let c=(await client.readResource({uri})).contents[0];return c&&"text"in c?JSON.parse(c.text):null};return client.setNotificationHandler("notifications/resources/updated",async(n)=>{await onUpdate(n.params.uri,await read(n.params.uri))}),{uris:me.subscribe,read,subscription:await client.listen({resourceSubscriptions:me.subscribe})}}function listenRefusal(e){let err=e;if(err?.code!==-32003)return;return typeof err.data?.reason==="string"?err.data.reason:"refused"}var insufficientScope=(e)=>e?.constructor?.mcpBrand==="mcp.InsufficientScopeError",adminOnly=(verb)=>`${toolName(verb)} is an admin verb: only the admin token may call it, and this token is an agent session's. Ask whoever runs Kolab.`;async function call(client,verb,args={}){let r;try{r=await client.callTool({name:toolName(verb),arguments:args})}catch(e){if(insufficientScope(e))throw Error(adminOnly(verb));throw e}let text=(r.content??[]).map((c)=>c.type==="text"?c.text:"").join(`
96
+ `);if(r.isError)throw Error(text);return r.structuredContent??text}var usage=(canServe)=>`konjir — Kolab from a shell. Same verbs as the MCP server.
97
+
98
+ konjir instructions the operating rules and precedent (read this first)
99
+ konjir instructions reviewer how to review a version that waits for you
100
+ konjir tools every verb, one line each
101
+ konjir help <verb> a verb's description and parameters
102
+ konjir <verb> key=value ... call a verb; values parse as JSON when they can,
103
+ e.g. elements='[{"id":"R1","text":"..."}]'
104
+ konjir <verb> --json '{...}' the same, with all arguments as one JSON object
105
+
106
+ Shortcuts: konjir resolve <address> · konjir read <node> [version] · konjir stale [all] · konjir queries [all]
107
+ Push: konjir watch prints your inbox, then a JSON line each time it changes (questions, notes,
108
+ answers, marks, review requests and verdicts). konjir watch --once waits for the next change,
109
+ prints it and exits.
110
+ Addresses: kj:[<kolab>/]<node>[@<version>][#<element>][~q({"exact":"words"})]; kj:<node> is a node in your kolab
111
+ Sign in: konjir login [--kolab <name>] [--role product|engineer] [--agent <agent>] signs in with your browser
112
+ (GitHub, through Kolab): you choose who this CLI works as (an agent of yours, by default; --agent
113
+ preselects one, and refuses a sign-in as anyone else), the kolab and the role.
114
+ Every later command uses that sign-in, renewing it by itself. konjir logout revokes it.
115
+ Harnesses: konjir connect opencode|claude [--kolab <k>] [--agent <label>[:<role>]]… [--global] [--force] [--yes]
116
+ [--no-auth] [--http] connects a harness to a kolab, one agent per entry (by default product and engineer):
117
+ it makes or reuses your agents <you>-<label> (signed in as yourself for a moment, in memory only, then
118
+ revoked: on Kolab's page, choose Yourself by hand), shows the change to opencode.json or .mcp.json (with --global, your own settings) and asks
119
+ first, then signs each entry in as its agent. --force replaces konjir-<label> entries already there;
120
+ --force-path writes a config file that links outside the project. For Claude Code each entry is the
121
+ Konjir channel (from this checkout): Kolab's tools and the inbox pushed into the session, on one sign-in;
122
+ --http writes Claude Code's plain HTTP entry instead, with no channel.
123
+ Connection: KONJIR_URL (default http://127.0.0.1:7420/mcp) and KONJIR_TOKEN, or --url / --token; with no
124
+ token, the sign-in konjir login keeps for that URL.
125
+ Version: konjir --version
126
+ ${canServe?`Server: konjir serve [--port 7420] [--data .konjir | --database-url postgres://…] [--admin-token T] [--public-host kolab.example.com]
127
+ Kolab runs structural checks only and makes no model calls; reviewing agents review.
128
+ Sign-in with GitHub (D55): KONJIR_GITHUB_CLIENT_ID and KONJIR_GITHUB_CLIENT_SECRET, a GitHub OAuth app's,
129
+ whose callback is <origin>/oauth/callback/github. KONJIR_WEB_TOKEN_SIGN_IN=on keeps pasting a token in the
130
+ web page (on by default without GitHub); KONJIR_HAND_ISSUED_TOKENS=off turns admin-issued session tokens off.
131
+ KONJIR_CLI_NPM_SPEC=konjir@<version> (an exact version, once published) lets the web page show npx <spec>.`:"Server: this konjir is the client only. Kolab runs from a checkout of github.com/konjir/kolab."}`;function parseKv(argv){let out={};for(let i=0;i<argv.length;i++){if(argv[i]==="--json"){Object.assign(out,JSON.parse(argv[++i]));continue}let eq=argv[i].indexOf("=");if(eq<1)throw Error(`expected key=value, got "${argv[i]}"`);let k=argv[i].slice(0,eq),v=argv[i].slice(eq+1);try{out[k]=JSON.parse(v)}catch{out[k]=v}}return out}function flag(argv,name){let i=argv.indexOf(`--${name}`);if(i<0)return;let v=argv[i+1];return argv.splice(i,2),v}function retiredReviewSettings(env,reviewFlag){let mode=reviewFlag??env.KONJIR_REVIEW;if(mode!==void 0&&mode!=="structural")return{refuse:`review mode "${mode}" (${reviewFlag!==void 0?"--review":"KONJIR_REVIEW"}) is no longer supported (W1.7): Kolab has no model reviewer. Its checks are structural, and agents review through konjir_review. Unset it, or set it to structural.`};if(env.KONJIR_REVIEW_MODEL!==void 0&&mode===void 0)return{warn:`ignoring KONJIR_REVIEW_MODEL=${env.KONJIR_REVIEW_MODEL}: Kolab has no model reviewer any more (W1.7), so it calls no model. Unset it.`};return{}}function onOff(env,name){let v=env[name]?.trim().toLowerCase();if(v===void 0||v==="")return;if(["on","1","true","yes"].includes(v))return!0;if(["off","0","false","no"].includes(v))return!1;throw Error(`${name} is on or off`)}function signInSettings(env){let id=env.KONJIR_GITHUB_CLIENT_ID?.trim(),secret=env.KONJIR_GITHUB_CLIENT_SECRET?.trim();if(!!id!==!!secret)throw Error("set both KONJIR_GITHUB_CLIENT_ID and KONJIR_GITHUB_CLIENT_SECRET for sign-in with GitHub, or neither");let github=!!id&&!!secret,webTokenSignIn=onOff(env,"KONJIR_WEB_TOKEN_SIGN_IN")??!github,handIssuedTokens=onOff(env,"KONJIR_HAND_ISSUED_TOKENS")??!0;return{github,webTokenSignIn,handIssuedTokens,describe:[github?"GitHub":"no identity provider (set KONJIR_GITHUB_CLIENT_ID and KONJIR_GITHUB_CLIENT_SECRET)",webTokenSignIn?"a pasted token in the web page":"",handIssuedTokens?"hand-issued session tokens":""].filter(Boolean).join("; "),async identity(load){if(!github)return{};let{GitHubIdentity}=await load();return{identity:new GitHubIdentity({clientId:id,clientSecret:secret})}}}}async function main(argv){let url2=flag(argv,"url")??process.env.KONJIR_URL??"http://127.0.0.1:7420/mcp",token=flag(argv,"token")??process.env.KONJIR_TOKEN,[cmd,...rest]=argv;if(cmd==="--version"){console.log("0.5.0");return}if(!cmd||(cmd==="help"||cmd==="--help")&&!rest[0]){let canServe=await server().then(()=>!0,(e)=>{if(e instanceof ClientOnly)return!1;throw e});console.log(usage(canServe));return}if(cmd==="serve"){let{startServer}=await server(),port=Number(flag(rest,"port")??7420),dataDir=flag(rest,"data")??".konjir",adminToken=flag(rest,"admin-token")??process.env.KONJIR_ADMIN_TOKEN??randomBytes3(18).toString("base64url"),retired=retiredReviewSettings(process.env,flag(rest,"review"));if(retired.refuse)throw Error(retired.refuse);if(retired.warn)console.error(`warning: ${retired.warn}`);console.log("review: Kolab's structural checks, then reviewing agents (konjir_review); Kolab makes no model calls");let publicHost=flag(rest,"public-host")??process.env.KONJIR_PUBLIC_HOST,databaseUrl=flag(rest,"database-url")??process.env.KONJIR_DATABASE_URL,perPerson=process.env.KONJIR_KOLABS_PER_PERSON,kolabsPerPerson=perPerson===void 0||perPerson===""?void 0:Number(perPerson);if(kolabsPerPerson!==void 0&&!(Number.isInteger(kolabsPerPerson)&&kolabsPerPerson>=0))throw Error("KONJIR_KOLABS_PER_PERSON is a whole number");let sign=signInSettings(process.env),cliNpmSpec=process.env.KONJIR_CLI_NPM_SPEC?.trim()||void 0,s=await startServer({port,dataDir,databaseUrl,adminToken,publicHost,kolabsPerPerson,...await sign.identity(server),webTokenSignIn:sign.webTokenSignIn,handIssuedTokens:sign.handIssuedTokens,cliNpmSpec});if(console.log(`sign-in: ${sign.describe}`),console.log(`Kolab listening on ${s.url}`),console.log(`data: ${databaseUrl?withoutPassword(databaseUrl):dataDir}`),!process.env.KONJIR_ADMIN_TOKEN&&!rest.includes("--quiet"))console.log(`admin token: ${adminToken}`);let stop=async()=>{await s.close(),process.exit(0)};process.on("SIGINT",stop),process.on("SIGTERM",stop);return}if(cmd==="connect"){let harness=rest.shift();if(!HARNESSES.includes(harness))throw Error(`konjir connect ${HARNESSES.join("|")} [--kolab <k>] [--agent <label>[:<role>]]… [--global] [--force] [--force-path] [--yes] [--no-auth] [--http] [--url <kolab>]`);let kolab=flag(rest,"kolab"),agents=[];for(let a=flag(rest,"agent");a!==void 0;a=flag(rest,"agent"))agents.push(a);let on=(name)=>{let i=rest.indexOf(`--${name}`);if(i>=0)rest.splice(i,1);return i>=0},opts={global:on("global"),force:on("force"),forcePath:on("force-path"),yes:on("yes"),auth:!on("no-auth"),http:on("http")};if(rest.length)throw Error(`konjir connect: unknown ${rest.join(" ")}`);let mcp=mcpUrl(url2);await connectHarness({harness,url:mcp,kolab,agents:parseAgents(agents),cwd:process.cwd(),env:process.env,...opts},terminalIO(()=>personSession(mcp,token,{kolab}),signInAgent));return}if(cmd==="login"){let kolab=flag(rest,"kolab"),role=flag(rest,"role"),agent=flag(rest,"agent");if(role!==void 0&&!ROLES2.includes(role))throw Error(`--role is one of ${ROLES2.join(", ")}`);if(kolab!==void 0&&!/^[a-z0-9][a-z0-9-]*$/.test(kolab))throw Error("--kolab names a kolab: lowercase letters, digits and -");if(agent!==void 0&&!/^[a-z0-9][a-z0-9-]{0,63}$/.test(agent))throw Error("--agent names an agent of yours, such as ann-product: lowercase letters, digits and -");let scope=["konjir",kolab&&`kolab:${kolab}`,role&&`role:${role}`,agent&&`agent:${agent}`].filter(Boolean).join(" "),me;try{me=await login(url2,{scope})}catch(e){throw unreachable(e,url2)??e}if(agent!==void 0&&me.actor!==agent){let r=await logout(url2,{forget:!0});throw Error(`you signed in as ${me.actor}, not ${agent}, so that sign-in was ${r.revoked?"revoked":"forgotten, unrevoked,"} and nothing is kept: run it again and choose ${agent} on Kolab's page`)}console.log(`Signed in to ${url2} as ${me.actor}${me.kind==="agent"?` (an agent of ${me.owner}'s)`:""}, in kolab ${me.kolab} as ${me.role}.`),console.log(`Kept in ${credentialsPath()}; every konjir command now uses it. Start with: konjir instructions`);return}if(cmd==="logout"){let r=await logout(url2,{forget:rest.includes("--forget")});console.log(!r.had?`No sign-in kept for ${url2}.`:r.revoked?`Signed out of ${url2}: the sign-in is revoked and forgotten.`:`Forgotten, but not revoked at ${url2}${r.why?` (${r.why})`:""}: it lapses within 30 days unused, or an admin can end it.`);return}let stored=token?void 0:new StoredLogin(url2);if(!token&&!stored.signedIn)throw Error("set KONJIR_TOKEN (an agent session token, or the admin token for admin_* verbs), or run konjir login to sign in with your browser");let client;try{client=await connect(url2,token??stored)}catch(e){stored?.releaseLock();let msg=String(e.message??e),far=unreachable(e,url2);if(far)throw far;if(stored&&/401|invalid Konjir token|Unauthorized|run konjir login/i.test(msg))throw Error(`your sign-in to ${url2} has ended or was revoked: run konjir login`);if(/401|invalid Konjir token|Unauthorized/i.test(msg))throw Error(`the Kolab server at ${url2} refused your token. It may have been revoked or mistyped; ask for a new session token.`);throw e}if(cmd==="watch"){let once=rest.includes("--once"),finished=!1,done2=new Promise((resolve,reject)=>{let finish=()=>{finished=!0,resolve()},retries=0,opened=Date.now(),subscribe=(first)=>void watch(client,(uri,body)=>{if(console.log(JSON.stringify({updated:uri,...body})),once)finish()}).then(async(w)=>{if(opened=Date.now(),!once&&first)for(let uri of w.uris)console.log(JSON.stringify({inbox:uri,...await w.read(uri)}));w.subscription.closed.then((how)=>{if(stored?.releaseIdleLock(),!finished&&how!=="local"&&stored){retries=Date.now()-opened>60000?0:retries+1,setTimeout(()=>{if(!finished)subscribe(!1)},retries?Math.min(30000,1000*2**(retries-1)):0);return}if(!finished&&how==="remote")console.error("Kolab closed the subscription; run konjir watch again");finish()})},(e)=>{stored?.releaseIdleLock();let reason=listenRefusal(e);if(reason==="session_ended")reject(Error(stored?`your sign-in to ${url2} has ended or was revoked: run konjir login`:`the Kolab server at ${url2} refused your token. It may have been revoked or mistyped; ask for a new session token.`));else if(reason==="not_subscribable")reject(Error("Kolab refused to subscribe you to those resources: a session can subscribe only to its own kolab's inboxes and its own answers there. Run konjir watch again, which asks konjir_whoami for them afresh"));else if(reason)reject(Error(`Kolab couldn't open your subscription just now (${reason}); run konjir watch again`));else reject(e)});subscribe(!0)});try{await done2}finally{stored?.releaseLock(),await client.close()}return}try{let result;switch(rest.some((a)=>a==="--json"||a.includes("="))&&["resolve","read","stale","queries","instructions"].includes(cmd)?"":cmd){case"tools":result=(await client.listTools()).tools.map((t)=>`${t.name.replace(/^konjir_/,"")} — ${t.description}`).join(`
132
+ `);break;case"help":{let name=toolName(rest[0]),tool=(await client.listTools()).tools.find((t)=>t.name===name);if(!tool)throw Error(`no verb ${rest[0]}${name.startsWith("konjir_admin_")?" for this token: the admin verbs are for the admin token only":""}; run konjir tools`);let schema=tool.inputSchema,params=Object.entries(schema.properties??{}).map(([k,p])=>` ${k}${schema.required?.includes(k)?"":" (optional)"}: ${p.enum?p.enum.join(" | "):p.type??"json"}${p.description?` — ${p.description}`:""}`);result=[`konjir ${rest[0].replace(/^konjir_/,"")} key=value ...`,"",tool.description,"",params.length?params.join(`
133
+ `):" (no parameters)"].join(`
134
+ `);break}case"instructions":{if(rest[0]!==void 0&&rest[0]!=="reviewer")throw Error(`konjir instructions [reviewer]: no instructions "${rest[0]}"`);result=(await client.getPrompt({name:rest[0]==="reviewer"?"konjir_reviewer_instructions":"konjir_operating_instructions"})).messages.map((m)=>m.content.type==="text"?m.content.text:"").join(`
135
+ `);break}case"resolve":result=await call(client,"resolve",{address:rest[0]});break;case"read":result=await call(client,"read_node",{node:rest[0],...rest[1]?{version:Number(rest[1])}:{}});break;case"stale":result=await call(client,"list_stale",{all_layers:rest[0]==="all"});break;case"queries":result=await call(client,"list_queries",{all_layers:rest[0]==="all"});break;default:{let verb={stale:"list_stale",queries:"list_queries",read:"read_node"}[cmd]??cmd;result=await call(client,verb,parseKv(rest))}}console.log(typeof result==="string"?result:JSON.stringify(result,null,2))}finally{stored?.releaseLock(),await client.close()}}async function personSession(url2,token,opts={}){let log=opts.log??((l)=>console.error(l)),open2=async(auth2)=>{let client;try{client=await connect(url2,auth2)}catch(e){if(auth2 instanceof StoredLogin)auth2.releaseIdleLock();throw unreachable(e,url2)??e}try{return{client,me:await call(client,"whoami")}}catch(e){if(auth2 instanceof StoredLogin)auth2.releaseIdleLock();throw await client.close(),e}};if(token){let{client,me}=await open2(token);return{me,call:(verb,args)=>call(client,verb,args),close:()=>client.close()}}let stored=new StoredLogin(url2,{path:opts.path});if(stored.signedIn){let s2=await open2(stored).catch(()=>{return});if(s2?.me.kind==="person")return{me:s2.me,call:(verb,args)=>call(s2.client,verb,args),close:async()=>{stored.releaseIdleLock(),await s2.client.close()}};if(s2)stored.releaseIdleLock(),await s2.client.close()}log(`Signing you in as yourself for a moment, only to make your agents. On Kolab's page, under "Work as", choose "Yourself" by hand: it isn't chosen for you. konjir keeps none of it, and revokes it once they are made.`);let memory;try{memory=await ephemeralLogin(url2,{scope:["konjir",opts.kolab&&`kolab:${opts.kolab}`].filter(Boolean).join(" "),open:opts.open,log})}catch(e){throw unreachable(e,url2)??e}let end=async()=>{await memory.revoke(url2).then(()=>log("Revoked the sign-in as you."),(e)=>log(`warning: the sign-in as you wasn't revoked (${e.message}); konjir kept none of it, and it lapses within 30 days unused.`))},s;try{s=await open2(memory)}catch(e){throw await end(),e}if(s.me.kind!=="person")throw await s.client.close(),await end(),Error(`on Kolab's page you chose ${s.me.actor}, not Yourself, and konjir connect makes your agents as you. Run it again, and under "Work as" choose "Yourself"`);return{me:s.me,call:(verb,args)=>call(s.client,verb,args),close:async()=>{await s.client.close(),await end()}}}async function signInAgent(e,credentials,opts={}){let who=await login(e.url,{path:credentials,clientName:CHANNEL_CLIENT_NAME,scope:entryScope(e.kolab,e.role,e.agent),open:opts.open,log:opts.log});if(who.actor!==e.agent){let r=await logout(e.url,{path:credentials,forget:!0});throw Error(`it signed in as ${who.actor}, not ${e.agent}, so that sign-in was ${r.revoked?"revoked":"forgotten, unrevoked,"} and nothing is kept for ${e.name}`)}return who.actor}function unreachable(e,url2){let msg=String(e.message??e);if(/fetch failed|ECONNREFUSED|ENOTFOUND|EHOSTUNREACH/.test(msg+String(e.cause??"")))return Error(`cannot reach Kolab at ${url2}. Nothing is listening there: Kolab isn't running, or KONJIR_URL is wrong. Start it with \`konjir serve\`, or ask whoever runs it. Your work is safe; Kolab stores everything.`);return}function withoutPassword(url2){let u=new URL(url2);if(u.password)u.password="***";return u.toString()}main(process.argv.slice(2)).catch((e)=>{console.error(String(e.message??e)),process.exit(1)});