context-doctor 0.35.0 → 0.36.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/dist/mcp.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cdRequire } from 'module'; const require = __cdRequire(import.meta.url);
3
- var C0=Object.create;var ka=Object.defineProperty;var A0=Object.getOwnPropertyDescriptor;var N0=Object.getOwnPropertyNames;var M0=Object.getPrototypeOf,j0=Object.prototype.hasOwnProperty;var G=(t,e)=>()=>(t&&(e=t(t=0)),e);var T=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),eo=(t,e)=>{for(var r in e)ka(t,r,{get:e[r],enumerable:!0})},Z0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of N0(e))!j0.call(t,o)&&o!==r&&ka(t,o,{get:()=>e[o],enumerable:!(n=A0(e,o))||n.enumerable});return t};var Sa=(t,e,r)=>(r=t!=null?C0(M0(t)):{},Z0(e||!t||!t.__esModule?ka(r,"default",{value:t,enumerable:!0}):r,t));function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function tt(t){return t&&Object.assign(vs,t),vs}var Wx,Kx,Ut,vs,yn=G(()=>{Wx=Object.freeze({status:"aborted"});Kx=Symbol("zod_brand"),Ut=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},vs={}});var X={};eo(X,{BIGINT_FORMAT_RANGES:()=>ap,Class:()=>Ia,NUMBER_FORMAT_RANGES:()=>Za,aborted:()=>Dr,allowsEval:()=>Na,assert:()=>eb,assertEqual:()=>Gx,assertIs:()=>Yx,assertNever:()=>Qx,assertNotEqual:()=>Xx,assignProp:()=>Aa,cached:()=>io,captureStackTrace:()=>bs,cleanEnum:()=>pb,cleanRegex:()=>co,clone:()=>rt,createTransparentProxy:()=>ib,defineLazy:()=>de,esc:()=>Zr,escapeRegex:()=>rr,extend:()=>ub,finalizeIssue:()=>ht,floatSafeRemainder:()=>Ca,getElementAtPath:()=>tb,getEnumValues:()=>so,getLengthableOrigin:()=>uo,getParsedType:()=>sb,getSizableOrigin:()=>cp,isObject:()=>_n,isPlainObject:()=>vn,issue:()=>Da,joinValues:()=>xs,jsonStringifyReplacer:()=>Oa,merge:()=>lb,normalizeParams:()=>j,nullish:()=>ao,numKeys:()=>ob,omit:()=>cb,optionalKeys:()=>ja,partial:()=>db,pick:()=>ab,prefixIssues:()=>Tt,primitiveTypes:()=>ip,promiseAllObject:()=>rb,propertyKeyTypes:()=>Ma,randomString:()=>nb,required:()=>fb,stringifyPrimitive:()=>ws,unwrapMessage:()=>oo});function Gx(t){return t}function Xx(t){return t}function Yx(t){}function Qx(t){throw new Error}function eb(t){}function so(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function xs(t,e="|"){return t.map(r=>ws(r)).join(e)}function Oa(t,e){return typeof e=="bigint"?e.toString():e}function io(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ao(t){return t==null}function co(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Ca(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function de(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Aa(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function tb(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function rb(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function nb(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Zr(t){return JSON.stringify(t)}function _n(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vn(t){if(_n(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(_n(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ob(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function rr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function j(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function ib(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function ws(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ja(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function ab(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return rt(t,{...t._zod.def,shape:r,checks:[]})}function cb(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return rt(t,{...t._zod.def,shape:r,checks:[]})}function ub(t,e){if(!vn(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Aa(this,"shape",n),n},checks:[]};return rt(t,r)}function lb(t,e){return rt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Aa(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function db(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return rt(e,{...e._zod.def,shape:o,checks:[]})}function fb(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return rt(e,{...e._zod.def,shape:o,checks:[]})}function Dr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Tt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function oo(t){return typeof t=="string"?t:t?.message}function ht(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=oo(t.inst?._zod.def?.error?.(t))??oo(e?.error?.(t))??oo(r.customError?.(t))??oo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function cp(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function uo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Da(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function pb(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var bs,Na,sb,Ma,ip,Za,ap,Ia,zt=G(()=>{bs=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Na=io(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});sb=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Ma=new Set(["string","number","symbol"]),ip=new Set(["string","number","bigint","boolean","symbol","undefined"]);Za={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ap={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Ia=class{constructor(...e){}}});function qa(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function La(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var up,$s,lo,Ua=G(()=>{yn();zt();up=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Oa,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},$s=w("$ZodError",up),lo=w("$ZodError",up,{Parent:Error})});var Fa,Ha,Va,Ba,Ja,qr,Wa,Lr,Ka=G(()=>{yn();Ua();zt();Fa=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ut;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,tt())));throw bs(a,o?.callee),a}return i.value},Ha=Fa(lo),Va=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,tt())));throw bs(a,o?.callee),a}return i.value},Ba=Va(lo),Ja=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ut;return s.issues.length?{success:!1,error:new(t??$s)(s.issues.map(i=>ht(i,o,tt())))}:{success:!0,data:s.value}},qr=Ja(lo),Wa=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>ht(i,o,tt())))}:{success:!0,data:s.value}},Lr=Wa(lo)});function vp(){return new RegExp(hb,"u")}function Pp(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Rp(t){return new RegExp(`^${Pp(t)}$`)}function Ip(t){let e=Pp({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Tp}T(?:${n})$`)}var lp,dp,fp,pp,mp,hp,gp,yp,Ga,_p,hb,xp,bp,wp,$p,kp,Xa,Sp,Ep,Tp,zp,Op,Cp,Ap,Np,Mp,jp,Zp,Ss=G(()=>{lp=/^[cC][^\s-]{8,}$/,dp=/^[0-9a-z]+$/,fp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pp=/^[0-9a-vA-V]{20}$/,mp=/^[A-Za-z0-9]{27}$/,hp=/^[a-zA-Z0-9_-]{21}$/,gp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,yp=/^([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})$/,Ga=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,_p=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,hb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";xp=/^(?:(?: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])$/,bp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,wp=/^((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])$/,$p=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,kp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Xa=/^[A-Za-z0-9_-]*$/,Sp=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Ep=/^\+(?:[0-9]){6,14}[0-9]$/,Tp="(?:(?:\\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])))",zp=new RegExp(`^${Tp}$`);Op=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Cp=/^\d+$/,Ap=/^-?\d+(?:\.\d+)?/i,Np=/true|false/i,Mp=/null/i,jp=/^[^A-Z]*$/,Zp=/^[^a-z]*$/});var Re,Dp,Ya,Qa,qp,Lp,Up,Fp,Hp,fo,Vp,Bp,Jp,Wp,Kp,Gp,Xp,Es=G(()=>{yn();Ss();zt();Re=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Dp={number:"number",bigint:"bigint",object:"date"},Ya=w("$ZodCheckLessThan",(t,e)=>{Re.init(t,e);let r=Dp[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Qa=w("$ZodCheckGreaterThan",(t,e)=>{Re.init(t,e);let r=Dp[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),qp=w("$ZodCheckMultipleOf",(t,e)=>{Re.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Ca(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Lp=w("$ZodCheckNumberFormat",(t,e)=>{Re.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Za[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Cp)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Up=w("$ZodCheckMaxLength",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=uo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Fp=w("$ZodCheckMinLength",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=uo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Hp=w("$ZodCheckLengthEquals",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=uo(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),fo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Re.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Vp=w("$ZodCheckRegex",(t,e)=>{fo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Bp=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=jp),fo.init(t,e)}),Jp=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Zp),fo.init(t,e)}),Wp=w("$ZodCheckIncludes",(t,e)=>{Re.init(t,e);let r=rr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Kp=w("$ZodCheckStartsWith",(t,e)=>{Re.init(t,e);let r=new RegExp(`^${rr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Gp=w("$ZodCheckEndsWith",(t,e)=>{Re.init(t,e);let r=new RegExp(`.*${rr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Xp=w("$ZodCheckOverwrite",(t,e)=>{Re.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Ts,ec=G(()=>{Ts=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
3
+ var N0=Object.create;var Sa=Object.defineProperty;var M0=Object.getOwnPropertyDescriptor;var j0=Object.getOwnPropertyNames;var Z0=Object.getPrototypeOf,D0=Object.prototype.hasOwnProperty;var G=(t,e)=>()=>(t&&(e=t(t=0)),e);var T=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),eo=(t,e)=>{for(var r in e)Sa(t,r,{get:e[r],enumerable:!0})},q0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of j0(e))!D0.call(t,o)&&o!==r&&Sa(t,o,{get:()=>e[o],enumerable:!(n=M0(e,o))||n.enumerable});return t};var Ea=(t,e,r)=>(r=t!=null?N0(Z0(t)):{},q0(e||!t||!t.__esModule?Sa(r,"default",{value:t,enumerable:!0}):r,t));function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function tt(t){return t&&Object.assign(vs,t),vs}var Gx,Xx,Ut,vs,yn=G(()=>{Gx=Object.freeze({status:"aborted"});Xx=Symbol("zod_brand"),Ut=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},vs={}});var X={};eo(X,{BIGINT_FORMAT_RANGES:()=>cp,Class:()=>Oa,NUMBER_FORMAT_RANGES:()=>Da,aborted:()=>Dr,allowsEval:()=>Ma,assert:()=>rb,assertEqual:()=>Yx,assertIs:()=>eb,assertNever:()=>tb,assertNotEqual:()=>Qx,assignProp:()=>Na,cached:()=>io,captureStackTrace:()=>bs,cleanEnum:()=>hb,cleanRegex:()=>co,clone:()=>rt,createTransparentProxy:()=>cb,defineLazy:()=>fe,esc:()=>Zr,escapeRegex:()=>rr,extend:()=>db,finalizeIssue:()=>ht,floatSafeRemainder:()=>Aa,getElementAtPath:()=>nb,getEnumValues:()=>so,getLengthableOrigin:()=>uo,getParsedType:()=>ab,getSizableOrigin:()=>up,isObject:()=>_n,isPlainObject:()=>vn,issue:()=>qa,joinValues:()=>xs,jsonStringifyReplacer:()=>Ca,merge:()=>fb,normalizeParams:()=>j,nullish:()=>ao,numKeys:()=>ib,omit:()=>lb,optionalKeys:()=>Za,partial:()=>pb,pick:()=>ub,prefixIssues:()=>Tt,primitiveTypes:()=>ap,promiseAllObject:()=>ob,propertyKeyTypes:()=>ja,randomString:()=>sb,required:()=>mb,stringifyPrimitive:()=>ws,unwrapMessage:()=>oo});function Yx(t){return t}function Qx(t){return t}function eb(t){}function tb(t){throw new Error}function rb(t){}function so(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function xs(t,e="|"){return t.map(r=>ws(r)).join(e)}function Ca(t,e){return typeof e=="bigint"?e.toString():e}function io(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ao(t){return t==null}function co(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Aa(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function fe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Na(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function nb(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function ob(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function sb(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Zr(t){return JSON.stringify(t)}function _n(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vn(t){if(_n(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(_n(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ib(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function rr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function j(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function cb(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function ws(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Za(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function ub(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return rt(t,{...t._zod.def,shape:r,checks:[]})}function lb(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return rt(t,{...t._zod.def,shape:r,checks:[]})}function db(t,e){if(!vn(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Na(this,"shape",n),n},checks:[]};return rt(t,r)}function fb(t,e){return rt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Na(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function pb(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return rt(e,{...e._zod.def,shape:o,checks:[]})}function mb(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return rt(e,{...e._zod.def,shape:o,checks:[]})}function Dr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Tt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function oo(t){return typeof t=="string"?t:t?.message}function ht(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=oo(t.inst?._zod.def?.error?.(t))??oo(e?.error?.(t))??oo(r.customError?.(t))??oo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function up(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function uo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function qa(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function hb(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var bs,Ma,ab,ja,ap,Da,cp,Oa,zt=G(()=>{bs=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Ma=io(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});ab=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ja=new Set(["string","number","symbol"]),ap=new Set(["string","number","bigint","boolean","symbol","undefined"]);Da={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},cp={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Oa=class{constructor(...e){}}});function La(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Ua(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var lp,$s,lo,Fa=G(()=>{yn();zt();lp=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Ca,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},$s=w("$ZodError",lp),lo=w("$ZodError",lp,{Parent:Error})});var Ha,Va,Ba,Ja,Wa,qr,Ka,Lr,Ga=G(()=>{yn();Fa();zt();Ha=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ut;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,tt())));throw bs(a,o?.callee),a}return i.value},Va=Ha(lo),Ba=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,tt())));throw bs(a,o?.callee),a}return i.value},Ja=Ba(lo),Wa=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ut;return s.issues.length?{success:!1,error:new(t??$s)(s.issues.map(i=>ht(i,o,tt())))}:{success:!0,data:s.value}},qr=Wa(lo),Ka=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>ht(i,o,tt())))}:{success:!0,data:s.value}},Lr=Ka(lo)});function xp(){return new RegExp(yb,"u")}function Rp(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ip(t){return new RegExp(`^${Rp(t)}$`)}function Op(t){let e=Rp({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${zp}T(?:${n})$`)}var dp,fp,pp,mp,hp,gp,yp,_p,Xa,vp,yb,bp,wp,$p,kp,Sp,Ya,Ep,Tp,zp,Pp,Cp,Ap,Np,Mp,jp,Zp,Dp,Ss=G(()=>{dp=/^[cC][^\s-]{8,}$/,fp=/^[0-9a-z]+$/,pp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,mp=/^[0-9a-vA-V]{20}$/,hp=/^[A-Za-z0-9]{27}$/,gp=/^[a-zA-Z0-9_-]{21}$/,yp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,_p=/^([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})$/,Xa=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,vp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,yb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";bp=/^(?:(?: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])$/,wp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,$p=/^((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])$/,kp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Sp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ya=/^[A-Za-z0-9_-]*$/,Ep=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Tp=/^\+(?:[0-9]){6,14}[0-9]$/,zp="(?:(?:\\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])))",Pp=new RegExp(`^${zp}$`);Cp=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Ap=/^\d+$/,Np=/^-?\d+(?:\.\d+)?/i,Mp=/true|false/i,jp=/null/i,Zp=/^[^A-Z]*$/,Dp=/^[^a-z]*$/});var Re,qp,Qa,ec,Lp,Up,Fp,Hp,Vp,fo,Bp,Jp,Wp,Kp,Gp,Xp,Yp,Es=G(()=>{yn();Ss();zt();Re=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),qp={number:"number",bigint:"bigint",object:"date"},Qa=w("$ZodCheckLessThan",(t,e)=>{Re.init(t,e);let r=qp[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),ec=w("$ZodCheckGreaterThan",(t,e)=>{Re.init(t,e);let r=qp[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Lp=w("$ZodCheckMultipleOf",(t,e)=>{Re.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Aa(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Up=w("$ZodCheckNumberFormat",(t,e)=>{Re.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Da[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Ap)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Fp=w("$ZodCheckMaxLength",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=uo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Hp=w("$ZodCheckMinLength",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=uo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Vp=w("$ZodCheckLengthEquals",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=uo(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),fo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Re.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Bp=w("$ZodCheckRegex",(t,e)=>{fo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Jp=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Zp),fo.init(t,e)}),Wp=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Dp),fo.init(t,e)}),Kp=w("$ZodCheckIncludes",(t,e)=>{Re.init(t,e);let r=rr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Gp=w("$ZodCheckStartsWith",(t,e)=>{Re.init(t,e);let r=new RegExp(`^${rr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Xp=w("$ZodCheckEndsWith",(t,e)=>{Re.init(t,e);let r=new RegExp(`.*${rr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Yp=w("$ZodCheckOverwrite",(t,e)=>{Re.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Ts,tc=G(()=>{Ts=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
4
4
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
5
- `))}}});var Qp,tc=G(()=>{Qp={major:4,minor:0,patch:0}});function pm(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function gb(t){if(!Xa.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return pm(r)}function yb(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function em(t,e,r){t.issues.length&&e.issues.push(...Tt(r,t.issues)),e.value[r]=t.value}function zs(t,e,r){t.issues.length&&e.issues.push(...Tt(r,t.issues)),e.value[r]=t.value}function tm(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Tt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function rm(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>ht(s,n,tt())))}),e}function rc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(vn(t)&&vn(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=rc(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=rc(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function nm(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Dr(t))return t;let n=rc(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function om(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function sm(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function im(t,e,r){return Dr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function am(t){return t.value=Object.freeze(t.value),t}function cm(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Da(o))}}var ce,po,fe,nc,oc,sc,ic,ac,cc,uc,lc,dc,fc,pc,um,lm,dm,fm,mc,hc,gc,yc,_c,vc,xc,bc,Ps,wc,$c,kc,Sc,Ec,Tc,Rs,Is,zc,Pc,Rc,Ic,Oc,Cc,Ac,Nc,Mc,jc,Zc,Dc,qc,Lc,Uc,mm=G(()=>{Es();yn();ec();Ka();Ss();zt();tc();zt();ce=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Qp;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Dr(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Ut;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Dr(s,d)))});else{if(s.issues.length===d)continue;c||(c=Dr(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Ut;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=qr(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Lr(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),po=w("$ZodString",(t,e)=>{ce.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Op(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),fe=w("$ZodStringFormat",(t,e)=>{fo.init(t,e),po.init(t,e)}),nc=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=yp),fe.init(t,e)}),oc=w("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Ga(n))}else e.pattern??(e.pattern=Ga());fe.init(t,e)}),sc=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=_p),fe.init(t,e)}),ic=w("$ZodURL",(t,e)=>{fe.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Sp.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),ac=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=vp()),fe.init(t,e)}),cc=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=hp),fe.init(t,e)}),uc=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=lp),fe.init(t,e)}),lc=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=dp),fe.init(t,e)}),dc=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=fp),fe.init(t,e)}),fc=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=pp),fe.init(t,e)}),pc=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=mp),fe.init(t,e)}),um=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ip(e)),fe.init(t,e)}),lm=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=zp),fe.init(t,e)}),dm=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Rp(e)),fe.init(t,e)}),fm=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=gp),fe.init(t,e)}),mc=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=xp),fe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),hc=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=bp),fe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),gc=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=wp),fe.init(t,e)}),yc=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=$p),fe.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});_c=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=kp),fe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{pm(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});vc=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Xa),fe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{gb(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),xc=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Ep),fe.init(t,e)});bc=w("$ZodJWT",(t,e)=>{fe.init(t,e),t._zod.check=r=>{yb(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ps=w("$ZodNumber",(t,e)=>{ce.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ap,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),wc=w("$ZodNumber",(t,e)=>{Lp.init(t,e),Ps.init(t,e)}),$c=w("$ZodBoolean",(t,e)=>{ce.init(t,e),t._zod.pattern=Np,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),kc=w("$ZodNull",(t,e)=>{ce.init(t,e),t._zod.pattern=Mp,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Sc=w("$ZodUnknown",(t,e)=>{ce.init(t,e),t._zod.parse=r=>r}),Ec=w("$ZodNever",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Tc=w("$ZodArray",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>em(u,r,i))):em(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Rs=w("$ZodObject",(t,e)=>{ce.init(t,e);let r=io(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof ce))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let p=ja(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});de(t._zod,"propValues",()=>{let d=e.shape,p={};for(let m in d){let f=d[m]._zod;if(f.values){p[m]??(p[m]=new Set);for(let h of f.values)p[m].add(h)}}return p});let n=d=>{let p=new Ts(["shape","payload","ctx"]),m=r.value,f=v=>{let g=Zr(v);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),y=0;for(let v of m.keys)h[v]=`key_${y++}`;p.write("const newResult = {}");for(let v of m.keys)if(m.optionalKeys.has(v)){let g=h[v];p.write(`const ${g} = ${f(v)};`);let x=Zr(v);p.write(`
5
+ `))}}});var em,rc=G(()=>{em={major:4,minor:0,patch:0}});function mm(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function _b(t){if(!Ya.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return mm(r)}function vb(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function tm(t,e,r){t.issues.length&&e.issues.push(...Tt(r,t.issues)),e.value[r]=t.value}function zs(t,e,r){t.issues.length&&e.issues.push(...Tt(r,t.issues)),e.value[r]=t.value}function rm(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Tt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function nm(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>ht(s,n,tt())))}),e}function nc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(vn(t)&&vn(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=nc(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=nc(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function om(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Dr(t))return t;let n=nc(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function sm(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function im(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function am(t,e,r){return Dr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function cm(t){return t.value=Object.freeze(t.value),t}function um(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(qa(o))}}var ue,po,pe,oc,sc,ic,ac,cc,uc,lc,dc,fc,pc,mc,lm,dm,fm,pm,hc,gc,yc,_c,vc,xc,bc,wc,Ps,$c,kc,Sc,Ec,Tc,zc,Rs,Is,Pc,Rc,Ic,Oc,Cc,Ac,Nc,Mc,jc,Zc,Dc,qc,Lc,Uc,Fc,hm=G(()=>{Es();yn();tc();Ga();Ss();zt();rc();zt();ue=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=em;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Dr(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Ut;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Dr(s,d)))});else{if(s.issues.length===d)continue;c||(c=Dr(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Ut;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=qr(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Lr(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),po=w("$ZodString",(t,e)=>{ue.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Cp(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),pe=w("$ZodStringFormat",(t,e)=>{fo.init(t,e),po.init(t,e)}),oc=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=_p),pe.init(t,e)}),sc=w("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Xa(n))}else e.pattern??(e.pattern=Xa());pe.init(t,e)}),ic=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=vp),pe.init(t,e)}),ac=w("$ZodURL",(t,e)=>{pe.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Ep.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),cc=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=xp()),pe.init(t,e)}),uc=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=gp),pe.init(t,e)}),lc=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=dp),pe.init(t,e)}),dc=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=fp),pe.init(t,e)}),fc=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=pp),pe.init(t,e)}),pc=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=mp),pe.init(t,e)}),mc=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=hp),pe.init(t,e)}),lm=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Op(e)),pe.init(t,e)}),dm=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Pp),pe.init(t,e)}),fm=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ip(e)),pe.init(t,e)}),pm=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=yp),pe.init(t,e)}),hc=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=bp),pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),gc=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=wp),pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),yc=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=$p),pe.init(t,e)}),_c=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=kp),pe.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});vc=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Sp),pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{mm(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});xc=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ya),pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{_b(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),bc=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Tp),pe.init(t,e)});wc=w("$ZodJWT",(t,e)=>{pe.init(t,e),t._zod.check=r=>{vb(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ps=w("$ZodNumber",(t,e)=>{ue.init(t,e),t._zod.pattern=t._zod.bag.pattern??Np,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),$c=w("$ZodNumber",(t,e)=>{Up.init(t,e),Ps.init(t,e)}),kc=w("$ZodBoolean",(t,e)=>{ue.init(t,e),t._zod.pattern=Mp,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),Sc=w("$ZodNull",(t,e)=>{ue.init(t,e),t._zod.pattern=jp,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Ec=w("$ZodUnknown",(t,e)=>{ue.init(t,e),t._zod.parse=r=>r}),Tc=w("$ZodNever",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});zc=w("$ZodArray",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>tm(u,r,i))):tm(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Rs=w("$ZodObject",(t,e)=>{ue.init(t,e);let r=io(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof ue))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let p=Za(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});fe(t._zod,"propValues",()=>{let d=e.shape,p={};for(let m in d){let f=d[m]._zod;if(f.values){p[m]??(p[m]=new Set);for(let h of f.values)p[m].add(h)}}return p});let n=d=>{let p=new Ts(["shape","payload","ctx"]),m=r.value,f=v=>{let g=Zr(v);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),y=0;for(let v of m.keys)h[v]=`key_${y++}`;p.write("const newResult = {}");for(let v of m.keys)if(m.optionalKeys.has(v)){let g=h[v];p.write(`const ${g} = ${f(v)};`);let x=Zr(v);p.write(`
6
6
  if (${g}.issues.length) {
7
7
  if (input[${x}] === undefined) {
8
8
  if (${x} in input) {
@@ -25,17 +25,17 @@ var C0=Object.create;var ka=Object.defineProperty;var A0=Object.getOwnPropertyDe
25
25
  if (${g}.issues.length) payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
26
26
  ...iss,
27
27
  path: iss.path ? [${Zr(v)}, ...iss.path] : [${Zr(v)}]
28
- })));`),p.write(`newResult[${Zr(v)}] = ${g}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(v,g)=>_(d,v,g)},o,s=_n,i=!vs.jitless,c=i&&Na.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let f=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let g=l.shape;for(let x of l.keys){let $=g[x],D=$._zod.run({value:m[x],issues:[]},p),R=$._zod.optin==="optional"&&$._zod.optout==="optional";D instanceof Promise?f.push(D.then(ie=>R?tm(ie,d,x,m):zs(ie,d,x))):R?tm(D,d,x,m):zs(D,d,x)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let h=[],y=l.keySet,_=u._zod,v=_.def.type;for(let g of Object.keys(m)){if(y.has(g))continue;if(v==="never"){h.push(g);continue}let x=_.run({value:m[g],issues:[]},p);x instanceof Promise?f.push(x.then($=>zs($,d,g))):zs(x,d,g)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Is=w("$ZodUnion",(t,e)=>{ce.init(t,e),de(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),de(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),de(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),de(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>co(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>rm(i,r,t,n)):rm(s,r,t,n)}}),zc=w("$ZodDiscriminatedUnion",(t,e)=>{Is.init(t,e);let r=t._zod.parse;de(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=io(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!_n(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Pc=w("$ZodIntersection",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>nm(r,c,u)):nm(r,s,i)}});Rc=w("$ZodRecord",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!vn(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Tt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Tt(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>ht(u,n,tt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Tt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Tt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Ic=w("$ZodEnum",(t,e)=>{ce.init(t,e);let r=so(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Ma.has(typeof n)).map(n=>typeof n=="string"?rr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Oc=w("$ZodLiteral",(t,e)=>{ce.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?rr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),Cc=w("$ZodTransform",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Ut;return r.value=o,r}}),Ac=w("$ZodOptional",(t,e)=>{ce.init(t,e),t._zod.optin="optional",t._zod.optout="optional",de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${co(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Nc=w("$ZodNullable",(t,e)=>{ce.init(t,e),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${co(r.source)}|null)$`):void 0}),de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Mc=w("$ZodDefault",(t,e)=>{ce.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>om(s,e)):om(o,e)}});jc=w("$ZodPrefault",(t,e)=>{ce.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Zc=w("$ZodNonOptional",(t,e)=>{ce.init(t,e),de(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>sm(s,t)):sm(o,t)}});Dc=w("$ZodCatch",(t,e)=>{ce.init(t,e),t._zod.optin="optional",de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>ht(i,n,tt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>ht(s,n,tt()))},input:r.value}),r.issues=[]),r)}}),qc=w("$ZodPipe",(t,e)=>{ce.init(t,e),de(t._zod,"values",()=>e.in._zod.values),de(t._zod,"optin",()=>e.in._zod.optin),de(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>im(s,e,n)):im(o,e,n)}});Lc=w("$ZodReadonly",(t,e)=>{ce.init(t,e),de(t._zod,"propValues",()=>e.innerType._zod.propValues),de(t._zod,"values",()=>e.innerType._zod.values),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(am):am(o)}});Uc=w("$ZodCustom",(t,e)=>{Re.init(t,e),ce.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>cm(s,r,n,t));cm(o,r,n,t)}})});function hm(){return{localeError:vb()}}var _b,vb,gm=G(()=>{zt();_b=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},vb=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={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",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${_b(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ws(n.values[0])}`:`Invalid option: expected one of ${xs(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${xs(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Os=G(()=>{});function ym(){return new mo}var xb,bb,mo,nr,Hc=G(()=>{xb=Symbol("ZodOutput"),bb=Symbol("ZodInput"),mo=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};nr=ym()});function Vc(t,e){return new t({type:"string",...j(e)})}function Bc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Cs(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function Jc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function Wc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function Kc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function Gc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function Xc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function Yc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function Qc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function eu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function tu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function ru(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function nu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function ou(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function su(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function iu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function au(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function cu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function uu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function lu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function du(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function fu(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}function _m(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function vm(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function xm(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function bm(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function pu(t,e){return new t({type:"number",checks:[],...j(e)})}function mu(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function hu(t,e){return new t({type:"boolean",...j(e)})}function gu(t,e){return new t({type:"null",...j(e)})}function yu(t){return new t({type:"unknown"})}function _u(t,e){return new t({type:"never",...j(e)})}function As(t,e){return new Ya({check:"less_than",...j(e),value:t,inclusive:!1})}function ho(t,e){return new Ya({check:"less_than",...j(e),value:t,inclusive:!0})}function Ns(t,e){return new Qa({check:"greater_than",...j(e),value:t,inclusive:!1})}function go(t,e){return new Qa({check:"greater_than",...j(e),value:t,inclusive:!0})}function Ms(t,e){return new qp({check:"multiple_of",...j(e),value:t})}function js(t,e){return new Up({check:"max_length",...j(e),maximum:t})}function xn(t,e){return new Fp({check:"min_length",...j(e),minimum:t})}function Zs(t,e){return new Hp({check:"length_equals",...j(e),length:t})}function vu(t,e){return new Vp({check:"string_format",format:"regex",...j(e),pattern:t})}function xu(t){return new Bp({check:"string_format",format:"lowercase",...j(t)})}function bu(t){return new Jp({check:"string_format",format:"uppercase",...j(t)})}function wu(t,e){return new Wp({check:"string_format",format:"includes",...j(e),includes:t})}function $u(t,e){return new Kp({check:"string_format",format:"starts_with",...j(e),prefix:t})}function ku(t,e){return new Gp({check:"string_format",format:"ends_with",...j(e),suffix:t})}function Ur(t){return new Xp({check:"overwrite",tx:t})}function Su(t){return Ur(e=>e.normalize(t))}function Eu(){return Ur(t=>t.trim())}function Tu(){return Ur(t=>t.toLowerCase())}function zu(){return Ur(t=>t.toUpperCase())}function wm(t,e,r){return new t({type:"array",element:e,...j(r)})}function Pu(t,e,r){let n=j(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Ru(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}var $m=G(()=>{Es();zt()});var km=G(()=>{});function Iu(t,e){if(t instanceof mo){let n=new Ds(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new Ds(e);return r.process(t),r.emit(t,e)}function Se(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Se(o.element,r);case"object":{for(let s in o.shape)if(Se(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Se(s,r))return!0;return!1}case"intersection":return Se(o.left,r)||Se(o.right,r);case"tuple":{for(let s of o.items)if(Se(s,r))return!0;return!!(o.rest&&Se(o.rest,r))}case"record":return Se(o.keyType,r)||Se(o.valueType,r);case"map":return Se(o.keyType,r)||Se(o.valueType,r);case"set":return Se(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Se(o.innerType,r);case"lazy":return Se(o.getter(),r);case"default":return Se(o.innerType,r);case"prefault":return Se(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Se(o.in,r)||Se(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Ds,Sm=G(()=>{Hc();zt();Ds=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??nr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let f=m;f.type="string";let{minimum:h,maximum:y,format:_,patterns:v,contentEncoding:g}=e._zod.bag;if(typeof h=="number"&&(f.minLength=h),typeof y=="number"&&(f.maxLength=y),_&&(f.format=s[_]??_,f.format===""&&delete f.format),g&&(f.contentEncoding=g),v&&v.size>0){let x=[...v];x.length===1?f.pattern=x[0].source:x.length>1&&(a.schema.allOf=[...x.map($=>({...this.target==="draft-7"?{type:"string"}:{},pattern:$.source}))])}break}case"number":{let f=m,{minimum:h,maximum:y,format:_,multipleOf:v,exclusiveMaximum:g,exclusiveMinimum:x}=e._zod.bag;typeof _=="string"&&_.includes("int")?f.type="integer":f.type="number",typeof x=="number"&&(f.exclusiveMinimum=x),typeof h=="number"&&(f.minimum=h,typeof x=="number"&&(x>=h?delete f.minimum:delete f.exclusiveMinimum)),typeof g=="number"&&(f.exclusiveMaximum=g),typeof y=="number"&&(f.maximum=y,typeof g=="number"&&(g<=y?delete f.maximum:delete f.exclusiveMaximum)),typeof v=="number"&&(f.multipleOf=v);break}case"boolean":{let f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=m,{minimum:h,maximum:y}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof y=="number"&&(f.maxItems=y),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=m;f.type="object",f.properties={};let h=o.shape;for(let v in h)f.properties[v]=this.process(h[v],{...d,path:[...d.path,"properties",v]});let y=new Set(Object.keys(h)),_=new Set([...y].filter(v=>{let g=o.shape[v]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));_.size>0&&(f.required=Array.from(_)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=m;f.anyOf=o.options.map((h,y)=>this.process(h,{...d,path:[...d.path,"anyOf",y]}));break}case"intersection":{let f=m,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),y=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),_=g=>"allOf"in g&&Object.keys(g).length===1,v=[..._(h)?h.allOf:[h],..._(y)?y.allOf:[y]];f.allOf=v;break}case"tuple":{let f=m;f.type="array";let h=o.items.map((v,g)=>this.process(v,{...d,path:[...d.path,"prefixItems",g]}));if(this.target==="draft-2020-12"?f.prefixItems=h:f.items=h,o.rest){let v=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=v:f.additionalItems=v}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:y,maximum:_}=e._zod.bag;typeof y=="number"&&(f.minItems=y),typeof _=="number"&&(f.maxItems=_);break}case"record":{let f=m;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=m,h=so(o.entries);h.every(y=>typeof y=="number")&&(f.type="number"),h.every(y=>typeof y=="string")&&(f.type="string"),f.enum=h;break}case"literal":{let f=m,h=[];for(let y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(y))}else h.push(y);if(h.length!==0)if(h.length===1){let y=h[0];f.type=y===null?"null":typeof y,f.const=y}else h.every(y=>typeof y=="number")&&(f.type="number"),h.every(y=>typeof y=="string")&&(f.type="string"),h.every(y=>typeof y=="boolean")&&(f.type="string"),h.every(y=>y===null)&&(f.type="null"),f.enum=h;break}case"file":{let f=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:_,mime:v}=e._zod.bag;y!==void 0&&(h.minLength=y),_!==void 0&&(h.maxLength=_),v?v.length===1?(h.contentMediaType=v[0],Object.assign(f,h)):f.anyOf=v.map(g=>({...h,contentMediaType:g})):Object.assign(f,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=m;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=m,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=h.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Se(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,y=n.external.uri??(v=>v);if(h)return{ref:y(h)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${y("__shared")}#/${d}/${_}`}}if(l[1]===o)return{ref:"#"};let m=`#/${d}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:m}=s(l);d.def={...d.schema},m&&(d.defId=m);let f=d.schema;for(let h in f)delete f[h];f.$ref=p};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
28
+ })));`),p.write(`newResult[${Zr(v)}] = ${g}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(v,g)=>_(d,v,g)},o,s=_n,i=!vs.jitless,c=i&&Ma.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let f=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let g=l.shape;for(let x of l.keys){let $=g[x],D=$._zod.run({value:m[x],issues:[]},p),R=$._zod.optin==="optional"&&$._zod.optout==="optional";D instanceof Promise?f.push(D.then(ae=>R?rm(ae,d,x,m):zs(ae,d,x))):R?rm(D,d,x,m):zs(D,d,x)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let h=[],y=l.keySet,_=u._zod,v=_.def.type;for(let g of Object.keys(m)){if(y.has(g))continue;if(v==="never"){h.push(g);continue}let x=_.run({value:m[g],issues:[]},p);x instanceof Promise?f.push(x.then($=>zs($,d,g))):zs(x,d,g)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Is=w("$ZodUnion",(t,e)=>{ue.init(t,e),fe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),fe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),fe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),fe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>co(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>nm(i,r,t,n)):nm(s,r,t,n)}}),Pc=w("$ZodDiscriminatedUnion",(t,e)=>{Is.init(t,e);let r=t._zod.parse;fe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=io(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!_n(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Rc=w("$ZodIntersection",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>om(r,c,u)):om(r,s,i)}});Ic=w("$ZodRecord",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!vn(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Tt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Tt(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>ht(u,n,tt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Tt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Tt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Oc=w("$ZodEnum",(t,e)=>{ue.init(t,e);let r=so(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>ja.has(typeof n)).map(n=>typeof n=="string"?rr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Cc=w("$ZodLiteral",(t,e)=>{ue.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?rr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),Ac=w("$ZodTransform",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Ut;return r.value=o,r}}),Nc=w("$ZodOptional",(t,e)=>{ue.init(t,e),t._zod.optin="optional",t._zod.optout="optional",fe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),fe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${co(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Mc=w("$ZodNullable",(t,e)=>{ue.init(t,e),fe(t._zod,"optin",()=>e.innerType._zod.optin),fe(t._zod,"optout",()=>e.innerType._zod.optout),fe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${co(r.source)}|null)$`):void 0}),fe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),jc=w("$ZodDefault",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>sm(s,e)):sm(o,e)}});Zc=w("$ZodPrefault",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Dc=w("$ZodNonOptional",(t,e)=>{ue.init(t,e),fe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>im(s,t)):im(o,t)}});qc=w("$ZodCatch",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"optout",()=>e.innerType._zod.optout),fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>ht(i,n,tt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>ht(s,n,tt()))},input:r.value}),r.issues=[]),r)}}),Lc=w("$ZodPipe",(t,e)=>{ue.init(t,e),fe(t._zod,"values",()=>e.in._zod.values),fe(t._zod,"optin",()=>e.in._zod.optin),fe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>am(s,e,n)):am(o,e,n)}});Uc=w("$ZodReadonly",(t,e)=>{ue.init(t,e),fe(t._zod,"propValues",()=>e.innerType._zod.propValues),fe(t._zod,"values",()=>e.innerType._zod.values),fe(t._zod,"optin",()=>e.innerType._zod.optin),fe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(cm):cm(o)}});Fc=w("$ZodCustom",(t,e)=>{Re.init(t,e),ue.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>um(s,r,n,t));um(o,r,n,t)}})});function gm(){return{localeError:bb()}}var xb,bb,ym=G(()=>{zt();xb=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},bb=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={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",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${xb(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ws(n.values[0])}`:`Invalid option: expected one of ${xs(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${xs(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Os=G(()=>{});function _m(){return new mo}var wb,$b,mo,nr,Vc=G(()=>{wb=Symbol("ZodOutput"),$b=Symbol("ZodInput"),mo=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};nr=_m()});function Bc(t,e){return new t({type:"string",...j(e)})}function Jc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Cs(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function Wc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function Kc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function Gc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function Xc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function Yc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function Qc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function eu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function tu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function ru(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function nu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function ou(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function su(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function iu(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function au(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function cu(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function uu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function lu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function du(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function fu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function pu(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}function vm(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function xm(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function bm(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function wm(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function mu(t,e){return new t({type:"number",checks:[],...j(e)})}function hu(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function gu(t,e){return new t({type:"boolean",...j(e)})}function yu(t,e){return new t({type:"null",...j(e)})}function _u(t){return new t({type:"unknown"})}function vu(t,e){return new t({type:"never",...j(e)})}function As(t,e){return new Qa({check:"less_than",...j(e),value:t,inclusive:!1})}function ho(t,e){return new Qa({check:"less_than",...j(e),value:t,inclusive:!0})}function Ns(t,e){return new ec({check:"greater_than",...j(e),value:t,inclusive:!1})}function go(t,e){return new ec({check:"greater_than",...j(e),value:t,inclusive:!0})}function Ms(t,e){return new Lp({check:"multiple_of",...j(e),value:t})}function js(t,e){return new Fp({check:"max_length",...j(e),maximum:t})}function xn(t,e){return new Hp({check:"min_length",...j(e),minimum:t})}function Zs(t,e){return new Vp({check:"length_equals",...j(e),length:t})}function xu(t,e){return new Bp({check:"string_format",format:"regex",...j(e),pattern:t})}function bu(t){return new Jp({check:"string_format",format:"lowercase",...j(t)})}function wu(t){return new Wp({check:"string_format",format:"uppercase",...j(t)})}function $u(t,e){return new Kp({check:"string_format",format:"includes",...j(e),includes:t})}function ku(t,e){return new Gp({check:"string_format",format:"starts_with",...j(e),prefix:t})}function Su(t,e){return new Xp({check:"string_format",format:"ends_with",...j(e),suffix:t})}function Ur(t){return new Yp({check:"overwrite",tx:t})}function Eu(t){return Ur(e=>e.normalize(t))}function Tu(){return Ur(t=>t.trim())}function zu(){return Ur(t=>t.toLowerCase())}function Pu(){return Ur(t=>t.toUpperCase())}function $m(t,e,r){return new t({type:"array",element:e,...j(r)})}function Ru(t,e,r){let n=j(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Iu(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}var km=G(()=>{Es();zt()});var Sm=G(()=>{});function Ou(t,e){if(t instanceof mo){let n=new Ds(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new Ds(e);return r.process(t),r.emit(t,e)}function Se(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Se(o.element,r);case"object":{for(let s in o.shape)if(Se(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Se(s,r))return!0;return!1}case"intersection":return Se(o.left,r)||Se(o.right,r);case"tuple":{for(let s of o.items)if(Se(s,r))return!0;return!!(o.rest&&Se(o.rest,r))}case"record":return Se(o.keyType,r)||Se(o.valueType,r);case"map":return Se(o.keyType,r)||Se(o.valueType,r);case"set":return Se(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Se(o.innerType,r);case"lazy":return Se(o.getter(),r);case"default":return Se(o.innerType,r);case"prefault":return Se(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Se(o.in,r)||Se(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Ds,Em=G(()=>{Vc();zt();Ds=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??nr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let f=m;f.type="string";let{minimum:h,maximum:y,format:_,patterns:v,contentEncoding:g}=e._zod.bag;if(typeof h=="number"&&(f.minLength=h),typeof y=="number"&&(f.maxLength=y),_&&(f.format=s[_]??_,f.format===""&&delete f.format),g&&(f.contentEncoding=g),v&&v.size>0){let x=[...v];x.length===1?f.pattern=x[0].source:x.length>1&&(a.schema.allOf=[...x.map($=>({...this.target==="draft-7"?{type:"string"}:{},pattern:$.source}))])}break}case"number":{let f=m,{minimum:h,maximum:y,format:_,multipleOf:v,exclusiveMaximum:g,exclusiveMinimum:x}=e._zod.bag;typeof _=="string"&&_.includes("int")?f.type="integer":f.type="number",typeof x=="number"&&(f.exclusiveMinimum=x),typeof h=="number"&&(f.minimum=h,typeof x=="number"&&(x>=h?delete f.minimum:delete f.exclusiveMinimum)),typeof g=="number"&&(f.exclusiveMaximum=g),typeof y=="number"&&(f.maximum=y,typeof g=="number"&&(g<=y?delete f.maximum:delete f.exclusiveMaximum)),typeof v=="number"&&(f.multipleOf=v);break}case"boolean":{let f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=m,{minimum:h,maximum:y}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof y=="number"&&(f.maxItems=y),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=m;f.type="object",f.properties={};let h=o.shape;for(let v in h)f.properties[v]=this.process(h[v],{...d,path:[...d.path,"properties",v]});let y=new Set(Object.keys(h)),_=new Set([...y].filter(v=>{let g=o.shape[v]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));_.size>0&&(f.required=Array.from(_)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=m;f.anyOf=o.options.map((h,y)=>this.process(h,{...d,path:[...d.path,"anyOf",y]}));break}case"intersection":{let f=m,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),y=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),_=g=>"allOf"in g&&Object.keys(g).length===1,v=[..._(h)?h.allOf:[h],..._(y)?y.allOf:[y]];f.allOf=v;break}case"tuple":{let f=m;f.type="array";let h=o.items.map((v,g)=>this.process(v,{...d,path:[...d.path,"prefixItems",g]}));if(this.target==="draft-2020-12"?f.prefixItems=h:f.items=h,o.rest){let v=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=v:f.additionalItems=v}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:y,maximum:_}=e._zod.bag;typeof y=="number"&&(f.minItems=y),typeof _=="number"&&(f.maxItems=_);break}case"record":{let f=m;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=m,h=so(o.entries);h.every(y=>typeof y=="number")&&(f.type="number"),h.every(y=>typeof y=="string")&&(f.type="string"),f.enum=h;break}case"literal":{let f=m,h=[];for(let y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(y))}else h.push(y);if(h.length!==0)if(h.length===1){let y=h[0];f.type=y===null?"null":typeof y,f.const=y}else h.every(y=>typeof y=="number")&&(f.type="number"),h.every(y=>typeof y=="string")&&(f.type="string"),h.every(y=>typeof y=="boolean")&&(f.type="string"),h.every(y=>y===null)&&(f.type="null"),f.enum=h;break}case"file":{let f=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:_,mime:v}=e._zod.bag;y!==void 0&&(h.minLength=y),_!==void 0&&(h.maxLength=_),v?v.length===1?(h.contentMediaType=v[0],Object.assign(f,h)):f.anyOf=v.map(g=>({...h,contentMediaType:g})):Object.assign(f,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=m;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=m,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=h.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Se(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,y=n.external.uri??(v=>v);if(h)return{ref:y(h)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${y("__shared")}#/${d}/${_}`}}if(l[1]===o)return{ref:"#"};let m=`#/${d}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:m}=s(l);d.def={...d.schema},m&&(d.defId=m);let f=d.schema;for(let h in f)delete f[h];f.$ref=p};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
29
29
 
30
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let m=n.external.registry.get(l[0])?.id;if(e!==l[0]&&m){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),m=p.def??p.schema,f={...m};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,d);let y=this.seen.get(h).schema;y.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(y)):(Object.assign(m,y),Object.assign(m,f))}p.isParent||this.override({zodSchema:l,jsonSchema:m,path:p.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var Em=G(()=>{});var qe=G(()=>{yn();Ka();Ua();mm();Es();tc();zt();Ss();Os();Hc();ec();km();$m();Sm();Em()});var Cu=G(()=>{qe()});var yo={};eo(yo,{ZodISODate:()=>Rm,ZodISODateTime:()=>Pm,ZodISODuration:()=>Om,ZodISOTime:()=>Im,date:()=>Nu,datetime:()=>Au,duration:()=>ju,time:()=>Mu});function Au(t){return _m(Pm,t)}function Nu(t){return vm(Rm,t)}function Mu(t){return xm(Im,t)}function ju(t){return bm(Om,t)}var Pm,Rm,Im,Om,Zu=G(()=>{qe();Du();Pm=w("ZodISODateTime",(t,e)=>{um.init(t,e),ve.init(t,e)});Rm=w("ZodISODate",(t,e)=>{lm.init(t,e),ve.init(t,e)});Im=w("ZodISOTime",(t,e)=>{dm.init(t,e),ve.init(t,e)});Om=w("ZodISODuration",(t,e)=>{fm.init(t,e),ve.init(t,e)})});var Cm,PA,_o,qu=G(()=>{qe();qe();Cm=(t,e)=>{$s.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>La(t,r)},flatten:{value:r=>qa(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},PA=w("ZodError",Cm),_o=w("ZodError",Cm,{Parent:Error})});var Am,Nm,Mm,jm,Lu=G(()=>{qe();qu();Am=Fa(_o),Nm=Va(_o),Mm=Ja(_o),jm=Wa(_o)});function b(t){return Vc(pw,t)}function se(t){return pu(Um,t)}function Dm(t){return mu(Iw,t)}function ze(t){return hu(Ow,t)}function Fm(t){return gu(Cw,t)}function xe(){return yu(Aw)}function Mw(t){return _u(Nw,t)}function Y(t,e){return wm(jw,t,e)}function P(t,e){let r={type:"object",get shape(){return X.assignProp(this,"shape",{...t}),this.shape},...X.normalizeParams(e)};return new Hm(r)}function Le(t,e){return new Hm({type:"object",get shape(){return X.assignProp(this,"shape",{...t}),this.shape},catchall:xe(),...X.normalizeParams(e)})}function he(t,e){return new Vm({type:"union",options:t,...X.normalizeParams(e)})}function Hu(t,e,r){return new Zw({type:"union",options:e,discriminator:t,...X.normalizeParams(r)})}function Fs(t,e){return new Dw({type:"intersection",left:t,right:e})}function pe(t,e,r){return new qw({type:"record",keyType:t,valueType:e,...X.normalizeParams(r)})}function We(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Uu({type:"enum",entries:r,...X.normalizeParams(e)})}function C(t,e){return new Lw({type:"literal",values:Array.isArray(t)?t:[t],...X.normalizeParams(e)})}function Bm(t){return new Uw({type:"transform",transform:t})}function be(t){return new Jm({type:"optional",innerType:t})}function qm(t){return new Fw({type:"nullable",innerType:t})}function Vw(t,e){return new Hw({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Jw(t,e){return new Bw({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Ww(t,e){return new Wm({type:"nonoptional",innerType:t,...X.normalizeParams(e)})}function Gw(t,e){return new Kw({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Fu(t,e){return new Xw({type:"pipe",in:t,out:e})}function Qw(t){return new Yw({type:"readonly",innerType:t})}function e$(t){let e=new Re({check:"custom"});return e._zod.check=t,e}function Gm(t,e){return Pu(Km,t??(()=>!0),e)}function t$(t,e={}){return Ru(Km,t,e)}function r$(t){let e=e$(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(X.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(X.issue(o))}},t(r.value,r)));return e}function Vu(t,e){return Fu(Bm(t),e)}var $e,Lm,pw,ve,mw,Zm,Us,hw,gw,yw,_w,vw,xw,bw,ww,$w,kw,Sw,Ew,Tw,zw,Pw,Rw,Um,Iw,Ow,Cw,Aw,Nw,jw,Hm,Vm,Zw,Dw,qw,Uu,Lw,Uw,Jm,Fw,Hw,Bw,Wm,Kw,Xw,Yw,Km,Du=G(()=>{qe();qe();Cu();Zu();Lu();$e=w("ZodType",(t,e)=>(ce.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>rt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Am(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Mm(t,r,n),t.parseAsync=async(r,n)=>Nm(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>jm(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(t$(r,n)),t.superRefine=r=>t.check(r$(r)),t.overwrite=r=>t.check(Ur(r)),t.optional=()=>be(t),t.nullable=()=>qm(t),t.nullish=()=>be(qm(t)),t.nonoptional=r=>Ww(t,r),t.array=()=>Y(t),t.or=r=>he([t,r]),t.and=r=>Fs(t,r),t.transform=r=>Fu(t,Bm(r)),t.default=r=>Vw(t,r),t.prefault=r=>Jw(t,r),t.catch=r=>Gw(t,r),t.pipe=r=>Fu(t,r),t.readonly=()=>Qw(t),t.describe=r=>{let n=t.clone();return nr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return nr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return nr.get(t);let n=t.clone();return nr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Lm=w("_ZodString",(t,e)=>{po.init(t,e),$e.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(vu(...n)),t.includes=(...n)=>t.check(wu(...n)),t.startsWith=(...n)=>t.check($u(...n)),t.endsWith=(...n)=>t.check(ku(...n)),t.min=(...n)=>t.check(xn(...n)),t.max=(...n)=>t.check(js(...n)),t.length=(...n)=>t.check(Zs(...n)),t.nonempty=(...n)=>t.check(xn(1,...n)),t.lowercase=n=>t.check(xu(n)),t.uppercase=n=>t.check(bu(n)),t.trim=()=>t.check(Eu()),t.normalize=(...n)=>t.check(Su(...n)),t.toLowerCase=()=>t.check(Tu()),t.toUpperCase=()=>t.check(zu())}),pw=w("ZodString",(t,e)=>{po.init(t,e),Lm.init(t,e),t.email=r=>t.check(Bc(mw,r)),t.url=r=>t.check(Xc(hw,r)),t.jwt=r=>t.check(fu(Rw,r)),t.emoji=r=>t.check(Yc(gw,r)),t.guid=r=>t.check(Cs(Zm,r)),t.uuid=r=>t.check(Jc(Us,r)),t.uuidv4=r=>t.check(Wc(Us,r)),t.uuidv6=r=>t.check(Kc(Us,r)),t.uuidv7=r=>t.check(Gc(Us,r)),t.nanoid=r=>t.check(Qc(yw,r)),t.guid=r=>t.check(Cs(Zm,r)),t.cuid=r=>t.check(eu(_w,r)),t.cuid2=r=>t.check(tu(vw,r)),t.ulid=r=>t.check(ru(xw,r)),t.base64=r=>t.check(uu(Tw,r)),t.base64url=r=>t.check(lu(zw,r)),t.xid=r=>t.check(nu(bw,r)),t.ksuid=r=>t.check(ou(ww,r)),t.ipv4=r=>t.check(su($w,r)),t.ipv6=r=>t.check(iu(kw,r)),t.cidrv4=r=>t.check(au(Sw,r)),t.cidrv6=r=>t.check(cu(Ew,r)),t.e164=r=>t.check(du(Pw,r)),t.datetime=r=>t.check(Au(r)),t.date=r=>t.check(Nu(r)),t.time=r=>t.check(Mu(r)),t.duration=r=>t.check(ju(r))});ve=w("ZodStringFormat",(t,e)=>{fe.init(t,e),Lm.init(t,e)}),mw=w("ZodEmail",(t,e)=>{sc.init(t,e),ve.init(t,e)}),Zm=w("ZodGUID",(t,e)=>{nc.init(t,e),ve.init(t,e)}),Us=w("ZodUUID",(t,e)=>{oc.init(t,e),ve.init(t,e)}),hw=w("ZodURL",(t,e)=>{ic.init(t,e),ve.init(t,e)}),gw=w("ZodEmoji",(t,e)=>{ac.init(t,e),ve.init(t,e)}),yw=w("ZodNanoID",(t,e)=>{cc.init(t,e),ve.init(t,e)}),_w=w("ZodCUID",(t,e)=>{uc.init(t,e),ve.init(t,e)}),vw=w("ZodCUID2",(t,e)=>{lc.init(t,e),ve.init(t,e)}),xw=w("ZodULID",(t,e)=>{dc.init(t,e),ve.init(t,e)}),bw=w("ZodXID",(t,e)=>{fc.init(t,e),ve.init(t,e)}),ww=w("ZodKSUID",(t,e)=>{pc.init(t,e),ve.init(t,e)}),$w=w("ZodIPv4",(t,e)=>{mc.init(t,e),ve.init(t,e)}),kw=w("ZodIPv6",(t,e)=>{hc.init(t,e),ve.init(t,e)}),Sw=w("ZodCIDRv4",(t,e)=>{gc.init(t,e),ve.init(t,e)}),Ew=w("ZodCIDRv6",(t,e)=>{yc.init(t,e),ve.init(t,e)}),Tw=w("ZodBase64",(t,e)=>{_c.init(t,e),ve.init(t,e)}),zw=w("ZodBase64URL",(t,e)=>{vc.init(t,e),ve.init(t,e)}),Pw=w("ZodE164",(t,e)=>{xc.init(t,e),ve.init(t,e)}),Rw=w("ZodJWT",(t,e)=>{bc.init(t,e),ve.init(t,e)}),Um=w("ZodNumber",(t,e)=>{Ps.init(t,e),$e.init(t,e),t.gt=(n,o)=>t.check(Ns(n,o)),t.gte=(n,o)=>t.check(go(n,o)),t.min=(n,o)=>t.check(go(n,o)),t.lt=(n,o)=>t.check(As(n,o)),t.lte=(n,o)=>t.check(ho(n,o)),t.max=(n,o)=>t.check(ho(n,o)),t.int=n=>t.check(Dm(n)),t.safe=n=>t.check(Dm(n)),t.positive=n=>t.check(Ns(0,n)),t.nonnegative=n=>t.check(go(0,n)),t.negative=n=>t.check(As(0,n)),t.nonpositive=n=>t.check(ho(0,n)),t.multipleOf=(n,o)=>t.check(Ms(n,o)),t.step=(n,o)=>t.check(Ms(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});Iw=w("ZodNumberFormat",(t,e)=>{wc.init(t,e),Um.init(t,e)});Ow=w("ZodBoolean",(t,e)=>{$c.init(t,e),$e.init(t,e)});Cw=w("ZodNull",(t,e)=>{kc.init(t,e),$e.init(t,e)});Aw=w("ZodUnknown",(t,e)=>{Sc.init(t,e),$e.init(t,e)});Nw=w("ZodNever",(t,e)=>{Ec.init(t,e),$e.init(t,e)});jw=w("ZodArray",(t,e)=>{Tc.init(t,e),$e.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(xn(r,n)),t.nonempty=r=>t.check(xn(1,r)),t.max=(r,n)=>t.check(js(r,n)),t.length=(r,n)=>t.check(Zs(r,n)),t.unwrap=()=>t.element});Hm=w("ZodObject",(t,e)=>{Rs.init(t,e),$e.init(t,e),X.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>We(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:xe()}),t.loose=()=>t.clone({...t._zod.def,catchall:xe()}),t.strict=()=>t.clone({...t._zod.def,catchall:Mw()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>X.extend(t,r),t.merge=r=>X.merge(t,r),t.pick=r=>X.pick(t,r),t.omit=r=>X.omit(t,r),t.partial=(...r)=>X.partial(Jm,t,r[0]),t.required=(...r)=>X.required(Wm,t,r[0])});Vm=w("ZodUnion",(t,e)=>{Is.init(t,e),$e.init(t,e),t.options=e.options});Zw=w("ZodDiscriminatedUnion",(t,e)=>{Vm.init(t,e),zc.init(t,e)});Dw=w("ZodIntersection",(t,e)=>{Pc.init(t,e),$e.init(t,e)});qw=w("ZodRecord",(t,e)=>{Rc.init(t,e),$e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Uu=w("ZodEnum",(t,e)=>{Ic.init(t,e),$e.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Uu({...e,checks:[],...X.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Uu({...e,checks:[],...X.normalizeParams(o),entries:s})}});Lw=w("ZodLiteral",(t,e)=>{Oc.init(t,e),$e.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});Uw=w("ZodTransform",(t,e)=>{Cc.init(t,e),$e.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(X.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(X.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Jm=w("ZodOptional",(t,e)=>{Ac.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Fw=w("ZodNullable",(t,e)=>{Nc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Hw=w("ZodDefault",(t,e)=>{Mc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});Bw=w("ZodPrefault",(t,e)=>{jc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Wm=w("ZodNonOptional",(t,e)=>{Zc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Kw=w("ZodCatch",(t,e)=>{Dc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Xw=w("ZodPipe",(t,e)=>{qc.init(t,e),$e.init(t,e),t.in=e.in,t.out=e.out});Yw=w("ZodReadonly",(t,e)=>{Lc.init(t,e),$e.init(t,e)});Km=w("ZodCustom",(t,e)=>{Uc.init(t,e),$e.init(t,e)})});var Xm=G(()=>{});var Ym=G(()=>{});var Qm=G(()=>{qe();Du();Cu();qu();Lu();Xm();qe();gm();Os();Zu();Ym();tt(hm())});var eh=G(()=>{Qm()});var th=G(()=>{eh()});function gh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function yh(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ju,rh,kn,ir,Vs,Ee,nh,oh,VA,s$,i$,Wu,nt,vo,sh,Ie,it,at,Oe,Bs,ih,Ft,ah,ch,Ku,Ht,N,Gu,Sn,xo,BA,Js,a$,Ws,c$,bo,$n,uh,u$,l$,d$,f$,p$,m$,Ks,Xu,h$,g$,Yu,Gs,y$,_$,Xs,v$,wo,$o,x$,ko,En,b$,So,Ys,Qs,ei,JA,ti,ri,ni,lh,dh,fh,Qu,ph,Eo,Tn,mh,w$,oi,$$,si,k$,el,S$,ii,E$,T$,z$,P$,R$,I$,O$,C$,A$,N$,ai,M$,j$,ci,tl,rl,nl,Z$,D$,q$,ol,L$,U$,F$,H$,V$,hh,ui,B$,li,WA,J$,zn,W$,KA,To,K$,sl,G$,X$,Y$,Q$,ek,tk,rk,Hs,nk,ok,sk,zo,il,ik,ak,ck,uk,lk,dk,fk,pk,mk,hk,gk,yk,_k,vk,xk,bk,wk,$k,Pn,kk,Sk,Ek,di,Tk,zk,Pk,al,Rk,GA,XA,YA,QA,eN,tN,O,Bu,Vr=G(()=>{th();Ju="2025-11-25",rh="2025-03-26",kn=[Ju,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ir="io.modelcontextprotocol/related-task",Vs="2.0",Ee=Gm(t=>t!==null&&(typeof t=="object"||typeof t=="function")),nh=he([b(),se().int()]),oh=b(),VA=Le({ttl:se().optional(),pollInterval:se().optional()}),s$=P({ttl:se().optional()}),i$=P({taskId:b()}),Wu=Le({progressToken:nh.optional(),[ir]:i$.optional()}),nt=P({_meta:Wu.optional()}),vo=nt.extend({task:s$.optional()}),sh=t=>vo.safeParse(t).success,Ie=P({method:b(),params:nt.loose().optional()}),it=P({_meta:Wu.optional()}),at=P({method:b(),params:it.loose().optional()}),Oe=Le({_meta:Wu.optional()}),Bs=he([b(),se().int()]),ih=P({jsonrpc:C(Vs),id:Bs,...Ie.shape}).strict(),Ft=t=>ih.safeParse(t).success,ah=P({jsonrpc:C(Vs),...at.shape}).strict(),ch=t=>ah.safeParse(t).success,Ku=P({jsonrpc:C(Vs),id:Bs,result:Oe}).strict(),Ht=t=>Ku.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(N||(N={}));Gu=P({jsonrpc:C(Vs),id:Bs.optional(),error:P({code:se().int(),message:b(),data:xe().optional()})}).strict(),Sn=t=>Gu.safeParse(t).success,xo=he([ih,ah,Ku,Gu]),BA=he([Ku,Gu]),Js=Oe.strict(),a$=it.extend({requestId:Bs.optional(),reason:b().optional()}),Ws=at.extend({method:C("notifications/cancelled"),params:a$}),c$=P({src:b(),mimeType:b().optional(),sizes:Y(b()).optional(),theme:We(["light","dark"]).optional()}),bo=P({icons:Y(c$).optional()}),$n=P({name:b(),title:b().optional()}),uh=$n.extend({...$n.shape,...bo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),u$=Fs(P({applyDefaults:ze().optional()}),pe(b(),xe())),l$=Vu(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Fs(P({form:u$.optional(),url:Ee.optional()}),pe(b(),xe()).optional())),d$=Le({list:Ee.optional(),cancel:Ee.optional(),requests:Le({sampling:Le({createMessage:Ee.optional()}).optional(),elicitation:Le({create:Ee.optional()}).optional()}).optional()}),f$=Le({list:Ee.optional(),cancel:Ee.optional(),requests:Le({tools:Le({call:Ee.optional()}).optional()}).optional()}),p$=P({experimental:pe(b(),Ee).optional(),sampling:P({context:Ee.optional(),tools:Ee.optional()}).optional(),elicitation:l$.optional(),roots:P({listChanged:ze().optional()}).optional(),tasks:d$.optional(),extensions:pe(b(),Ee).optional()}),m$=nt.extend({protocolVersion:b(),capabilities:p$,clientInfo:uh}),Ks=Ie.extend({method:C("initialize"),params:m$}),Xu=t=>Ks.safeParse(t).success,h$=P({experimental:pe(b(),Ee).optional(),logging:Ee.optional(),completions:Ee.optional(),prompts:P({listChanged:ze().optional()}).optional(),resources:P({subscribe:ze().optional(),listChanged:ze().optional()}).optional(),tools:P({listChanged:ze().optional()}).optional(),tasks:f$.optional(),extensions:pe(b(),Ee).optional()}),g$=Oe.extend({protocolVersion:b(),capabilities:h$,serverInfo:uh,instructions:b().optional()}),Yu=at.extend({method:C("notifications/initialized"),params:it.optional()}),Gs=Ie.extend({method:C("ping"),params:nt.optional()}),y$=P({progress:se(),total:be(se()),message:be(b())}),_$=P({...it.shape,...y$.shape,progressToken:nh}),Xs=at.extend({method:C("notifications/progress"),params:_$}),v$=nt.extend({cursor:oh.optional()}),wo=Ie.extend({params:v$.optional()}),$o=Oe.extend({nextCursor:oh.optional()}),x$=We(["working","input_required","completed","failed","cancelled"]),ko=P({taskId:b(),status:x$,ttl:he([se(),Fm()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:be(se()),statusMessage:be(b())}),En=Oe.extend({task:ko}),b$=it.merge(ko),So=at.extend({method:C("notifications/tasks/status"),params:b$}),Ys=Ie.extend({method:C("tasks/get"),params:nt.extend({taskId:b()})}),Qs=Oe.merge(ko),ei=Ie.extend({method:C("tasks/result"),params:nt.extend({taskId:b()})}),JA=Oe.loose(),ti=wo.extend({method:C("tasks/list")}),ri=$o.extend({tasks:Y(ko)}),ni=Ie.extend({method:C("tasks/cancel"),params:nt.extend({taskId:b()})}),lh=Oe.merge(ko),dh=P({uri:b(),mimeType:be(b()),_meta:pe(b(),xe()).optional()}),fh=dh.extend({text:b()}),Qu=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ph=dh.extend({blob:Qu}),Eo=We(["user","assistant"]),Tn=P({audience:Y(Eo).optional(),priority:se().min(0).max(1).optional(),lastModified:yo.datetime({offset:!0}).optional()}),mh=P({...$n.shape,...bo.shape,uri:b(),description:be(b()),mimeType:be(b()),size:be(se()),annotations:Tn.optional(),_meta:be(Le({}))}),w$=P({...$n.shape,...bo.shape,uriTemplate:b(),description:be(b()),mimeType:be(b()),annotations:Tn.optional(),_meta:be(Le({}))}),oi=wo.extend({method:C("resources/list")}),$$=$o.extend({resources:Y(mh)}),si=wo.extend({method:C("resources/templates/list")}),k$=$o.extend({resourceTemplates:Y(w$)}),el=nt.extend({uri:b()}),S$=el,ii=Ie.extend({method:C("resources/read"),params:S$}),E$=Oe.extend({contents:Y(he([fh,ph]))}),T$=at.extend({method:C("notifications/resources/list_changed"),params:it.optional()}),z$=el,P$=Ie.extend({method:C("resources/subscribe"),params:z$}),R$=el,I$=Ie.extend({method:C("resources/unsubscribe"),params:R$}),O$=it.extend({uri:b()}),C$=at.extend({method:C("notifications/resources/updated"),params:O$}),A$=P({name:b(),description:be(b()),required:be(ze())}),N$=P({...$n.shape,...bo.shape,description:be(b()),arguments:be(Y(A$)),_meta:be(Le({}))}),ai=wo.extend({method:C("prompts/list")}),M$=$o.extend({prompts:Y(N$)}),j$=nt.extend({name:b(),arguments:pe(b(),b()).optional()}),ci=Ie.extend({method:C("prompts/get"),params:j$}),tl=P({type:C("text"),text:b(),annotations:Tn.optional(),_meta:pe(b(),xe()).optional()}),rl=P({type:C("image"),data:Qu,mimeType:b(),annotations:Tn.optional(),_meta:pe(b(),xe()).optional()}),nl=P({type:C("audio"),data:Qu,mimeType:b(),annotations:Tn.optional(),_meta:pe(b(),xe()).optional()}),Z$=P({type:C("tool_use"),name:b(),id:b(),input:pe(b(),xe()),_meta:pe(b(),xe()).optional()}),D$=P({type:C("resource"),resource:he([fh,ph]),annotations:Tn.optional(),_meta:pe(b(),xe()).optional()}),q$=mh.extend({type:C("resource_link")}),ol=he([tl,rl,nl,q$,D$]),L$=P({role:Eo,content:ol}),U$=Oe.extend({description:b().optional(),messages:Y(L$)}),F$=at.extend({method:C("notifications/prompts/list_changed"),params:it.optional()}),H$=P({title:b().optional(),readOnlyHint:ze().optional(),destructiveHint:ze().optional(),idempotentHint:ze().optional(),openWorldHint:ze().optional()}),V$=P({taskSupport:We(["required","optional","forbidden"]).optional()}),hh=P({...$n.shape,...bo.shape,description:b().optional(),inputSchema:P({type:C("object"),properties:pe(b(),Ee).optional(),required:Y(b()).optional()}).catchall(xe()),outputSchema:P({type:C("object"),properties:pe(b(),Ee).optional(),required:Y(b()).optional()}).catchall(xe()).optional(),annotations:H$.optional(),execution:V$.optional(),_meta:pe(b(),xe()).optional()}),ui=wo.extend({method:C("tools/list")}),B$=$o.extend({tools:Y(hh)}),li=Oe.extend({content:Y(ol).default([]),structuredContent:pe(b(),xe()).optional(),isError:ze().optional()}),WA=li.or(Oe.extend({toolResult:xe()})),J$=vo.extend({name:b(),arguments:pe(b(),xe()).optional()}),zn=Ie.extend({method:C("tools/call"),params:J$}),W$=at.extend({method:C("notifications/tools/list_changed"),params:it.optional()}),KA=P({autoRefresh:ze().default(!0),debounceMs:se().int().nonnegative().default(300)}),To=We(["debug","info","notice","warning","error","critical","alert","emergency"]),K$=nt.extend({level:To}),sl=Ie.extend({method:C("logging/setLevel"),params:K$}),G$=it.extend({level:To,logger:b().optional(),data:xe()}),X$=at.extend({method:C("notifications/message"),params:G$}),Y$=P({name:b().optional()}),Q$=P({hints:Y(Y$).optional(),costPriority:se().min(0).max(1).optional(),speedPriority:se().min(0).max(1).optional(),intelligencePriority:se().min(0).max(1).optional()}),ek=P({mode:We(["auto","required","none"]).optional()}),tk=P({type:C("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Y(ol).default([]),structuredContent:P({}).loose().optional(),isError:ze().optional(),_meta:pe(b(),xe()).optional()}),rk=Hu("type",[tl,rl,nl]),Hs=Hu("type",[tl,rl,nl,Z$,tk]),nk=P({role:Eo,content:he([Hs,Y(Hs)]),_meta:pe(b(),xe()).optional()}),ok=vo.extend({messages:Y(nk),modelPreferences:Q$.optional(),systemPrompt:b().optional(),includeContext:We(["none","thisServer","allServers"]).optional(),temperature:se().optional(),maxTokens:se().int(),stopSequences:Y(b()).optional(),metadata:Ee.optional(),tools:Y(hh).optional(),toolChoice:ek.optional()}),sk=Ie.extend({method:C("sampling/createMessage"),params:ok}),zo=Oe.extend({model:b(),stopReason:be(We(["endTurn","stopSequence","maxTokens"]).or(b())),role:Eo,content:rk}),il=Oe.extend({model:b(),stopReason:be(We(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Eo,content:he([Hs,Y(Hs)])}),ik=P({type:C("boolean"),title:b().optional(),description:b().optional(),default:ze().optional()}),ak=P({type:C("string"),title:b().optional(),description:b().optional(),minLength:se().optional(),maxLength:se().optional(),format:We(["email","uri","date","date-time"]).optional(),default:b().optional()}),ck=P({type:We(["number","integer"]),title:b().optional(),description:b().optional(),minimum:se().optional(),maximum:se().optional(),default:se().optional()}),uk=P({type:C("string"),title:b().optional(),description:b().optional(),enum:Y(b()),default:b().optional()}),lk=P({type:C("string"),title:b().optional(),description:b().optional(),oneOf:Y(P({const:b(),title:b()})),default:b().optional()}),dk=P({type:C("string"),title:b().optional(),description:b().optional(),enum:Y(b()),enumNames:Y(b()).optional(),default:b().optional()}),fk=he([uk,lk]),pk=P({type:C("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({type:C("string"),enum:Y(b())}),default:Y(b()).optional()}),mk=P({type:C("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({anyOf:Y(P({const:b(),title:b()}))}),default:Y(b()).optional()}),hk=he([pk,mk]),gk=he([dk,fk,hk]),yk=he([gk,ik,ak,ck]),_k=vo.extend({mode:C("form").optional(),message:b(),requestedSchema:P({type:C("object"),properties:pe(b(),yk),required:Y(b()).optional()})}),vk=vo.extend({mode:C("url"),message:b(),elicitationId:b(),url:b().url()}),xk=he([_k,vk]),bk=Ie.extend({method:C("elicitation/create"),params:xk}),wk=it.extend({elicitationId:b()}),$k=at.extend({method:C("notifications/elicitation/complete"),params:wk}),Pn=Oe.extend({action:We(["accept","decline","cancel"]),content:Vu(t=>t===null?void 0:t,pe(b(),he([b(),se(),ze(),Y(b())])).optional())}),kk=P({type:C("ref/resource"),uri:b()}),Sk=P({type:C("ref/prompt"),name:b()}),Ek=nt.extend({ref:he([Sk,kk]),argument:P({name:b(),value:b()}),context:P({arguments:pe(b(),b()).optional()}).optional()}),di=Ie.extend({method:C("completion/complete"),params:Ek});Tk=Oe.extend({completion:Le({values:Y(b()).max(100),total:be(se().int()),hasMore:be(ze())})}),zk=P({uri:b().startsWith("file://"),name:b().optional(),_meta:pe(b(),xe()).optional()}),Pk=Ie.extend({method:C("roots/list"),params:nt.optional()}),al=Oe.extend({roots:Y(zk)}),Rk=at.extend({method:C("notifications/roots/list_changed"),params:it.optional()}),GA=he([Gs,Ks,di,sl,ci,ai,oi,si,ii,P$,I$,zn,ui,Ys,ei,ti,ni]),XA=he([Ws,Xs,Yu,Rk,So]),YA=he([Js,zo,il,Pn,al,Qs,ri,En]),QA=he([Gs,sk,bk,Pk,Ys,ei,ti,ni]),eN=he([Ws,Xs,X$,C$,T$,W$,F$,So,$k]),tN=he([Js,g$,Tk,U$,M$,$$,k$,E$,li,B$,Qs,ri,En]),O=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===N.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Bu(o.elicitations,r)}return new t(e,r,n)}},Bu=class extends O{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(N.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var Oo=T(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.regexpCode=oe.getEsmExportName=oe.getProperty=oe.safeStringify=oe.stringify=oe.strConcat=oe.addCodeArg=oe.str=oe._=oe.nil=oe._Code=oe.Name=oe.IDENTIFIER=oe._CodeOrName=void 0;var Ro=class{};oe._CodeOrName=Ro;oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Br=class extends Ro{constructor(e){if(super(),!oe.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};oe.Name=Br;var ct=class extends Ro{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Br&&(r[n.str]=(r[n.str]||0)+1),r),{})}};oe._Code=ct;oe.nil=new ct("");function Yh(t,...e){let r=[t[0]],n=0;for(;n<e.length;)yl(r,e[n]),r.push(t[++n]);return new ct(r)}oe._=Yh;var gl=new ct("+");function Qh(t,...e){let r=[Io(t[0])],n=0;for(;n<e.length;)r.push(gl),yl(r,e[n]),r.push(gl,Io(t[++n]));return Lk(r),new ct(r)}oe.str=Qh;function yl(t,e){e instanceof ct?t.push(...e._items):e instanceof Br?t.push(e):t.push(Hk(e))}oe.addCodeArg=yl;function Lk(t){let e=1;for(;e<t.length-1;){if(t[e]===gl){let r=Uk(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Uk(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Br||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Br))return`"${t}${e.slice(1)}`}function Fk(t,e){return e.emptyStr()?t:t.emptyStr()?e:Qh`${t}${e}`}oe.strConcat=Fk;function Hk(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Io(Array.isArray(t)?t.join(","):t)}function Vk(t){return new ct(Io(t))}oe.stringify=Vk;function Io(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oe.safeStringify=Io;function Bk(t){return typeof t=="string"&&oe.IDENTIFIER.test(t)?new ct(`.${t}`):Yh`[${t}]`}oe.getProperty=Bk;function Jk(t){if(typeof t=="string"&&oe.IDENTIFIER.test(t))return new ct(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}oe.getEsmExportName=Jk;function Wk(t){return new ct(t.toString())}oe.regexpCode=Wk});var xl=T(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.ValueScope=Ge.ValueScopeName=Ge.Scope=Ge.varKinds=Ge.UsedValueState=void 0;var Ke=Oo(),_l=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},yi;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(yi||(Ge.UsedValueState=yi={}));Ge.varKinds={const:new Ke.Name("const"),let:new Ke.Name("let"),var:new Ke.Name("var")};var _i=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ke.Name?e:this.name(e)}name(e){return new Ke.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ge.Scope=_i;var vi=class extends Ke.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ke._)`.${new Ke.Name(r)}[${n}]`}};Ge.ValueScopeName=vi;var Kk=(0,Ke._)`\n`,vl=class extends _i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Kk:Ke.nil}}get(){return this._scope}name(e){return new vi(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ke._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ke.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,yi.Started);let l=r(u);if(l){let d=this.opts.es5?Ge.varKinds.var:Ge.varKinds.const;s=(0,Ke._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ke._)`${s}${l}${this.opts._n}`;else throw new _l(u);c.set(u,yi.Completed)})}return s}};Ge.ValueScope=vl});var B=T(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.or=J.and=J.not=J.CodeGen=J.operators=J.varKinds=J.ValueScopeName=J.ValueScope=J.Scope=J.Name=J.regexpCode=J.stringify=J.getProperty=J.nil=J.strConcat=J.str=J._=void 0;var ee=Oo(),_t=xl(),cr=Oo();Object.defineProperty(J,"_",{enumerable:!0,get:function(){return cr._}});Object.defineProperty(J,"str",{enumerable:!0,get:function(){return cr.str}});Object.defineProperty(J,"strConcat",{enumerable:!0,get:function(){return cr.strConcat}});Object.defineProperty(J,"nil",{enumerable:!0,get:function(){return cr.nil}});Object.defineProperty(J,"getProperty",{enumerable:!0,get:function(){return cr.getProperty}});Object.defineProperty(J,"stringify",{enumerable:!0,get:function(){return cr.stringify}});Object.defineProperty(J,"regexpCode",{enumerable:!0,get:function(){return cr.regexpCode}});Object.defineProperty(J,"Name",{enumerable:!0,get:function(){return cr.Name}});var $i=xl();Object.defineProperty(J,"Scope",{enumerable:!0,get:function(){return $i.Scope}});Object.defineProperty(J,"ValueScope",{enumerable:!0,get:function(){return $i.ValueScope}});Object.defineProperty(J,"ValueScopeName",{enumerable:!0,get:function(){return $i.ValueScopeName}});Object.defineProperty(J,"varKinds",{enumerable:!0,get:function(){return $i.varKinds}});J.operators={GT:new ee._Code(">"),GTE:new ee._Code(">="),LT:new ee._Code("<"),LTE:new ee._Code("<="),EQ:new ee._Code("==="),NEQ:new ee._Code("!=="),NOT:new ee._Code("!"),OR:new ee._Code("||"),AND:new ee._Code("&&"),ADD:new ee._Code("+")};var Vt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},bl=class extends Vt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?_t.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=In(this.rhs,e,r)),this}get names(){return this.rhs instanceof ee._CodeOrName?this.rhs.names:{}}},xi=class extends Vt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ee.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=In(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ee.Name?{}:{...this.lhs.names};return wi(e,this.rhs)}},wl=class extends xi{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},$l=class extends Vt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},kl=class extends Vt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Sl=class extends Vt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},El=class extends Vt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=In(this.code,e,r),this}get names(){return this.code instanceof ee._CodeOrName?this.code.names:{}}},Co=class extends Vt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(Gk(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Kr(e,r.names),{})}},Bt=class extends Co{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Tl=class extends Co{},Rn=class extends Bt{};Rn.kind="else";var Jr=class t extends Bt{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Rn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(eg(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=In(this.condition,e,r),this}get names(){let e=super.names;return wi(e,this.condition),this.else&&Kr(e,this.else.names),e}};Jr.kind="if";var Wr=class extends Bt{};Wr.kind="for";var zl=class extends Wr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=In(this.iteration,e,r),this}get names(){return Kr(super.names,this.iteration.names)}},Pl=class extends Wr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?_t.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=wi(super.names,this.from);return wi(e,this.to)}},bi=class extends Wr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=In(this.iterable,e,r),this}get names(){return Kr(super.names,this.iterable.names)}},Ao=class extends Bt{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ao.kind="func";var No=class extends Co{render(e){return"return "+super.render(e)}};No.kind="return";var Rl=class extends Bt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Kr(e,this.catch.names),this.finally&&Kr(e,this.finally.names),e}},Mo=class extends Bt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Mo.kind="catch";var jo=class extends Bt{render(e){return"finally"+super.render(e)}};jo.kind="finally";var Il=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
31
- `:""},this._extScope=e,this._scope=new _t.Scope({parent:e}),this._nodes=[new Tl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new bl(e,s,n)),s}const(e,r,n){return this._def(_t.varKinds.const,e,r,n)}let(e,r,n){return this._def(_t.varKinds.let,e,r,n)}var(e,r,n){return this._def(_t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new xi(e,r,n))}add(e,r){return this._leafNode(new wl(e,J.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ee.nil&&this._leafNode(new El(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ee.addCodeArg)(r,o));return r.push("}"),new ee._Code(r)}if(e,r,n){if(this._blockNode(new Jr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Jr(e))}else(){return this._elseNode(new Rn)}endIf(){return this._endBlockNode(Jr,Rn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new zl(e),r)}forRange(e,r,n,o,s=this.opts.es5?_t.varKinds.var:_t.varKinds.let){let i=this._scope.toName(e);return this._for(new Pl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=_t.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ee.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ee._)`${i}.length`,a=>{this.var(s,(0,ee._)`${i}[${a}]`),n(s)})}return this._for(new bi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?_t.varKinds.var:_t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ee._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new bi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Wr)}label(e){return this._leafNode(new $l(e))}break(e){return this._leafNode(new kl(e))}return(e){let r=new No;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(No)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Rl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Mo(s),r(s)}return n&&(this._currNode=o.finally=new jo,this.code(n)),this._endBlockNode(Mo,jo)}throw(e){return this._leafNode(new Sl(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ee.nil,n,o){return this._blockNode(new Ao(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Ao)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Jr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};J.CodeGen=Il;function Kr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function wi(t,e){return e instanceof ee._CodeOrName?Kr(t,e.names):t}function In(t,e,r){if(t instanceof ee.Name)return n(t);if(!o(t))return t;return new ee._Code(t._items.reduce((s,i)=>(i instanceof ee.Name&&(i=n(i)),i instanceof ee._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ee._Code&&s._items.some(i=>i instanceof ee.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Gk(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function eg(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ee._)`!${Ol(t)}`}J.not=eg;var Xk=tg(J.operators.AND);function Yk(...t){return t.reduce(Xk)}J.and=Yk;var Qk=tg(J.operators.OR);function eS(...t){return t.reduce(Qk)}J.or=eS;function tg(t){return(e,r)=>e===ee.nil?r:r===ee.nil?e:(0,ee._)`${Ol(e)} ${t} ${Ol(r)}`}function Ol(t){return t instanceof ee.Name?t:(0,ee._)`(${t})`}});var re=T(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.checkStrictMode=W.getErrorPath=W.Type=W.useFunc=W.setEvaluated=W.evaluatedPropsToName=W.mergeEvaluated=W.eachItem=W.unescapeJsonPointer=W.escapeJsonPointer=W.escapeFragment=W.unescapeFragment=W.schemaRefOrVal=W.schemaHasRulesButRef=W.schemaHasRules=W.checkUnknownRules=W.alwaysValidSchema=W.toHash=void 0;var le=B(),tS=Oo();function rS(t){let e={};for(let r of t)e[r]=!0;return e}W.toHash=rS;function nS(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(og(t,e),!sg(e,t.self.RULES.all))}W.alwaysValidSchema=nS;function og(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||cg(t,`unknown keyword: "${s}"`)}W.checkUnknownRules=og;function sg(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}W.schemaHasRules=sg;function oS(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}W.schemaHasRulesButRef=oS;function sS({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,le._)`${r}`}return(0,le._)`${t}${e}${(0,le.getProperty)(n)}`}W.schemaRefOrVal=sS;function iS(t){return ig(decodeURIComponent(t))}W.unescapeFragment=iS;function aS(t){return encodeURIComponent(Al(t))}W.escapeFragment=aS;function Al(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}W.escapeJsonPointer=Al;function ig(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}W.unescapeJsonPointer=ig;function cS(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}W.eachItem=cS;function rg({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof le.Name?(s instanceof le.Name?t(o,s,i):e(o,s,i),i):s instanceof le.Name?(e(o,i,s),s):r(s,i);return a===le.Name&&!(c instanceof le.Name)?n(o,c):c}}W.mergeEvaluated={props:rg({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,le._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,le._)`${r} || {}`).code((0,le._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,le._)`${r} || {}`),Nl(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:ag}),items:rg({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,le._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,le._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function ag(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&Nl(t,r,e),r}W.evaluatedPropsToName=ag;function Nl(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}W.setEvaluated=Nl;var ng={};function uS(t,e){return t.scopeValue("func",{ref:e,code:ng[e.code]||(ng[e.code]=new tS._Code(e.code))})}W.useFunc=uS;var Cl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Cl||(W.Type=Cl={}));function lS(t,e,r){if(t instanceof le.Name){let n=e===Cl.Num;return r?n?(0,le._)`"[" + ${t} + "]"`:(0,le._)`"['" + ${t} + "']"`:n?(0,le._)`"/" + ${t}`:(0,le._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,le.getProperty)(t).toString():"/"+Al(t)}W.getErrorPath=lS;function cg(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}W.checkStrictMode=cg});var Jt=T(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var Me=B(),dS={data:new Me.Name("data"),valCxt:new Me.Name("valCxt"),instancePath:new Me.Name("instancePath"),parentData:new Me.Name("parentData"),parentDataProperty:new Me.Name("parentDataProperty"),rootData:new Me.Name("rootData"),dynamicAnchors:new Me.Name("dynamicAnchors"),vErrors:new Me.Name("vErrors"),errors:new Me.Name("errors"),this:new Me.Name("this"),self:new Me.Name("self"),scope:new Me.Name("scope"),json:new Me.Name("json"),jsonPos:new Me.Name("jsonPos"),jsonLen:new Me.Name("jsonLen"),jsonPart:new Me.Name("jsonPart")};Ml.default=dS});var Zo=T(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.extendErrors=je.resetErrorsCount=je.reportExtraError=je.reportError=je.keyword$DataError=je.keywordError=void 0;var ne=B(),ki=re(),Fe=Jt();je.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};je.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function fS(t,e=je.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=dg(t,e,r);n??(i||a)?ug(s,c):lg(o,(0,ne._)`[${c}]`)}je.reportError=fS;function pS(t,e=je.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=dg(t,e,r);ug(o,a),s||i||lg(n,Fe.default.vErrors)}je.reportExtraError=pS;function mS(t,e){t.assign(Fe.default.errors,e),t.if((0,ne._)`${Fe.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Fe.default.vErrors}.length`,e),()=>t.assign(Fe.default.vErrors,null)))}je.resetErrorsCount=mS;function hS({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Fe.default.errors,a=>{t.const(i,(0,ne._)`${Fe.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Fe.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}je.extendErrors=hS;function ug(t,e){let r=t.const("err",e);t.if((0,ne._)`${Fe.default.vErrors} === null`,()=>t.assign(Fe.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Fe.default.vErrors}.push(${r})`),t.code((0,ne._)`${Fe.default.errors}++`)}function lg(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var Gr={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function dg(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:gS(t,e,r)}function gS(t,e,r={}){let{gen:n,it:o}=t,s=[yS(o,r),_S(t,r)];return vS(t,e,s),n.object(...s)}function yS({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,ki.getErrorPath)(e,ki.Type.Str)}`:t;return[Fe.default.instancePath,(0,ne.strConcat)(Fe.default.instancePath,r)]}function _S({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ne.str)`${e}/${t}`;return r&&(o=(0,ne.str)`${o}${(0,ki.getErrorPath)(r,ki.Type.Str)}`),[Gr.schemaPath,o]}function vS(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Gr.keyword,o],[Gr.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([Gr.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Gr.schema,i],[Gr.parentSchema,(0,ne._)`${l}${d}`],[Fe.default.data,s]),u&&n.push([Gr.propertyName,u])}});var pg=T(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.boolOrEmptySchema=On.topBoolOrEmptySchema=void 0;var xS=Zo(),bS=B(),wS=Jt(),$S={message:"boolean schema is false"};function kS(t){let{gen:e,schema:r,validateName:n}=t;r===!1?fg(t,!1):typeof r=="object"&&r.$async===!0?e.return(wS.default.data):(e.assign((0,bS._)`${n}.errors`,null),e.return(!0))}On.topBoolOrEmptySchema=kS;function SS(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),fg(t)):r.var(e,!0)}On.boolOrEmptySchema=SS;function fg(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,xS.reportError)(o,$S,void 0,e)}});var jl=T(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.getRules=Cn.isJSONType=void 0;var ES=["string","number","integer","boolean","null","object","array"],TS=new Set(ES);function zS(t){return typeof t=="string"&&TS.has(t)}Cn.isJSONType=zS;function PS(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Cn.getRules=PS});var Zl=T(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.shouldUseRule=ur.shouldUseGroup=ur.schemaHasRulesForType=void 0;function RS({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&mg(t,n)}ur.schemaHasRulesForType=RS;function mg(t,e){return e.rules.some(r=>hg(t,r))}ur.shouldUseGroup=mg;function hg(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}ur.shouldUseRule=hg});var Do=T(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.reportTypeError=Ze.checkDataTypes=Ze.checkDataType=Ze.coerceAndCheckDataType=Ze.getJSONTypes=Ze.getSchemaTypes=Ze.DataType=void 0;var IS=jl(),OS=Zl(),CS=Zo(),F=B(),gg=re(),An;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(An||(Ze.DataType=An={}));function AS(t){let e=yg(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ze.getSchemaTypes=AS;function yg(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(IS.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ze.getJSONTypes=yg;function NS(t,e){let{gen:r,data:n,opts:o}=t,s=MS(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,OS.schemaHasRulesForType)(t,e[0]));if(i){let a=ql(e,n,o.strictNumbers,An.Wrong);r.if(a,()=>{s.length?jS(t,e,s):Ll(t)})}return i}Ze.coerceAndCheckDataType=NS;var _g=new Set(["string","number","integer","boolean","null"]);function MS(t,e){return e?t.filter(r=>_g.has(r)||e==="array"&&r==="array"):[]}function jS(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,F._)`typeof ${o}`),a=n.let("coerced",(0,F._)`undefined`);s.coerceTypes==="array"&&n.if((0,F._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,F._)`${o}[0]`).assign(i,(0,F._)`typeof ${o}`).if(ql(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,F._)`${a} !== undefined`);for(let u of r)(_g.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Ll(t),n.endIf(),n.if((0,F._)`${a} !== undefined`,()=>{n.assign(o,a),ZS(t,a)});function c(u){switch(u){case"string":n.elseIf((0,F._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,F._)`"" + ${o}`).elseIf((0,F._)`${o} === null`).assign(a,(0,F._)`""`);return;case"number":n.elseIf((0,F._)`${i} == "boolean" || ${o} === null
30
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let m=n.external.registry.get(l[0])?.id;if(e!==l[0]&&m){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),m=p.def??p.schema,f={...m};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,d);let y=this.seen.get(h).schema;y.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(y)):(Object.assign(m,y),Object.assign(m,f))}p.isParent||this.override({zodSchema:l,jsonSchema:m,path:p.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var Tm=G(()=>{});var Le=G(()=>{yn();Ga();Fa();hm();Es();rc();zt();Ss();Os();Vc();tc();Sm();km();Em();Tm()});var Au=G(()=>{Le()});var yo={};eo(yo,{ZodISODate:()=>Im,ZodISODateTime:()=>Rm,ZodISODuration:()=>Cm,ZodISOTime:()=>Om,date:()=>Mu,datetime:()=>Nu,duration:()=>Zu,time:()=>ju});function Nu(t){return vm(Rm,t)}function Mu(t){return xm(Im,t)}function ju(t){return bm(Om,t)}function Zu(t){return wm(Cm,t)}var Rm,Im,Om,Cm,Du=G(()=>{Le();qu();Rm=w("ZodISODateTime",(t,e)=>{lm.init(t,e),ve.init(t,e)});Im=w("ZodISODate",(t,e)=>{dm.init(t,e),ve.init(t,e)});Om=w("ZodISOTime",(t,e)=>{fm.init(t,e),ve.init(t,e)});Cm=w("ZodISODuration",(t,e)=>{pm.init(t,e),ve.init(t,e)})});var Am,RA,_o,Lu=G(()=>{Le();Le();Am=(t,e)=>{$s.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Ua(t,r)},flatten:{value:r=>La(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},RA=w("ZodError",Am),_o=w("ZodError",Am,{Parent:Error})});var Nm,Mm,jm,Zm,Uu=G(()=>{Le();Lu();Nm=Ha(_o),Mm=Ba(_o),jm=Wa(_o),Zm=Ka(_o)});function b(t){return Bc(hw,t)}function se(t){return mu(Fm,t)}function qm(t){return hu(Cw,t)}function ze(t){return gu(Aw,t)}function Hm(t){return yu(Nw,t)}function xe(){return _u(Mw)}function Zw(t){return vu(jw,t)}function Y(t,e){return $m(Dw,t,e)}function P(t,e){let r={type:"object",get shape(){return X.assignProp(this,"shape",{...t}),this.shape},...X.normalizeParams(e)};return new Vm(r)}function Ue(t,e){return new Vm({type:"object",get shape(){return X.assignProp(this,"shape",{...t}),this.shape},catchall:xe(),...X.normalizeParams(e)})}function he(t,e){return new Bm({type:"union",options:t,...X.normalizeParams(e)})}function Vu(t,e,r){return new qw({type:"union",options:e,discriminator:t,...X.normalizeParams(r)})}function Fs(t,e){return new Lw({type:"intersection",left:t,right:e})}function me(t,e,r){return new Uw({type:"record",keyType:t,valueType:e,...X.normalizeParams(r)})}function Ke(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Fu({type:"enum",entries:r,...X.normalizeParams(e)})}function C(t,e){return new Fw({type:"literal",values:Array.isArray(t)?t:[t],...X.normalizeParams(e)})}function Jm(t){return new Hw({type:"transform",transform:t})}function be(t){return new Wm({type:"optional",innerType:t})}function Lm(t){return new Vw({type:"nullable",innerType:t})}function Jw(t,e){return new Bw({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Kw(t,e){return new Ww({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Gw(t,e){return new Km({type:"nonoptional",innerType:t,...X.normalizeParams(e)})}function Yw(t,e){return new Xw({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Hu(t,e){return new Qw({type:"pipe",in:t,out:e})}function t$(t){return new e$({type:"readonly",innerType:t})}function r$(t){let e=new Re({check:"custom"});return e._zod.check=t,e}function Xm(t,e){return Ru(Gm,t??(()=>!0),e)}function n$(t,e={}){return Iu(Gm,t,e)}function o$(t){let e=r$(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(X.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(X.issue(o))}},t(r.value,r)));return e}function Bu(t,e){return Hu(Jm(t),e)}var $e,Um,hw,ve,gw,Dm,Us,yw,_w,vw,xw,bw,ww,$w,kw,Sw,Ew,Tw,zw,Pw,Rw,Iw,Ow,Fm,Cw,Aw,Nw,Mw,jw,Dw,Vm,Bm,qw,Lw,Uw,Fu,Fw,Hw,Wm,Vw,Bw,Ww,Km,Xw,Qw,e$,Gm,qu=G(()=>{Le();Le();Au();Du();Uu();$e=w("ZodType",(t,e)=>(ue.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>rt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Nm(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>jm(t,r,n),t.parseAsync=async(r,n)=>Mm(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Zm(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(n$(r,n)),t.superRefine=r=>t.check(o$(r)),t.overwrite=r=>t.check(Ur(r)),t.optional=()=>be(t),t.nullable=()=>Lm(t),t.nullish=()=>be(Lm(t)),t.nonoptional=r=>Gw(t,r),t.array=()=>Y(t),t.or=r=>he([t,r]),t.and=r=>Fs(t,r),t.transform=r=>Hu(t,Jm(r)),t.default=r=>Jw(t,r),t.prefault=r=>Kw(t,r),t.catch=r=>Yw(t,r),t.pipe=r=>Hu(t,r),t.readonly=()=>t$(t),t.describe=r=>{let n=t.clone();return nr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return nr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return nr.get(t);let n=t.clone();return nr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Um=w("_ZodString",(t,e)=>{po.init(t,e),$e.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(xu(...n)),t.includes=(...n)=>t.check($u(...n)),t.startsWith=(...n)=>t.check(ku(...n)),t.endsWith=(...n)=>t.check(Su(...n)),t.min=(...n)=>t.check(xn(...n)),t.max=(...n)=>t.check(js(...n)),t.length=(...n)=>t.check(Zs(...n)),t.nonempty=(...n)=>t.check(xn(1,...n)),t.lowercase=n=>t.check(bu(n)),t.uppercase=n=>t.check(wu(n)),t.trim=()=>t.check(Tu()),t.normalize=(...n)=>t.check(Eu(...n)),t.toLowerCase=()=>t.check(zu()),t.toUpperCase=()=>t.check(Pu())}),hw=w("ZodString",(t,e)=>{po.init(t,e),Um.init(t,e),t.email=r=>t.check(Jc(gw,r)),t.url=r=>t.check(Yc(yw,r)),t.jwt=r=>t.check(pu(Ow,r)),t.emoji=r=>t.check(Qc(_w,r)),t.guid=r=>t.check(Cs(Dm,r)),t.uuid=r=>t.check(Wc(Us,r)),t.uuidv4=r=>t.check(Kc(Us,r)),t.uuidv6=r=>t.check(Gc(Us,r)),t.uuidv7=r=>t.check(Xc(Us,r)),t.nanoid=r=>t.check(eu(vw,r)),t.guid=r=>t.check(Cs(Dm,r)),t.cuid=r=>t.check(tu(xw,r)),t.cuid2=r=>t.check(ru(bw,r)),t.ulid=r=>t.check(nu(ww,r)),t.base64=r=>t.check(lu(Pw,r)),t.base64url=r=>t.check(du(Rw,r)),t.xid=r=>t.check(ou($w,r)),t.ksuid=r=>t.check(su(kw,r)),t.ipv4=r=>t.check(iu(Sw,r)),t.ipv6=r=>t.check(au(Ew,r)),t.cidrv4=r=>t.check(cu(Tw,r)),t.cidrv6=r=>t.check(uu(zw,r)),t.e164=r=>t.check(fu(Iw,r)),t.datetime=r=>t.check(Nu(r)),t.date=r=>t.check(Mu(r)),t.time=r=>t.check(ju(r)),t.duration=r=>t.check(Zu(r))});ve=w("ZodStringFormat",(t,e)=>{pe.init(t,e),Um.init(t,e)}),gw=w("ZodEmail",(t,e)=>{ic.init(t,e),ve.init(t,e)}),Dm=w("ZodGUID",(t,e)=>{oc.init(t,e),ve.init(t,e)}),Us=w("ZodUUID",(t,e)=>{sc.init(t,e),ve.init(t,e)}),yw=w("ZodURL",(t,e)=>{ac.init(t,e),ve.init(t,e)}),_w=w("ZodEmoji",(t,e)=>{cc.init(t,e),ve.init(t,e)}),vw=w("ZodNanoID",(t,e)=>{uc.init(t,e),ve.init(t,e)}),xw=w("ZodCUID",(t,e)=>{lc.init(t,e),ve.init(t,e)}),bw=w("ZodCUID2",(t,e)=>{dc.init(t,e),ve.init(t,e)}),ww=w("ZodULID",(t,e)=>{fc.init(t,e),ve.init(t,e)}),$w=w("ZodXID",(t,e)=>{pc.init(t,e),ve.init(t,e)}),kw=w("ZodKSUID",(t,e)=>{mc.init(t,e),ve.init(t,e)}),Sw=w("ZodIPv4",(t,e)=>{hc.init(t,e),ve.init(t,e)}),Ew=w("ZodIPv6",(t,e)=>{gc.init(t,e),ve.init(t,e)}),Tw=w("ZodCIDRv4",(t,e)=>{yc.init(t,e),ve.init(t,e)}),zw=w("ZodCIDRv6",(t,e)=>{_c.init(t,e),ve.init(t,e)}),Pw=w("ZodBase64",(t,e)=>{vc.init(t,e),ve.init(t,e)}),Rw=w("ZodBase64URL",(t,e)=>{xc.init(t,e),ve.init(t,e)}),Iw=w("ZodE164",(t,e)=>{bc.init(t,e),ve.init(t,e)}),Ow=w("ZodJWT",(t,e)=>{wc.init(t,e),ve.init(t,e)}),Fm=w("ZodNumber",(t,e)=>{Ps.init(t,e),$e.init(t,e),t.gt=(n,o)=>t.check(Ns(n,o)),t.gte=(n,o)=>t.check(go(n,o)),t.min=(n,o)=>t.check(go(n,o)),t.lt=(n,o)=>t.check(As(n,o)),t.lte=(n,o)=>t.check(ho(n,o)),t.max=(n,o)=>t.check(ho(n,o)),t.int=n=>t.check(qm(n)),t.safe=n=>t.check(qm(n)),t.positive=n=>t.check(Ns(0,n)),t.nonnegative=n=>t.check(go(0,n)),t.negative=n=>t.check(As(0,n)),t.nonpositive=n=>t.check(ho(0,n)),t.multipleOf=(n,o)=>t.check(Ms(n,o)),t.step=(n,o)=>t.check(Ms(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});Cw=w("ZodNumberFormat",(t,e)=>{$c.init(t,e),Fm.init(t,e)});Aw=w("ZodBoolean",(t,e)=>{kc.init(t,e),$e.init(t,e)});Nw=w("ZodNull",(t,e)=>{Sc.init(t,e),$e.init(t,e)});Mw=w("ZodUnknown",(t,e)=>{Ec.init(t,e),$e.init(t,e)});jw=w("ZodNever",(t,e)=>{Tc.init(t,e),$e.init(t,e)});Dw=w("ZodArray",(t,e)=>{zc.init(t,e),$e.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(xn(r,n)),t.nonempty=r=>t.check(xn(1,r)),t.max=(r,n)=>t.check(js(r,n)),t.length=(r,n)=>t.check(Zs(r,n)),t.unwrap=()=>t.element});Vm=w("ZodObject",(t,e)=>{Rs.init(t,e),$e.init(t,e),X.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Ke(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:xe()}),t.loose=()=>t.clone({...t._zod.def,catchall:xe()}),t.strict=()=>t.clone({...t._zod.def,catchall:Zw()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>X.extend(t,r),t.merge=r=>X.merge(t,r),t.pick=r=>X.pick(t,r),t.omit=r=>X.omit(t,r),t.partial=(...r)=>X.partial(Wm,t,r[0]),t.required=(...r)=>X.required(Km,t,r[0])});Bm=w("ZodUnion",(t,e)=>{Is.init(t,e),$e.init(t,e),t.options=e.options});qw=w("ZodDiscriminatedUnion",(t,e)=>{Bm.init(t,e),Pc.init(t,e)});Lw=w("ZodIntersection",(t,e)=>{Rc.init(t,e),$e.init(t,e)});Uw=w("ZodRecord",(t,e)=>{Ic.init(t,e),$e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Fu=w("ZodEnum",(t,e)=>{Oc.init(t,e),$e.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Fu({...e,checks:[],...X.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Fu({...e,checks:[],...X.normalizeParams(o),entries:s})}});Fw=w("ZodLiteral",(t,e)=>{Cc.init(t,e),$e.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});Hw=w("ZodTransform",(t,e)=>{Ac.init(t,e),$e.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(X.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(X.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Wm=w("ZodOptional",(t,e)=>{Nc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Vw=w("ZodNullable",(t,e)=>{Mc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Bw=w("ZodDefault",(t,e)=>{jc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});Ww=w("ZodPrefault",(t,e)=>{Zc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Km=w("ZodNonOptional",(t,e)=>{Dc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Xw=w("ZodCatch",(t,e)=>{qc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Qw=w("ZodPipe",(t,e)=>{Lc.init(t,e),$e.init(t,e),t.in=e.in,t.out=e.out});e$=w("ZodReadonly",(t,e)=>{Uc.init(t,e),$e.init(t,e)});Gm=w("ZodCustom",(t,e)=>{Fc.init(t,e),$e.init(t,e)})});var Ym=G(()=>{});var Qm=G(()=>{});var eh=G(()=>{Le();qu();Au();Lu();Uu();Ym();Le();ym();Os();Du();Qm();tt(gm())});var th=G(()=>{eh()});var rh=G(()=>{th()});function yh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function _h(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Wu,nh,kn,ir,Vs,Ee,oh,sh,BA,a$,c$,Ku,nt,vo,ih,Ie,it,at,Oe,Bs,ah,Ft,ch,uh,Gu,Ht,N,Xu,Sn,xo,JA,Js,u$,Ws,l$,bo,$n,lh,d$,f$,p$,m$,h$,g$,Ks,Yu,y$,_$,Qu,Gs,v$,x$,Xs,b$,wo,$o,w$,ko,En,$$,So,Ys,Qs,ei,WA,ti,ri,ni,dh,fh,ph,el,mh,Eo,Tn,hh,k$,oi,S$,si,E$,tl,T$,ii,z$,P$,R$,I$,O$,C$,A$,N$,M$,j$,ai,Z$,D$,ci,rl,nl,ol,q$,L$,U$,sl,F$,H$,V$,B$,J$,gh,ui,W$,li,KA,K$,zn,G$,GA,To,X$,il,Y$,Q$,ek,tk,rk,nk,ok,Hs,sk,ik,ak,zo,al,ck,uk,lk,dk,fk,pk,mk,hk,gk,yk,_k,vk,xk,bk,wk,$k,kk,Sk,Pn,Ek,Tk,zk,di,Pk,Rk,Ik,cl,Ok,XA,YA,QA,eN,tN,rN,O,Ju,Vr=G(()=>{rh();Wu="2025-11-25",nh="2025-03-26",kn=[Wu,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ir="io.modelcontextprotocol/related-task",Vs="2.0",Ee=Xm(t=>t!==null&&(typeof t=="object"||typeof t=="function")),oh=he([b(),se().int()]),sh=b(),BA=Ue({ttl:se().optional(),pollInterval:se().optional()}),a$=P({ttl:se().optional()}),c$=P({taskId:b()}),Ku=Ue({progressToken:oh.optional(),[ir]:c$.optional()}),nt=P({_meta:Ku.optional()}),vo=nt.extend({task:a$.optional()}),ih=t=>vo.safeParse(t).success,Ie=P({method:b(),params:nt.loose().optional()}),it=P({_meta:Ku.optional()}),at=P({method:b(),params:it.loose().optional()}),Oe=Ue({_meta:Ku.optional()}),Bs=he([b(),se().int()]),ah=P({jsonrpc:C(Vs),id:Bs,...Ie.shape}).strict(),Ft=t=>ah.safeParse(t).success,ch=P({jsonrpc:C(Vs),...at.shape}).strict(),uh=t=>ch.safeParse(t).success,Gu=P({jsonrpc:C(Vs),id:Bs,result:Oe}).strict(),Ht=t=>Gu.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(N||(N={}));Xu=P({jsonrpc:C(Vs),id:Bs.optional(),error:P({code:se().int(),message:b(),data:xe().optional()})}).strict(),Sn=t=>Xu.safeParse(t).success,xo=he([ah,ch,Gu,Xu]),JA=he([Gu,Xu]),Js=Oe.strict(),u$=it.extend({requestId:Bs.optional(),reason:b().optional()}),Ws=at.extend({method:C("notifications/cancelled"),params:u$}),l$=P({src:b(),mimeType:b().optional(),sizes:Y(b()).optional(),theme:Ke(["light","dark"]).optional()}),bo=P({icons:Y(l$).optional()}),$n=P({name:b(),title:b().optional()}),lh=$n.extend({...$n.shape,...bo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),d$=Fs(P({applyDefaults:ze().optional()}),me(b(),xe())),f$=Bu(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Fs(P({form:d$.optional(),url:Ee.optional()}),me(b(),xe()).optional())),p$=Ue({list:Ee.optional(),cancel:Ee.optional(),requests:Ue({sampling:Ue({createMessage:Ee.optional()}).optional(),elicitation:Ue({create:Ee.optional()}).optional()}).optional()}),m$=Ue({list:Ee.optional(),cancel:Ee.optional(),requests:Ue({tools:Ue({call:Ee.optional()}).optional()}).optional()}),h$=P({experimental:me(b(),Ee).optional(),sampling:P({context:Ee.optional(),tools:Ee.optional()}).optional(),elicitation:f$.optional(),roots:P({listChanged:ze().optional()}).optional(),tasks:p$.optional(),extensions:me(b(),Ee).optional()}),g$=nt.extend({protocolVersion:b(),capabilities:h$,clientInfo:lh}),Ks=Ie.extend({method:C("initialize"),params:g$}),Yu=t=>Ks.safeParse(t).success,y$=P({experimental:me(b(),Ee).optional(),logging:Ee.optional(),completions:Ee.optional(),prompts:P({listChanged:ze().optional()}).optional(),resources:P({subscribe:ze().optional(),listChanged:ze().optional()}).optional(),tools:P({listChanged:ze().optional()}).optional(),tasks:m$.optional(),extensions:me(b(),Ee).optional()}),_$=Oe.extend({protocolVersion:b(),capabilities:y$,serverInfo:lh,instructions:b().optional()}),Qu=at.extend({method:C("notifications/initialized"),params:it.optional()}),Gs=Ie.extend({method:C("ping"),params:nt.optional()}),v$=P({progress:se(),total:be(se()),message:be(b())}),x$=P({...it.shape,...v$.shape,progressToken:oh}),Xs=at.extend({method:C("notifications/progress"),params:x$}),b$=nt.extend({cursor:sh.optional()}),wo=Ie.extend({params:b$.optional()}),$o=Oe.extend({nextCursor:sh.optional()}),w$=Ke(["working","input_required","completed","failed","cancelled"]),ko=P({taskId:b(),status:w$,ttl:he([se(),Hm()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:be(se()),statusMessage:be(b())}),En=Oe.extend({task:ko}),$$=it.merge(ko),So=at.extend({method:C("notifications/tasks/status"),params:$$}),Ys=Ie.extend({method:C("tasks/get"),params:nt.extend({taskId:b()})}),Qs=Oe.merge(ko),ei=Ie.extend({method:C("tasks/result"),params:nt.extend({taskId:b()})}),WA=Oe.loose(),ti=wo.extend({method:C("tasks/list")}),ri=$o.extend({tasks:Y(ko)}),ni=Ie.extend({method:C("tasks/cancel"),params:nt.extend({taskId:b()})}),dh=Oe.merge(ko),fh=P({uri:b(),mimeType:be(b()),_meta:me(b(),xe()).optional()}),ph=fh.extend({text:b()}),el=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),mh=fh.extend({blob:el}),Eo=Ke(["user","assistant"]),Tn=P({audience:Y(Eo).optional(),priority:se().min(0).max(1).optional(),lastModified:yo.datetime({offset:!0}).optional()}),hh=P({...$n.shape,...bo.shape,uri:b(),description:be(b()),mimeType:be(b()),size:be(se()),annotations:Tn.optional(),_meta:be(Ue({}))}),k$=P({...$n.shape,...bo.shape,uriTemplate:b(),description:be(b()),mimeType:be(b()),annotations:Tn.optional(),_meta:be(Ue({}))}),oi=wo.extend({method:C("resources/list")}),S$=$o.extend({resources:Y(hh)}),si=wo.extend({method:C("resources/templates/list")}),E$=$o.extend({resourceTemplates:Y(k$)}),tl=nt.extend({uri:b()}),T$=tl,ii=Ie.extend({method:C("resources/read"),params:T$}),z$=Oe.extend({contents:Y(he([ph,mh]))}),P$=at.extend({method:C("notifications/resources/list_changed"),params:it.optional()}),R$=tl,I$=Ie.extend({method:C("resources/subscribe"),params:R$}),O$=tl,C$=Ie.extend({method:C("resources/unsubscribe"),params:O$}),A$=it.extend({uri:b()}),N$=at.extend({method:C("notifications/resources/updated"),params:A$}),M$=P({name:b(),description:be(b()),required:be(ze())}),j$=P({...$n.shape,...bo.shape,description:be(b()),arguments:be(Y(M$)),_meta:be(Ue({}))}),ai=wo.extend({method:C("prompts/list")}),Z$=$o.extend({prompts:Y(j$)}),D$=nt.extend({name:b(),arguments:me(b(),b()).optional()}),ci=Ie.extend({method:C("prompts/get"),params:D$}),rl=P({type:C("text"),text:b(),annotations:Tn.optional(),_meta:me(b(),xe()).optional()}),nl=P({type:C("image"),data:el,mimeType:b(),annotations:Tn.optional(),_meta:me(b(),xe()).optional()}),ol=P({type:C("audio"),data:el,mimeType:b(),annotations:Tn.optional(),_meta:me(b(),xe()).optional()}),q$=P({type:C("tool_use"),name:b(),id:b(),input:me(b(),xe()),_meta:me(b(),xe()).optional()}),L$=P({type:C("resource"),resource:he([ph,mh]),annotations:Tn.optional(),_meta:me(b(),xe()).optional()}),U$=hh.extend({type:C("resource_link")}),sl=he([rl,nl,ol,U$,L$]),F$=P({role:Eo,content:sl}),H$=Oe.extend({description:b().optional(),messages:Y(F$)}),V$=at.extend({method:C("notifications/prompts/list_changed"),params:it.optional()}),B$=P({title:b().optional(),readOnlyHint:ze().optional(),destructiveHint:ze().optional(),idempotentHint:ze().optional(),openWorldHint:ze().optional()}),J$=P({taskSupport:Ke(["required","optional","forbidden"]).optional()}),gh=P({...$n.shape,...bo.shape,description:b().optional(),inputSchema:P({type:C("object"),properties:me(b(),Ee).optional(),required:Y(b()).optional()}).catchall(xe()),outputSchema:P({type:C("object"),properties:me(b(),Ee).optional(),required:Y(b()).optional()}).catchall(xe()).optional(),annotations:B$.optional(),execution:J$.optional(),_meta:me(b(),xe()).optional()}),ui=wo.extend({method:C("tools/list")}),W$=$o.extend({tools:Y(gh)}),li=Oe.extend({content:Y(sl).default([]),structuredContent:me(b(),xe()).optional(),isError:ze().optional()}),KA=li.or(Oe.extend({toolResult:xe()})),K$=vo.extend({name:b(),arguments:me(b(),xe()).optional()}),zn=Ie.extend({method:C("tools/call"),params:K$}),G$=at.extend({method:C("notifications/tools/list_changed"),params:it.optional()}),GA=P({autoRefresh:ze().default(!0),debounceMs:se().int().nonnegative().default(300)}),To=Ke(["debug","info","notice","warning","error","critical","alert","emergency"]),X$=nt.extend({level:To}),il=Ie.extend({method:C("logging/setLevel"),params:X$}),Y$=it.extend({level:To,logger:b().optional(),data:xe()}),Q$=at.extend({method:C("notifications/message"),params:Y$}),ek=P({name:b().optional()}),tk=P({hints:Y(ek).optional(),costPriority:se().min(0).max(1).optional(),speedPriority:se().min(0).max(1).optional(),intelligencePriority:se().min(0).max(1).optional()}),rk=P({mode:Ke(["auto","required","none"]).optional()}),nk=P({type:C("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Y(sl).default([]),structuredContent:P({}).loose().optional(),isError:ze().optional(),_meta:me(b(),xe()).optional()}),ok=Vu("type",[rl,nl,ol]),Hs=Vu("type",[rl,nl,ol,q$,nk]),sk=P({role:Eo,content:he([Hs,Y(Hs)]),_meta:me(b(),xe()).optional()}),ik=vo.extend({messages:Y(sk),modelPreferences:tk.optional(),systemPrompt:b().optional(),includeContext:Ke(["none","thisServer","allServers"]).optional(),temperature:se().optional(),maxTokens:se().int(),stopSequences:Y(b()).optional(),metadata:Ee.optional(),tools:Y(gh).optional(),toolChoice:rk.optional()}),ak=Ie.extend({method:C("sampling/createMessage"),params:ik}),zo=Oe.extend({model:b(),stopReason:be(Ke(["endTurn","stopSequence","maxTokens"]).or(b())),role:Eo,content:ok}),al=Oe.extend({model:b(),stopReason:be(Ke(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Eo,content:he([Hs,Y(Hs)])}),ck=P({type:C("boolean"),title:b().optional(),description:b().optional(),default:ze().optional()}),uk=P({type:C("string"),title:b().optional(),description:b().optional(),minLength:se().optional(),maxLength:se().optional(),format:Ke(["email","uri","date","date-time"]).optional(),default:b().optional()}),lk=P({type:Ke(["number","integer"]),title:b().optional(),description:b().optional(),minimum:se().optional(),maximum:se().optional(),default:se().optional()}),dk=P({type:C("string"),title:b().optional(),description:b().optional(),enum:Y(b()),default:b().optional()}),fk=P({type:C("string"),title:b().optional(),description:b().optional(),oneOf:Y(P({const:b(),title:b()})),default:b().optional()}),pk=P({type:C("string"),title:b().optional(),description:b().optional(),enum:Y(b()),enumNames:Y(b()).optional(),default:b().optional()}),mk=he([dk,fk]),hk=P({type:C("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({type:C("string"),enum:Y(b())}),default:Y(b()).optional()}),gk=P({type:C("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({anyOf:Y(P({const:b(),title:b()}))}),default:Y(b()).optional()}),yk=he([hk,gk]),_k=he([pk,mk,yk]),vk=he([_k,ck,uk,lk]),xk=vo.extend({mode:C("form").optional(),message:b(),requestedSchema:P({type:C("object"),properties:me(b(),vk),required:Y(b()).optional()})}),bk=vo.extend({mode:C("url"),message:b(),elicitationId:b(),url:b().url()}),wk=he([xk,bk]),$k=Ie.extend({method:C("elicitation/create"),params:wk}),kk=it.extend({elicitationId:b()}),Sk=at.extend({method:C("notifications/elicitation/complete"),params:kk}),Pn=Oe.extend({action:Ke(["accept","decline","cancel"]),content:Bu(t=>t===null?void 0:t,me(b(),he([b(),se(),ze(),Y(b())])).optional())}),Ek=P({type:C("ref/resource"),uri:b()}),Tk=P({type:C("ref/prompt"),name:b()}),zk=nt.extend({ref:he([Tk,Ek]),argument:P({name:b(),value:b()}),context:P({arguments:me(b(),b()).optional()}).optional()}),di=Ie.extend({method:C("completion/complete"),params:zk});Pk=Oe.extend({completion:Ue({values:Y(b()).max(100),total:be(se().int()),hasMore:be(ze())})}),Rk=P({uri:b().startsWith("file://"),name:b().optional(),_meta:me(b(),xe()).optional()}),Ik=Ie.extend({method:C("roots/list"),params:nt.optional()}),cl=Oe.extend({roots:Y(Rk)}),Ok=at.extend({method:C("notifications/roots/list_changed"),params:it.optional()}),XA=he([Gs,Ks,di,il,ci,ai,oi,si,ii,I$,C$,zn,ui,Ys,ei,ti,ni]),YA=he([Ws,Xs,Qu,Ok,So]),QA=he([Js,zo,al,Pn,cl,Qs,ri,En]),eN=he([Gs,ak,$k,Ik,Ys,ei,ti,ni]),tN=he([Ws,Xs,Q$,N$,P$,G$,V$,So,Sk]),rN=he([Js,_$,Pk,H$,Z$,S$,E$,z$,li,W$,Qs,ri,En]),O=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===N.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ju(o.elicitations,r)}return new t(e,r,n)}},Ju=class extends O{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(N.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var Oo=T(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.regexpCode=oe.getEsmExportName=oe.getProperty=oe.safeStringify=oe.stringify=oe.strConcat=oe.addCodeArg=oe.str=oe._=oe.nil=oe._Code=oe.Name=oe.IDENTIFIER=oe._CodeOrName=void 0;var Ro=class{};oe._CodeOrName=Ro;oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Br=class extends Ro{constructor(e){if(super(),!oe.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};oe.Name=Br;var ct=class extends Ro{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Br&&(r[n.str]=(r[n.str]||0)+1),r),{})}};oe._Code=ct;oe.nil=new ct("");function Qh(t,...e){let r=[t[0]],n=0;for(;n<e.length;)_l(r,e[n]),r.push(t[++n]);return new ct(r)}oe._=Qh;var yl=new ct("+");function eg(t,...e){let r=[Io(t[0])],n=0;for(;n<e.length;)r.push(yl),_l(r,e[n]),r.push(yl,Io(t[++n]));return Fk(r),new ct(r)}oe.str=eg;function _l(t,e){e instanceof ct?t.push(...e._items):e instanceof Br?t.push(e):t.push(Bk(e))}oe.addCodeArg=_l;function Fk(t){let e=1;for(;e<t.length-1;){if(t[e]===yl){let r=Hk(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Hk(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Br||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Br))return`"${t}${e.slice(1)}`}function Vk(t,e){return e.emptyStr()?t:t.emptyStr()?e:eg`${t}${e}`}oe.strConcat=Vk;function Bk(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Io(Array.isArray(t)?t.join(","):t)}function Jk(t){return new ct(Io(t))}oe.stringify=Jk;function Io(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oe.safeStringify=Io;function Wk(t){return typeof t=="string"&&oe.IDENTIFIER.test(t)?new ct(`.${t}`):Qh`[${t}]`}oe.getProperty=Wk;function Kk(t){if(typeof t=="string"&&oe.IDENTIFIER.test(t))return new ct(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}oe.getEsmExportName=Kk;function Gk(t){return new ct(t.toString())}oe.regexpCode=Gk});var bl=T(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ge=Oo(),vl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},yi;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(yi||(Xe.UsedValueState=yi={}));Xe.varKinds={const:new Ge.Name("const"),let:new Ge.Name("let"),var:new Ge.Name("var")};var _i=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ge.Name?e:this.name(e)}name(e){return new Ge.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Xe.Scope=_i;var vi=class extends Ge.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ge._)`.${new Ge.Name(r)}[${n}]`}};Xe.ValueScopeName=vi;var Xk=(0,Ge._)`\n`,xl=class extends _i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Xk:Ge.nil}}get(){return this._scope}name(e){return new vi(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ge._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ge.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,yi.Started);let l=r(u);if(l){let d=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;s=(0,Ge._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ge._)`${s}${l}${this.opts._n}`;else throw new vl(u);c.set(u,yi.Completed)})}return s}};Xe.ValueScope=xl});var B=T(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.or=J.and=J.not=J.CodeGen=J.operators=J.varKinds=J.ValueScopeName=J.ValueScope=J.Scope=J.Name=J.regexpCode=J.stringify=J.getProperty=J.nil=J.strConcat=J.str=J._=void 0;var ee=Oo(),_t=bl(),cr=Oo();Object.defineProperty(J,"_",{enumerable:!0,get:function(){return cr._}});Object.defineProperty(J,"str",{enumerable:!0,get:function(){return cr.str}});Object.defineProperty(J,"strConcat",{enumerable:!0,get:function(){return cr.strConcat}});Object.defineProperty(J,"nil",{enumerable:!0,get:function(){return cr.nil}});Object.defineProperty(J,"getProperty",{enumerable:!0,get:function(){return cr.getProperty}});Object.defineProperty(J,"stringify",{enumerable:!0,get:function(){return cr.stringify}});Object.defineProperty(J,"regexpCode",{enumerable:!0,get:function(){return cr.regexpCode}});Object.defineProperty(J,"Name",{enumerable:!0,get:function(){return cr.Name}});var $i=bl();Object.defineProperty(J,"Scope",{enumerable:!0,get:function(){return $i.Scope}});Object.defineProperty(J,"ValueScope",{enumerable:!0,get:function(){return $i.ValueScope}});Object.defineProperty(J,"ValueScopeName",{enumerable:!0,get:function(){return $i.ValueScopeName}});Object.defineProperty(J,"varKinds",{enumerable:!0,get:function(){return $i.varKinds}});J.operators={GT:new ee._Code(">"),GTE:new ee._Code(">="),LT:new ee._Code("<"),LTE:new ee._Code("<="),EQ:new ee._Code("==="),NEQ:new ee._Code("!=="),NOT:new ee._Code("!"),OR:new ee._Code("||"),AND:new ee._Code("&&"),ADD:new ee._Code("+")};var Vt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},wl=class extends Vt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?_t.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=In(this.rhs,e,r)),this}get names(){return this.rhs instanceof ee._CodeOrName?this.rhs.names:{}}},xi=class extends Vt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ee.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=In(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ee.Name?{}:{...this.lhs.names};return wi(e,this.rhs)}},$l=class extends xi{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},kl=class extends Vt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Sl=class extends Vt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},El=class extends Vt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Tl=class extends Vt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=In(this.code,e,r),this}get names(){return this.code instanceof ee._CodeOrName?this.code.names:{}}},Co=class extends Vt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(Yk(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Kr(e,r.names),{})}},Bt=class extends Co{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},zl=class extends Co{},Rn=class extends Bt{};Rn.kind="else";var Jr=class t extends Bt{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Rn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(tg(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=In(this.condition,e,r),this}get names(){let e=super.names;return wi(e,this.condition),this.else&&Kr(e,this.else.names),e}};Jr.kind="if";var Wr=class extends Bt{};Wr.kind="for";var Pl=class extends Wr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=In(this.iteration,e,r),this}get names(){return Kr(super.names,this.iteration.names)}},Rl=class extends Wr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?_t.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=wi(super.names,this.from);return wi(e,this.to)}},bi=class extends Wr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=In(this.iterable,e,r),this}get names(){return Kr(super.names,this.iterable.names)}},Ao=class extends Bt{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ao.kind="func";var No=class extends Co{render(e){return"return "+super.render(e)}};No.kind="return";var Il=class extends Bt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Kr(e,this.catch.names),this.finally&&Kr(e,this.finally.names),e}},Mo=class extends Bt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Mo.kind="catch";var jo=class extends Bt{render(e){return"finally"+super.render(e)}};jo.kind="finally";var Ol=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
31
+ `:""},this._extScope=e,this._scope=new _t.Scope({parent:e}),this._nodes=[new zl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new wl(e,s,n)),s}const(e,r,n){return this._def(_t.varKinds.const,e,r,n)}let(e,r,n){return this._def(_t.varKinds.let,e,r,n)}var(e,r,n){return this._def(_t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new xi(e,r,n))}add(e,r){return this._leafNode(new $l(e,J.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ee.nil&&this._leafNode(new Tl(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ee.addCodeArg)(r,o));return r.push("}"),new ee._Code(r)}if(e,r,n){if(this._blockNode(new Jr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Jr(e))}else(){return this._elseNode(new Rn)}endIf(){return this._endBlockNode(Jr,Rn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Pl(e),r)}forRange(e,r,n,o,s=this.opts.es5?_t.varKinds.var:_t.varKinds.let){let i=this._scope.toName(e);return this._for(new Rl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=_t.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ee.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ee._)`${i}.length`,a=>{this.var(s,(0,ee._)`${i}[${a}]`),n(s)})}return this._for(new bi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?_t.varKinds.var:_t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ee._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new bi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Wr)}label(e){return this._leafNode(new kl(e))}break(e){return this._leafNode(new Sl(e))}return(e){let r=new No;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(No)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Il;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Mo(s),r(s)}return n&&(this._currNode=o.finally=new jo,this.code(n)),this._endBlockNode(Mo,jo)}throw(e){return this._leafNode(new El(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ee.nil,n,o){return this._blockNode(new Ao(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Ao)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Jr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};J.CodeGen=Ol;function Kr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function wi(t,e){return e instanceof ee._CodeOrName?Kr(t,e.names):t}function In(t,e,r){if(t instanceof ee.Name)return n(t);if(!o(t))return t;return new ee._Code(t._items.reduce((s,i)=>(i instanceof ee.Name&&(i=n(i)),i instanceof ee._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ee._Code&&s._items.some(i=>i instanceof ee.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Yk(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function tg(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ee._)`!${Cl(t)}`}J.not=tg;var Qk=rg(J.operators.AND);function eS(...t){return t.reduce(Qk)}J.and=eS;var tS=rg(J.operators.OR);function rS(...t){return t.reduce(tS)}J.or=rS;function rg(t){return(e,r)=>e===ee.nil?r:r===ee.nil?e:(0,ee._)`${Cl(e)} ${t} ${Cl(r)}`}function Cl(t){return t instanceof ee.Name?t:(0,ee._)`(${t})`}});var re=T(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.checkStrictMode=W.getErrorPath=W.Type=W.useFunc=W.setEvaluated=W.evaluatedPropsToName=W.mergeEvaluated=W.eachItem=W.unescapeJsonPointer=W.escapeJsonPointer=W.escapeFragment=W.unescapeFragment=W.schemaRefOrVal=W.schemaHasRulesButRef=W.schemaHasRules=W.checkUnknownRules=W.alwaysValidSchema=W.toHash=void 0;var de=B(),nS=Oo();function oS(t){let e={};for(let r of t)e[r]=!0;return e}W.toHash=oS;function sS(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(sg(t,e),!ig(e,t.self.RULES.all))}W.alwaysValidSchema=sS;function sg(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||ug(t,`unknown keyword: "${s}"`)}W.checkUnknownRules=sg;function ig(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}W.schemaHasRules=ig;function iS(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}W.schemaHasRulesButRef=iS;function aS({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,de._)`${r}`}return(0,de._)`${t}${e}${(0,de.getProperty)(n)}`}W.schemaRefOrVal=aS;function cS(t){return ag(decodeURIComponent(t))}W.unescapeFragment=cS;function uS(t){return encodeURIComponent(Nl(t))}W.escapeFragment=uS;function Nl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}W.escapeJsonPointer=Nl;function ag(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}W.unescapeJsonPointer=ag;function lS(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}W.eachItem=lS;function ng({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof de.Name?(s instanceof de.Name?t(o,s,i):e(o,s,i),i):s instanceof de.Name?(e(o,i,s),s):r(s,i);return a===de.Name&&!(c instanceof de.Name)?n(o,c):c}}W.mergeEvaluated={props:ng({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,de._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,de._)`${r} || {}`).code((0,de._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,de._)`${r} || {}`),Ml(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:cg}),items:ng({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,de._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,de._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function cg(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,de._)`{}`);return e!==void 0&&Ml(t,r,e),r}W.evaluatedPropsToName=cg;function Ml(t,e,r){Object.keys(r).forEach(n=>t.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}W.setEvaluated=Ml;var og={};function dS(t,e){return t.scopeValue("func",{ref:e,code:og[e.code]||(og[e.code]=new nS._Code(e.code))})}W.useFunc=dS;var Al;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Al||(W.Type=Al={}));function fS(t,e,r){if(t instanceof de.Name){let n=e===Al.Num;return r?n?(0,de._)`"[" + ${t} + "]"`:(0,de._)`"['" + ${t} + "']"`:n?(0,de._)`"/" + ${t}`:(0,de._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,de.getProperty)(t).toString():"/"+Nl(t)}W.getErrorPath=fS;function ug(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}W.checkStrictMode=ug});var Jt=T(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var je=B(),pS={data:new je.Name("data"),valCxt:new je.Name("valCxt"),instancePath:new je.Name("instancePath"),parentData:new je.Name("parentData"),parentDataProperty:new je.Name("parentDataProperty"),rootData:new je.Name("rootData"),dynamicAnchors:new je.Name("dynamicAnchors"),vErrors:new je.Name("vErrors"),errors:new je.Name("errors"),this:new je.Name("this"),self:new je.Name("self"),scope:new je.Name("scope"),json:new je.Name("json"),jsonPos:new je.Name("jsonPos"),jsonLen:new je.Name("jsonLen"),jsonPart:new je.Name("jsonPart")};jl.default=pS});var Zo=T(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.extendErrors=Ze.resetErrorsCount=Ze.reportExtraError=Ze.reportError=Ze.keyword$DataError=Ze.keywordError=void 0;var ne=B(),ki=re(),He=Jt();Ze.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};Ze.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function mS(t,e=Ze.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=fg(t,e,r);n??(i||a)?lg(s,c):dg(o,(0,ne._)`[${c}]`)}Ze.reportError=mS;function hS(t,e=Ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=fg(t,e,r);lg(o,a),s||i||dg(n,He.default.vErrors)}Ze.reportExtraError=hS;function gS(t,e){t.assign(He.default.errors,e),t.if((0,ne._)`${He.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${He.default.vErrors}.length`,e),()=>t.assign(He.default.vErrors,null)))}Ze.resetErrorsCount=gS;function yS({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,He.default.errors,a=>{t.const(i,(0,ne._)`${He.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(He.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}Ze.extendErrors=yS;function lg(t,e){let r=t.const("err",e);t.if((0,ne._)`${He.default.vErrors} === null`,()=>t.assign(He.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${He.default.vErrors}.push(${r})`),t.code((0,ne._)`${He.default.errors}++`)}function dg(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var Gr={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function fg(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:_S(t,e,r)}function _S(t,e,r={}){let{gen:n,it:o}=t,s=[vS(o,r),xS(t,r)];return bS(t,e,s),n.object(...s)}function vS({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,ki.getErrorPath)(e,ki.Type.Str)}`:t;return[He.default.instancePath,(0,ne.strConcat)(He.default.instancePath,r)]}function xS({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ne.str)`${e}/${t}`;return r&&(o=(0,ne.str)`${o}${(0,ki.getErrorPath)(r,ki.Type.Str)}`),[Gr.schemaPath,o]}function bS(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Gr.keyword,o],[Gr.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([Gr.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Gr.schema,i],[Gr.parentSchema,(0,ne._)`${l}${d}`],[He.default.data,s]),u&&n.push([Gr.propertyName,u])}});var mg=T(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.boolOrEmptySchema=On.topBoolOrEmptySchema=void 0;var wS=Zo(),$S=B(),kS=Jt(),SS={message:"boolean schema is false"};function ES(t){let{gen:e,schema:r,validateName:n}=t;r===!1?pg(t,!1):typeof r=="object"&&r.$async===!0?e.return(kS.default.data):(e.assign((0,$S._)`${n}.errors`,null),e.return(!0))}On.topBoolOrEmptySchema=ES;function TS(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),pg(t)):r.var(e,!0)}On.boolOrEmptySchema=TS;function pg(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,wS.reportError)(o,SS,void 0,e)}});var Zl=T(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.getRules=Cn.isJSONType=void 0;var zS=["string","number","integer","boolean","null","object","array"],PS=new Set(zS);function RS(t){return typeof t=="string"&&PS.has(t)}Cn.isJSONType=RS;function IS(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Cn.getRules=IS});var Dl=T(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.shouldUseRule=ur.shouldUseGroup=ur.schemaHasRulesForType=void 0;function OS({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&hg(t,n)}ur.schemaHasRulesForType=OS;function hg(t,e){return e.rules.some(r=>gg(t,r))}ur.shouldUseGroup=hg;function gg(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}ur.shouldUseRule=gg});var Do=T(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;var CS=Zl(),AS=Dl(),NS=Zo(),F=B(),yg=re(),An;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(An||(De.DataType=An={}));function MS(t){let e=_g(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}De.getSchemaTypes=MS;function _g(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(CS.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}De.getJSONTypes=_g;function jS(t,e){let{gen:r,data:n,opts:o}=t,s=ZS(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,AS.schemaHasRulesForType)(t,e[0]));if(i){let a=Ll(e,n,o.strictNumbers,An.Wrong);r.if(a,()=>{s.length?DS(t,e,s):Ul(t)})}return i}De.coerceAndCheckDataType=jS;var vg=new Set(["string","number","integer","boolean","null"]);function ZS(t,e){return e?t.filter(r=>vg.has(r)||e==="array"&&r==="array"):[]}function DS(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,F._)`typeof ${o}`),a=n.let("coerced",(0,F._)`undefined`);s.coerceTypes==="array"&&n.if((0,F._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,F._)`${o}[0]`).assign(i,(0,F._)`typeof ${o}`).if(Ll(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,F._)`${a} !== undefined`);for(let u of r)(vg.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Ul(t),n.endIf(),n.if((0,F._)`${a} !== undefined`,()=>{n.assign(o,a),qS(t,a)});function c(u){switch(u){case"string":n.elseIf((0,F._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,F._)`"" + ${o}`).elseIf((0,F._)`${o} === null`).assign(a,(0,F._)`""`);return;case"number":n.elseIf((0,F._)`${i} == "boolean" || ${o} === null
32
32
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,F._)`+${o}`);return;case"integer":n.elseIf((0,F._)`${i} === "boolean" || ${o} === null
33
33
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,F._)`+${o}`);return;case"boolean":n.elseIf((0,F._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,F._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,F._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,F._)`${i} === "string" || ${i} === "number"
34
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,F._)`[${o}]`)}}}function ZS({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,F._)`${e} !== undefined`,()=>t.assign((0,F._)`${e}[${r}]`,n))}function Dl(t,e,r,n=An.Correct){let o=n===An.Correct?F.operators.EQ:F.operators.NEQ,s;switch(t){case"null":return(0,F._)`${e} ${o} null`;case"array":s=(0,F._)`Array.isArray(${e})`;break;case"object":s=(0,F._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,F._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,F._)`typeof ${e} ${o} ${t}`}return n===An.Correct?s:(0,F.not)(s);function i(a=F.nil){return(0,F.and)((0,F._)`typeof ${e} == "number"`,a,r?(0,F._)`isFinite(${e})`:F.nil)}}Ze.checkDataType=Dl;function ql(t,e,r,n){if(t.length===1)return Dl(t[0],e,r,n);let o,s=(0,gg.toHash)(t);if(s.array&&s.object){let i=(0,F._)`typeof ${e} != "object"`;o=s.null?i:(0,F._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=F.nil;s.number&&delete s.integer;for(let i in s)o=(0,F.and)(o,Dl(i,e,r,n));return o}Ze.checkDataTypes=ql;var DS={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,F._)`{type: ${t}}`:(0,F._)`{type: ${e}}`};function Ll(t){let e=qS(t);(0,CS.reportError)(e,DS)}Ze.reportTypeError=Ll;function qS(t){let{gen:e,data:r,schema:n}=t,o=(0,gg.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var xg=T(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.assignDefaults=void 0;var Nn=B(),LS=re();function US(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)vg(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>vg(t,s,o.default))}Si.assignDefaults=US;function vg(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Nn._)`${s}${(0,Nn.getProperty)(e)}`;if(o){(0,LS.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Nn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Nn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Nn._)`${a} = ${(0,Nn.stringify)(r)}`)}});var ut=T(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=B(),Ul=re(),lr=Jt(),FS=re();function HS(t,e){let{gen:r,data:n,it:o}=t;r.if(Hl(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=HS;function VS({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(Hl(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=VS;function BS(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=BS;function bg(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=bg;function Fl(t,e,r){return(0,ge._)`${bg(t)}.call(${e}, ${r})`}ue.isOwnProperty=Fl;function JS(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${Fl(t,e,r)}`:o}ue.propertyInData=JS;function Hl(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(Fl(t,e,r))):o}ue.noPropertyInData=Hl;function wg(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=wg;function WS(t,e){return wg(e).filter(r=>!(0,Ul.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=WS;function KS({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[lr.default.instancePath,(0,ge.strConcat)(lr.default.instancePath,s)],[lr.default.parentData,i.parentData],[lr.default.parentDataProperty,i.parentDataProperty],[lr.default.rootData,lr.default.rootData]];i.opts.dynamicRef&&d.push([lr.default.dynamicAnchors,lr.default.dynamicAnchors]);let p=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}ue.callValidateCode=KS;var GS=(0,ge._)`new RegExp`;function XS({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?GS:(0,FS.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=XS;function YS(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Ul.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=YS;function QS(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Ul.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ue.validateUnion=QS});var Sg=T(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.validateKeywordUsage=Rt.validSchemaType=Rt.funcKeywordCode=Rt.macroKeywordCode=void 0;var He=B(),Xr=Jt(),eE=ut(),tE=Zo();function rE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=kg(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:He.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Rt.macroKeywordCode=rE;function nE(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;sE(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=kg(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)h(),e.modifying&&$g(t),y(()=>t.error());else{let _=e.async?m():f();e.modifying&&$g(t),y(()=>oE(t,_))}}function m(){let _=n.let("ruleErrs",null);return n.try(()=>h((0,He._)`await `),v=>n.assign(d,!1).if((0,He._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,He._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,He._)`${l}.errors`;return n.assign(_,null),h(He.nil),_}function h(_=e.async?(0,He._)`await `:He.nil){let v=c.opts.passContext?Xr.default.this:Xr.default.self,g=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,He._)`${_}${(0,eE.callValidateCode)(t,l,v,g)}`,e.modifying)}function y(_){var v;n.if((0,He.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}Rt.funcKeywordCode=nE;function $g(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,He._)`${n.parentData}[${n.parentDataProperty}]`))}function oE(t,e){let{gen:r}=t;r.if((0,He._)`Array.isArray(${e})`,()=>{r.assign(Xr.default.vErrors,(0,He._)`${Xr.default.vErrors} === null ? ${e} : ${Xr.default.vErrors}.concat(${e})`).assign(Xr.default.errors,(0,He._)`${Xr.default.vErrors}.length`),(0,tE.extendErrors)(t)},()=>t.error())}function sE({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function kg(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,He.stringify)(r)})}function iE(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Rt.validSchemaType=iE;function aE({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Rt.validateKeywordUsage=aE});var Tg=T(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.extendSubschemaMode=dr.extendSubschemaData=dr.getSubschema=void 0;var It=B(),Eg=re();function cE(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,It._)`${t.schemaPath}${(0,It.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,It._)`${t.schemaPath}${(0,It.getProperty)(e)}${(0,It.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Eg.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}dr.getSubschema=cE;function uE(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,It._)`${e.data}${(0,It.getProperty)(r)}`,!0);c(p),t.errorPath=(0,It.str)`${u}${(0,Eg.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,It._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof It.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}dr.extendSubschemaData=uE;function lE(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}dr.extendSubschemaMode=lE});var Vl=T((yZ,zg)=>{"use strict";zg.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Rg=T((_Z,Pg)=>{"use strict";var fr=Pg.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Ei(e,n,o,t,"",t)};fr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};fr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};fr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};fr.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 Ei(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in fr.arrayKeywords)for(var p=0;p<d.length;p++)Ei(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in fr.propsKeywords){if(d&&typeof d=="object")for(var m in d)Ei(t,e,r,d[m],o+"/"+l+"/"+dE(m),s,o,l,n,m)}else(l in fr.keywords||t.allKeys&&!(l in fr.skipKeywords))&&Ei(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function dE(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var qo=T(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.getSchemaRefs=Xe.resolveUrl=Xe.normalizeId=Xe._getFullPath=Xe.getFullPath=Xe.inlineRef=void 0;var fE=re(),pE=Vl(),mE=Rg(),hE=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function gE(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Bl(t):e?Ig(t)<=e:!1}Xe.inlineRef=gE;var yE=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Bl(t){for(let e in t){if(yE.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Bl)||typeof r=="object"&&Bl(r))return!0}return!1}function Ig(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!hE.has(r)&&(typeof t[r]=="object"&&(0,fE.eachItem)(t[r],n=>e+=Ig(n)),e===1/0))return 1/0}return e}function Og(t,e="",r){r!==!1&&(e=Mn(e));let n=t.parse(e);return Cg(t,n)}Xe.getFullPath=Og;function Cg(t,e){return t.serialize(e).split("#")[0]+"#"}Xe._getFullPath=Cg;var _E=/#\/?$/;function Mn(t){return t?t.replace(_E,""):""}Xe.normalizeId=Mn;function vE(t,e,r){return r=Mn(r),t.resolve(e,r)}Xe.resolveUrl=vE;var xE=/^[a-z_][-a-z0-9._]*$/i;function bE(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Mn(t[r]||e),s={"":o},i=Og(n,o,!1),a={},c=new Set;return mE(t,{allKeys:!0},(d,p,m,f)=>{if(f===void 0)return;let h=i+p,y=s[f];typeof d[r]=="string"&&(y=_.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[p]=y;function _(g){let x=this.opts.uriResolver.resolve;if(g=Mn(y?x(y,g):g),c.has(g))throw l(g);c.add(g);let $=this.refs[g];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,g):g!==Mn(h)&&(g[0]==="#"?(u(d,a[g],g),a[g]=d):this.refs[g]=h),g}function v(g){if(typeof g=="string"){if(!xE.test(g))throw new Error(`invalid anchor "${g}"`);_.call(this,`#${g}`)}}}),a;function u(d,p,m){if(p!==void 0&&!pE(d,p))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Xe.getSchemaRefs=bE});var Fo=T(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.getData=pr.KeywordCxt=pr.validateFunctionCode=void 0;var Zg=pg(),Ag=Do(),Wl=Zl(),Ti=Do(),wE=xg(),Uo=Sg(),Jl=Tg(),A=B(),q=Jt(),$E=qo(),Wt=re(),Lo=Zo();function kE(t){if(Lg(t)&&(Ug(t),qg(t))){TE(t);return}Dg(t,()=>(0,Zg.topBoolOrEmptySchema)(t))}pr.validateFunctionCode=kE;function Dg({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,A._)`${q.default.data}, ${q.default.valCxt}`,n.$async,()=>{t.code((0,A._)`"use strict"; ${Ng(r,o)}`),EE(t,o),t.code(s)}):t.func(e,(0,A._)`${q.default.data}, ${SE(o)}`,n.$async,()=>t.code(Ng(r,o)).code(s))}function SE(t){return(0,A._)`{${q.default.instancePath}="", ${q.default.parentData}, ${q.default.parentDataProperty}, ${q.default.rootData}=${q.default.data}${t.dynamicRef?(0,A._)`, ${q.default.dynamicAnchors}={}`:A.nil}}={}`}function EE(t,e){t.if(q.default.valCxt,()=>{t.var(q.default.instancePath,(0,A._)`${q.default.valCxt}.${q.default.instancePath}`),t.var(q.default.parentData,(0,A._)`${q.default.valCxt}.${q.default.parentData}`),t.var(q.default.parentDataProperty,(0,A._)`${q.default.valCxt}.${q.default.parentDataProperty}`),t.var(q.default.rootData,(0,A._)`${q.default.valCxt}.${q.default.rootData}`),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,A._)`${q.default.valCxt}.${q.default.dynamicAnchors}`)},()=>{t.var(q.default.instancePath,(0,A._)`""`),t.var(q.default.parentData,(0,A._)`undefined`),t.var(q.default.parentDataProperty,(0,A._)`undefined`),t.var(q.default.rootData,q.default.data),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,A._)`{}`)})}function TE(t){let{schema:e,opts:r,gen:n}=t;Dg(t,()=>{r.$comment&&e.$comment&&Hg(t),OE(t),n.let(q.default.vErrors,null),n.let(q.default.errors,0),r.unevaluated&&zE(t),Fg(t),NE(t)})}function zE(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,A._)`${r}.evaluated`),e.if((0,A._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,A._)`${t.evaluated}.props`,(0,A._)`undefined`)),e.if((0,A._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,A._)`${t.evaluated}.items`,(0,A._)`undefined`))}function Ng(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,A._)`/*# sourceURL=${r} */`:A.nil}function PE(t,e){if(Lg(t)&&(Ug(t),qg(t))){RE(t,e);return}(0,Zg.boolOrEmptySchema)(t,e)}function qg({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Lg(t){return typeof t.schema!="boolean"}function RE(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Hg(t),CE(t),AE(t);let s=n.const("_errs",q.default.errors);Fg(t,s),n.var(e,(0,A._)`${s} === ${q.default.errors}`)}function Ug(t){(0,Wt.checkUnknownRules)(t),IE(t)}function Fg(t,e){if(t.opts.jtd)return Mg(t,[],!1,e);let r=(0,Ag.getSchemaTypes)(t.schema),n=(0,Ag.coerceAndCheckDataType)(t,r);Mg(t,r,!n,e)}function IE(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Wt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function OE(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Wt.checkStrictMode)(t,"default is ignored in the schema root")}function CE(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,$E.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function AE(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Hg({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,A._)`${q.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,A.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,A._)`${q.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function NE(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,A._)`${q.default.errors} === 0`,()=>e.return(q.default.data),()=>e.throw((0,A._)`new ${o}(${q.default.vErrors})`)):(e.assign((0,A._)`${n}.errors`,q.default.vErrors),s.unevaluated&&ME(t),e.return((0,A._)`${q.default.errors} === 0`))}function ME({gen:t,evaluated:e,props:r,items:n}){r instanceof A.Name&&t.assign((0,A._)`${e}.props`,r),n instanceof A.Name&&t.assign((0,A._)`${e}.items`,n)}function Mg(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Wt.schemaHasRulesButRef)(s,l))){o.block(()=>Bg(t,"$ref",l.all.$ref.definition));return}c.jtd||jE(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Wl.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Ti.checkDataType)(p.type,i,c.strictNumbers)),jg(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Ti.reportTypeError)(t)),o.endIf()):jg(t,p),a||o.if((0,A._)`${q.default.errors} === ${n||0}`))}}function jg(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,wE.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Wl.shouldUseRule)(n,s)&&Bg(t,s.keyword,s.definition,e.type)})}function jE(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(ZE(t,e),t.opts.allowUnionTypes||DE(t,e),qE(t,t.dataTypes))}function ZE(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Vg(t.dataTypes,r)||Kl(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),UE(t,e)}}function DE(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Kl(t,"use allowUnionTypes to allow union type keyword")}function qE(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Wl.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>LE(e,i))&&Kl(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function LE(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Vg(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function UE(t,e){let r=[];for(let n of t.dataTypes)Vg(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Kl(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Wt.checkStrictMode)(t,e,t.opts.strictTypes)}var zi=class{constructor(e,r,n){if((0,Uo.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Wt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Jg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Uo.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",q.default.errors))}result(e,r,n){this.failResult((0,A.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,A.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,A._)`${r} !== undefined && (${(0,A.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Lo.reportExtraError:Lo.reportError)(this,this.def.error,r)}$dataError(){(0,Lo.reportError)(this,this.def.$dataError||Lo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Lo.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=A.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=A.nil,r=A.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,A.or)((0,A._)`${o} === undefined`,r)),e!==A.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==A.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,A.or)(i(),a());function i(){if(n.length){if(!(r instanceof A.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,A._)`${(0,Ti.checkDataTypes)(c,r,s.opts.strictNumbers,Ti.DataType.Wrong)}`}return A.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,A._)`!${c}(${r})`}return A.nil}}subschema(e,r){let n=(0,Jl.getSubschema)(this.it,e);(0,Jl.extendSubschemaData)(n,this.it,e),(0,Jl.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return PE(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Wt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Wt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,A.Name)),!0}};pr.KeywordCxt=zi;function Bg(t,e,r,n){let o=new zi(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Uo.funcKeywordCode)(o,r):"macro"in r?(0,Uo.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Uo.funcKeywordCode)(o,r)}var FE=/^\/(?:[^~]|~0|~1)*$/,HE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Jg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return q.default.rootData;if(t[0]==="/"){if(!FE.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=q.default.rootData}else{let u=HE.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,A._)`${s}${(0,A.getProperty)((0,Wt.unescapeJsonPointer)(u))}`,i=(0,A._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}pr.getData=Jg});var Pi=T(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var Gl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Xl.default=Gl});var Ho=T(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var Yl=qo(),Ql=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Yl.resolveUrl)(e,r,n),this.missingSchema=(0,Yl.normalizeId)((0,Yl.getFullPath)(e,this.missingRef))}};ed.default=Ql});var Ii=T(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.resolveSchema=lt.getCompilingSchema=lt.resolveRef=lt.compileSchema=lt.SchemaEnv=void 0;var vt=B(),VE=Pi(),Yr=Jt(),xt=qo(),Wg=re(),BE=Fo(),jn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,xt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};lt.SchemaEnv=jn;function rd(t){let e=Kg.call(this,t);if(e)return e;let r=(0,xt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new vt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:VE.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Yr.default.data,parentData:Yr.default.parentData,parentDataProperty:Yr.default.parentDataProperty,dataNames:[Yr.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,vt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:vt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,BE.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Yr.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Yr.default.self}`,`${Yr.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:h}=u;m.evaluated={props:f instanceof vt.Name?void 0:f,items:h instanceof vt.Name?void 0:h,dynamicProps:f instanceof vt.Name,dynamicItems:h instanceof vt.Name},m.source&&(m.source.evaluated=(0,vt.stringify)(m.evaluated))}return t.validate=m,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}lt.compileSchema=rd;function JE(t,e,r){var n;r=(0,xt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=GE.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new jn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=WE.call(this,s)}lt.resolveRef=JE;function WE(t){return(0,xt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:rd.call(this,t)}function Kg(t){for(let e of this._compilations)if(KE(e,t))return e}lt.getCompilingSchema=Kg;function KE(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function GE(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ri.call(this,t,e)}function Ri(t,e){let r=this.opts.uriResolver.parse(e),n=(0,xt._getFullPath)(this.opts.uriResolver,r),o=(0,xt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return td.call(this,r,t);let s=(0,xt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ri.call(this,t,i);return typeof a?.schema!="object"?void 0:td.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||rd.call(this,i),s===(0,xt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,xt.resolveUrl)(this.opts.uriResolver,o,u)),new jn({schema:a,schemaId:c,root:t,baseId:o})}return td.call(this,r,i)}}lt.resolveSchema=Ri;var XE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function td(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Wg.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!XE.has(a)&&u&&(e=(0,xt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Wg.schemaHasRulesButRef)(r,this.RULES)){let a=(0,xt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ri.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new jn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Gg=T((kZ,YE)=>{YE.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}});var cd=T((SZ,ny)=>{"use strict";var QE=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),od=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),eT=RegExp.prototype.test.bind(/^\d*$/u),Qr=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),sd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Yg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),id=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),tT=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Ye=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Ye[e]="%"+t[e>>4]+t[e&15]}function De(t){return t<2048?Ye[192|t>>6]+Ye[128|t&63]:t<65536?Ye[224|t>>12]+Ye[128|t>>6&63]+Ye[128|t&63]:Ye[240|t>>18]+Ye[128|t>>12&63]+Ye[128|t>>6&63]+Ye[128|t&63]}function rT(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var nT=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),oT=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),sT=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),iT=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function aT(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!sT(t[e])){if(t[e]==="%"&&e+2<t.length&&Qr(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function Xg(t){let e=-1,r=0,n=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(n===-1&&(n=a),o++,o>r&&(r=o,e=n)):(n=-1,o=0);if(r<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+r).join(":");return s+"::"+i}function cT(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let r=e===-1?t.split(":"):t.slice(0,e).split(":"),n=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let o=r.concat(n),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&n.length===0||!od(c))return;s+=2;continue}if(!nT(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:Xg(o);if(s>=8)return;let i=o.slice(0,r.length);for(let a=s;a<8;a++)i.push("0");for(let a=r.length;a<o.length;a++)i.push(o[a]);return Xg(i)}function nd(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let n=e?t.slice(1,-1):t;if(e&&oT(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(uT(n,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=n.indexOf("%");if(s!==-1){let a=n.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=n.slice(s+a),!aT(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=cT(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function uT(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function lT(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var dT={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},fT=/[@/?#:]/g,pT=/[@/?#]/g;function Qg(t,e){let r=e?pT:fT;return r.lastIndex=0,t.replace(r,n=>dT[n])}function ey(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Qr(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&sd(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function mT(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(Qr(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&sd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Yg(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=ry(o)?n:Ye[o];else if(o<55296||o>57343)e+=De(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=De(65536+(o-55296<<10)+(s-56320)),r++):e+=De(65533)}else e+=De(65533)}}return e}function hT(t,e=!1){let r="",n=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(Qr(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),Yg(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=Ye[i];else if(i<55296||i>57343)r+=De(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=De(65536+(i-55296<<10)+(a-56320)),o++):r+=De(65533)}else r+=De(65533)}}return r}function ad(t,e){let r="";for(let n=0;n<t.length;n++){let o=t[n];if(o==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(Qr(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=Ye[s];else if(s<55296||s>57343)r+=De(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=De(65536+(s-55296<<10)+(i-56320)),n++):r+=De(65533)}else r+=De(65533)}}return r}function ty(t){return ad(t,tT)}function gT(t){return ad(t,id)}function yT(t){return ad(t,id)}function ry(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function _T(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(Qr(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));sd(i)?e+=i:e+="%"+s,r+=2;continue}}if(id(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=ry(o)?n:Ye[o];else if(o<55296||o>57343)e+=De(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=De(65536+(o-55296<<10)+(s-56320)),r++):e+=De(65533)}else e+=De(65533)}}return e}function vT(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Qr(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function xT(t){let e=[];if(t.userinfo!==void 0&&(e.push(ty(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!od(r)){let n=nd(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=ey(r,!0),n=nd(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=Qg(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!eT(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}ny.exports={nonSimpleDomain:iT,recomposeAuthority:xT,reescapeHostDelimiters:Qg,normalizePercentEncoding:ey,normalizePathEncoding:mT,serializePathEncoding:hT,normalizeQueryFragmentEncoding:_T,encodeUserinfo:ty,encodeQuery:gT,encodeFragment:yT,escapePreservingEscapes:vT,removeDotSegments:lT,isIPv4:od,isUUID:QE,normalizeIPv6:nd,stringArrayToHexStripped:rT}});var cy=T((EZ,ay)=>{"use strict";var{isUUID:bT}=cd(),wT=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,$T=["http","https","ws","wss","urn","urn:uuid"];function kT(t){return $T.indexOf(t)!==-1}function ud(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function oy(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function sy(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function ST(t){return t.secure=ud(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function ET(t){if((t.port===(ud(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function TT(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(wT);if(r&&r[0]===t.path){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=ld(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function zT(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=ld(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function PT(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!bT(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function RT(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var iy={scheme:"http",domainHost:!0,parse:oy,serialize:sy},IT={scheme:"https",domainHost:iy.domainHost,parse:oy,serialize:sy},Oi={scheme:"ws",domainHost:!0,parse:ST,serialize:ET},OT={scheme:"wss",domainHost:Oi.domainHost,parse:Oi.parse,serialize:Oi.serialize},CT={scheme:"urn",parse:TT,serialize:zT,skipNormalize:!0},AT={scheme:"urn:uuid",parse:PT,serialize:RT,skipNormalize:!0},Ci={http:iy,https:IT,ws:Oi,wss:OT,urn:CT,"urn:uuid":AT};Object.setPrototypeOf(Ci,null);function ld(t){return t&&(Ci[t]||Ci[t.toLowerCase()])||void 0}ay.exports={wsIsSecure:ud,SCHEMES:Ci,isValidSchemeName:kT,getSchemeHandler:ld}});var by=T((TZ,Mi)=>{"use strict";var{normalizeIPv6:py,removeDotSegments:Bo,recomposeAuthority:NT,normalizePercentEncoding:dd,normalizePathEncoding:MT,serializePathEncoding:uy,normalizeQueryFragmentEncoding:ly,encodeQuery:jT,encodeFragment:ZT,reescapeHostDelimiters:DT,isIPv4:my,nonSimpleDomain:qT}=cd(),{SCHEMES:hy,getSchemeHandler:fd}=cy(),gy=/^[A-Za-z][A-Za-z0-9+.-]*$/u,yy="URI scheme is malformed.";function dy(t){let e=unescape(String(t));if(!gy.test(e))throw new TypeError(yy);return e}function LT(t,e){return typeof t=="string"?t=KT(t,e):typeof t=="object"&&(t=Ni(en(t,e),e)),t}function UT(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=Ai(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:p,malformedSchemeSpecific:m,malformedHost:f,malformedScheme:h}=Ai(e,n);if(s||d||i||p||a||m||c||f||u||h)throw new Error(o.error||l.error||"URI is malformed.");let y=_y(o,l,n,!0),_=fd(r&&r.scheme||y.scheme),v=y.host,g=v!==void 0&&v!==""&&(my(v)||py(v).isIPV6);vy(y,r||{},_,g);let x=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(y.error&&!x)throw new Error(y.error);return n.skipEscape=!0,en(y,n)}function _y(t,e,r,n){let o={};return n||(t=Ni(en(t,r),r),e=Ni(en(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Bo(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Bo(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Bo(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Bo(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function FT(t,e,r){let n=fy(t,r),o=fy(e,r);return n!==void 0&&o!==void 0&&n===o}function en(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[];r.scheme&&(r.scheme=dy(r.scheme));let s=fd(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=!n.skipEscape&&r.scheme===void 0&&!i;r.path!==void 0&&(n.skipEscape?r.path=dd(r.path):r.path=uy(r.path,a)),n.reference!=="suffix"&&r.scheme&&(r.scheme=dy(r.scheme),o.push(r.scheme,":"));let c=NT(r);if(c!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(c),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(u=Bo(u)),a&&(u=uy(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return r.query!==void 0&&o.push("?",jT(r.query)),r.fragment!==void 0&&o.push("#",ZT(r.fragment)),o.join("")}var HT=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,VT=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,BT=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function JT(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Vo(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function pd(t){return t[0]==="["&&t[t.length-1]==="]"}function WT(t){let e=t[4];return Vo(t[3])||e!==void 0&&!pd(e)&&Vo(e)||Vo(t[6])||Vo(t[7])||Vo(t[8])}function vy(t,e,r,n){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!pd(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&qT(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(o){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+o,!0}return!1}function Ai(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,c=!1,u=!1,l=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let d=t.match(VT);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let p=t.match(BT);if(p!==null){let f=p[1],h=f.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let m=t.match(HT);if(m){if(n.scheme=m[1],n.userinfo=m[3],n.host=m[4],n.port=parseInt(m[5],10),n.path=m[6]||"",n.query=m[7],n.fragment=m[8],n.scheme!==void 0){let y=unescape(n.scheme);gy.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||yy,u=!0)}s=WT(m),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=m[5]);let f=JT(n,m);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(my(n.host)===!1){let _=pd(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,g=py(n.host);l=g.isIPV6||g.isIPVFuture===!0,c=v&&(!_||g.error===!0),n.host=l?g.host:g.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",o=!0)}else l=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let h=fd(r.scheme||n.scheme);if(c||(a=vy(n,r,h,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=l?n.host:dd(n.host,!0);l||(y=dd(y.toLowerCase())),n.host=DT(y,l)}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=MT(n.path)),n.query&&(n.query=ly(n.query)),n.fragment&&(n.fragment=ly(n.fragment))),h&&h.parse&&(h.parse(n,r),h===hy.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function Ni(t,e){return Ai(t,e).parsed}function KT(t,e){return xy(t,e).normalized}function xy(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Ai(t,e);return{normalized:n||o||s||i||a?t:en(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function fy(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:en(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=xy(r,e);return o||s||i||a||c?void 0:n}var md={SCHEMES:hy,normalize:LT,resolve:UT,resolveComponent:_y,equal:FT,serialize:en,parse:Ni};Mi.exports=md;Mi.exports.default=md;Mi.exports.fastUri=md});var $y=T(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var wy=by();wy.code='require("ajv/dist/runtime/uri").default';hd.default=wy});var Iy=T(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=void 0;var GT=Fo();Object.defineProperty(Ce,"KeywordCxt",{enumerable:!0,get:function(){return GT.KeywordCxt}});var Zn=B();Object.defineProperty(Ce,"_",{enumerable:!0,get:function(){return Zn._}});Object.defineProperty(Ce,"str",{enumerable:!0,get:function(){return Zn.str}});Object.defineProperty(Ce,"stringify",{enumerable:!0,get:function(){return Zn.stringify}});Object.defineProperty(Ce,"nil",{enumerable:!0,get:function(){return Zn.nil}});Object.defineProperty(Ce,"Name",{enumerable:!0,get:function(){return Zn.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:!0,get:function(){return Zn.CodeGen}});var XT=Pi(),zy=Ho(),YT=jl(),Jo=Ii(),QT=B(),Wo=qo(),ji=Do(),yd=re(),ky=Gg(),ez=$y(),Py=(t,e)=>new RegExp(t,e);Py.code="new RegExp";var tz=["removeAdditional","useDefaults","coerceTypes"],rz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),nz={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."},oz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Sy=200;function sz(t){var e,r,n,o,s,i,a,c,u,l,d,p,m,f,h,y,_,v,g,x,$,D,R,ie,ae;let Te=t.strict,L=(e=t.code)===null||e===void 0?void 0:e.optimize,_e=L===!0||L===void 0?1:L||0,$t=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Py,xr=(o=t.uriResolver)!==null&&o!==void 0?o:ez.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Te)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Te)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Te)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:Te)!==null&&p!==void 0?p:"log",strictRequired:(f=(m=t.strictRequired)!==null&&m!==void 0?m:Te)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:_e,regExp:$t}:{optimize:_e,regExp:$t},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Sy,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Sy,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(g=t.inlineRefs)!==null&&g!==void 0?g:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(D=t.validateSchema)!==null&&D!==void 0?D:!0,validateFormats:(R=t.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(ie=t.unicodeRegExp)!==null&&ie!==void 0?ie:!0,int32range:(ae=t.int32range)!==null&&ae!==void 0?ae:!0,uriResolver:xr}}var Ko=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...sz(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new QT.ValueScope({scope:{},prefixes:rz,es5:r,lines:n}),this.logger=dz(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,YT.getRules)(),Ey.call(this,nz,e,"NOT SUPPORTED"),Ey.call(this,oz,e,"DEPRECATED","warn"),this._metaOpts=uz.call(this),e.formats&&az.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&cz.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),iz.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=ky;n==="id"&&(o={...ky},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof zy.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Wo.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Ty.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Jo.SchemaEnv({schema:{},schemaId:n});if(r=Jo.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Ty.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Wo.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(pz.call(this,n,r),!r)return(0,yd.eachItem)(n,s=>gd.call(this,s)),this;hz.call(this,r);let o={...r,type:(0,ji.getJSONTypes)(r.type),schemaType:(0,ji.getJSONTypes)(r.schemaType)};return(0,yd.eachItem)(n,o.type.length===0?s=>gd.call(this,s,o):s=>o.type.forEach(i=>gd.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=Ry(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Wo.normalizeId)(i||n);let u=Wo.getSchemaRefs.call(this,e,n);return c=new Jo.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Jo.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Jo.compileSchema.call(this,e)}finally{this.opts=r}}};Ko.ValidationError=XT.default;Ko.MissingRefError=zy.default;Ce.default=Ko;function Ey(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Ty(t){return t=(0,Wo.normalizeId)(t),this.schemas[t]||this.refs[t]}function iz(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function az(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function cz(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function uz(){let t={...this.opts};for(let e of tz)delete t[e];return t}var lz={log(){},warn(){},error(){}};function dz(t){if(t===!1)return lz;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var fz=/^[a-z_$][a-z0-9_$:-]*$/i;function pz(t,e){let{RULES:r}=this;if((0,yd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!fz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function gd(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ji.getJSONTypes)(e.type),schemaType:(0,ji.getJSONTypes)(e.schemaType)}};e.before?mz.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function mz(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function hz(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Ry(e)),t.validateSchema=this.compile(e,!0))}var gz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ry(t){return{anyOf:[t,gz]}}});var Oy=T(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var yz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};_d.default=yz});var My=T(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.callRef=tn.getValidate=void 0;var _z=Ho(),Cy=ut(),Qe=B(),Dn=Jt(),Ay=Ii(),Zi=re(),vz={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=Ay.resolveRef.call(c,u,o,r);if(l===void 0)throw new _z.default(n.opts.uriResolver,o,r);if(l instanceof Ay.SchemaEnv)return p(l);return m(l);function d(){if(s===u)return Di(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return Di(t,(0,Qe._)`${f}.validate`,u,u.$async)}function p(f){let h=Ny(t,f);Di(t,h,f,f.$async)}function m(f){let h=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Qe.stringify)(f)}:{ref:f}),y=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:Qe.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(_),t.ok(y)}}};function Ny(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Qe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}tn.getValidate=Ny;function Di(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Dn.default.this:Qe.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,Qe._)`await ${(0,Cy.callValidateCode)(t,e,u)}`),m(e),i||o.assign(f,!0)},h=>{o.if((0,Qe._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,Cy.callValidateCode)(t,e,u),()=>m(e),()=>p(e))}function p(f){let h=(0,Qe._)`${f}.errors`;o.assign(Dn.default.vErrors,(0,Qe._)`${Dn.default.vErrors} === null ? ${h} : ${Dn.default.vErrors}.concat(${h})`),o.assign(Dn.default.errors,(0,Qe._)`${Dn.default.vErrors}.length`)}function m(f){var h;if(!s.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Zi.mergeEvaluated.props(o,y.props,s.props));else{let _=o.var("props",(0,Qe._)`${f}.evaluated.props`);s.props=Zi.mergeEvaluated.props(o,_,s.props,Qe.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Zi.mergeEvaluated.items(o,y.items,s.items));else{let _=o.var("items",(0,Qe._)`${f}.evaluated.items`);s.items=Zi.mergeEvaluated.items(o,_,s.items,Qe.Name)}}}tn.callRef=Di;tn.default=vz});var jy=T(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var xz=Oy(),bz=My(),wz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",xz.default,bz.default];vd.default=wz});var Zy=T(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var qi=B(),mr=qi.operators,Li={maximum:{okStr:"<=",ok:mr.LTE,fail:mr.GT},minimum:{okStr:">=",ok:mr.GTE,fail:mr.LT},exclusiveMaximum:{okStr:"<",ok:mr.LT,fail:mr.GTE},exclusiveMinimum:{okStr:">",ok:mr.GT,fail:mr.LTE}},$z={message:({keyword:t,schemaCode:e})=>(0,qi.str)`must be ${Li[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qi._)`{comparison: ${Li[t].okStr}, limit: ${e}}`},kz={keyword:Object.keys(Li),type:"number",schemaType:"number",$data:!0,error:$z,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,qi._)`${r} ${Li[e].fail} ${n} || isNaN(${r})`)}};xd.default=kz});var Dy=T(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Go=B(),Sz={message:({schemaCode:t})=>(0,Go.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Go._)`{multipleOf: ${t}}`},Ez={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Sz,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Go._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Go._)`${i} !== parseInt(${i})`;t.fail$data((0,Go._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};bd.default=Ez});var Ly=T(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});function qy(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}wd.default=qy;qy.code='require("ajv/dist/runtime/ucs2length").default'});var Uy=T($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var rn=B(),Tz=re(),zz=Ly(),Pz={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,rn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,rn._)`{limit: ${t}}`},Rz={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Pz,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?rn.operators.GT:rn.operators.LT,i=o.opts.unicode===!1?(0,rn._)`${r}.length`:(0,rn._)`${(0,Tz.useFunc)(t.gen,zz.default)}(${r})`;t.fail$data((0,rn._)`${i} ${s} ${n}`)}};$d.default=Rz});var Fy=T(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var Iz=ut(),Oz=re(),qn=B(),Cz={message:({schemaCode:t})=>(0,qn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,qn._)`{pattern: ${t}}`},Az={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Cz,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,qn._)`new RegExp`:(0,Oz.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,qn._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,qn._)`!${l}`)}else{let c=(0,Iz.usePattern)(t,o);t.fail$data((0,qn._)`!${c}.test(${r})`)}}};kd.default=Az});var Hy=T(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Xo=B(),Nz={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Xo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Xo._)`{limit: ${t}}`},Mz={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Nz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Xo.operators.GT:Xo.operators.LT;t.fail$data((0,Xo._)`Object.keys(${r}).length ${o} ${n}`)}};Sd.default=Mz});var Vy=T(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var Yo=ut(),Qo=B(),jz=re(),Zz={message:({params:{missingProperty:t}})=>(0,Qo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Qo._)`{missingProperty: ${t}}`},Dz={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Zz,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:f}=t.it;for(let h of r)if(m?.[h]===void 0&&!f.has(h)){let y=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,jz.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Qo.nil,d);else for(let m of r)(0,Yo.checkReportMissingProp)(t,m)}function l(){let m=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>p(m,f)),t.ok(f)}else e.if((0,Yo.checkMissingProp)(t,r,m)),(0,Yo.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,Yo.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function p(m,f){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(f,(0,Yo.propertyInData)(e,o,m,a.ownProperties)),e.if((0,Qo.not)(f),()=>{t.error(),e.break()})},Qo.nil)}}};Ed.default=Dz});var By=T(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var es=B(),qz={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,es.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,es._)`{limit: ${t}}`},Lz={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:qz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?es.operators.GT:es.operators.LT;t.fail$data((0,es._)`${r}.length ${o} ${n}`)}};Td.default=Lz});var Ui=T(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var Jy=Vl();Jy.code='require("ajv/dist/runtime/equal").default';zd.default=Jy});var Wy=T(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var Pd=Do(),Ae=B(),Uz=re(),Fz=Ui(),Hz={message:({params:{i:t,j:e}})=>(0,Ae.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ae._)`{i: ${t}, j: ${e}}`},Vz={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Hz,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Pd.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ae._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Ae._)`${r}.length`),h=e.let("j");t.setParams({i:f,j:h}),e.assign(c,!0),e.if((0,Ae._)`${f} > 1`,()=>(d()?p:m)(f,h))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function p(f,h){let y=e.name("item"),_=(0,Pd.checkDataTypes)(u,y,a.opts.strictNumbers,Pd.DataType.Wrong),v=e.const("indices",(0,Ae._)`{}`);e.for((0,Ae._)`;${f}--;`,()=>{e.let(y,(0,Ae._)`${r}[${f}]`),e.if(_,(0,Ae._)`continue`),u.length>1&&e.if((0,Ae._)`typeof ${y} == "string"`,(0,Ae._)`${y} += "_"`),e.if((0,Ae._)`typeof ${v}[${y}] == "number"`,()=>{e.assign(h,(0,Ae._)`${v}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ae._)`${v}[${y}] = ${f}`)})}function m(f,h){let y=(0,Uz.useFunc)(e,Fz.default),_=e.name("outer");e.label(_).for((0,Ae._)`;${f}--;`,()=>e.for((0,Ae._)`${h} = ${f}; ${h}--;`,()=>e.if((0,Ae._)`${y}(${r}[${f}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};Rd.default=Vz});var Ky=T(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var Id=B(),Bz=re(),Jz=Ui(),Wz={message:"must be equal to constant",params:({schemaCode:t})=>(0,Id._)`{allowedValue: ${t}}`},Kz={keyword:"const",$data:!0,error:Wz,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Id._)`!${(0,Bz.useFunc)(e,Jz.default)}(${r}, ${o})`):t.fail((0,Id._)`${s} !== ${r}`)}};Od.default=Kz});var Gy=T(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var ts=B(),Gz=re(),Xz=Ui(),Yz={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ts._)`{allowedValues: ${t}}`},Qz={keyword:"enum",schemaType:"array",$data:!0,error:Yz,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,Gz.useFunc)(e,Xz.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);l=(0,ts.or)(...o.map((f,h)=>p(m,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,m=>e.if((0,ts._)`${u()}(${r}, ${m})`,()=>e.assign(l,!0).break()))}function p(m,f){let h=o[f];return typeof h=="object"&&h!==null?(0,ts._)`${u()}(${r}, ${m}[${f}])`:(0,ts._)`${r} === ${h}`}}};Cd.default=Qz});var Xy=T(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var eP=Zy(),tP=Dy(),rP=Uy(),nP=Fy(),oP=Hy(),sP=Vy(),iP=By(),aP=Wy(),cP=Ky(),uP=Gy(),lP=[eP.default,tP.default,rP.default,nP.default,oP.default,sP.default,iP.default,aP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},cP.default,uP.default];Ad.default=lP});var Md=T(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.validateAdditionalItems=void 0;var nn=B(),Nd=re(),dP={message:({params:{len:t}})=>(0,nn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,nn._)`{limit: ${t}}`},fP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:dP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Nd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Yy(t,n)}};function Yy(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,nn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,nn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Nd.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,nn._)`${a} <= ${e.length}`);r.if((0,nn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Nd.Type.Num},u),i.allErrors||r.if((0,nn.not)(u),()=>r.break())})}}rs.validateAdditionalItems=Yy;rs.default=fP});var jd=T(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.validateTuple=void 0;var Qy=B(),Fi=re(),pP=ut(),mP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return e_(t,"additionalItems",e);r.items=!0,!(0,Fi.alwaysValidSchema)(r,e)&&t.ok((0,pP.validateArray)(t))}};function e_(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Fi.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Qy._)`${s}.length`);r.forEach((d,p)=>{(0,Fi.alwaysValidSchema)(a,d)||(n.if((0,Qy._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:m}=a,f=r.length,h=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let y=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Fi.checkStrictMode)(a,y,p.strictTuples)}}}ns.validateTuple=e_;ns.default=mP});var t_=T(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});var hP=jd(),gP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,hP.validateTuple)(t,"items")};Zd.default=gP});var n_=T(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var r_=B(),yP=re(),_P=ut(),vP=Md(),xP={message:({params:{len:t}})=>(0,r_.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,r_._)`{limit: ${t}}`},bP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:xP,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,yP.alwaysValidSchema)(n,e)&&(o?(0,vP.validateAdditionalItems)(t,o):t.ok((0,_P.validateArray)(t)))}};Dd.default=bP});var o_=T(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var dt=B(),Hi=re(),wP={message:({params:{min:t,max:e}})=>e===void 0?(0,dt.str)`must contain at least ${t} valid item(s)`:(0,dt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dt._)`{minContains: ${t}}`:(0,dt._)`{minContains: ${t}, maxContains: ${e}}`},$P={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:wP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,dt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Hi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Hi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Hi.alwaysValidSchema)(s,r)){let h=(0,dt._)`${l} >= ${i}`;a!==void 0&&(h=(0,dt._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,dt._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),y=e.let("count",0);m(h,()=>e.if(h,()=>f(y)))}function m(h,y){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:Hi.Type.Num,compositeRule:!0},h),y()})}function f(h){e.code((0,dt._)`${h}++`),a===void 0?e.if((0,dt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,dt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,dt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};qd.default=$P});var a_=T(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.validateSchemaDeps=Ot.validatePropertyDeps=Ot.error=void 0;var Ld=B(),kP=re(),os=ut();Ot.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Ld.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Ld._)`{property: ${t},
34
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,F._)`[${o}]`)}}}function qS({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,F._)`${e} !== undefined`,()=>t.assign((0,F._)`${e}[${r}]`,n))}function ql(t,e,r,n=An.Correct){let o=n===An.Correct?F.operators.EQ:F.operators.NEQ,s;switch(t){case"null":return(0,F._)`${e} ${o} null`;case"array":s=(0,F._)`Array.isArray(${e})`;break;case"object":s=(0,F._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,F._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,F._)`typeof ${e} ${o} ${t}`}return n===An.Correct?s:(0,F.not)(s);function i(a=F.nil){return(0,F.and)((0,F._)`typeof ${e} == "number"`,a,r?(0,F._)`isFinite(${e})`:F.nil)}}De.checkDataType=ql;function Ll(t,e,r,n){if(t.length===1)return ql(t[0],e,r,n);let o,s=(0,yg.toHash)(t);if(s.array&&s.object){let i=(0,F._)`typeof ${e} != "object"`;o=s.null?i:(0,F._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=F.nil;s.number&&delete s.integer;for(let i in s)o=(0,F.and)(o,ql(i,e,r,n));return o}De.checkDataTypes=Ll;var LS={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,F._)`{type: ${t}}`:(0,F._)`{type: ${e}}`};function Ul(t){let e=US(t);(0,NS.reportError)(e,LS)}De.reportTypeError=Ul;function US(t){let{gen:e,data:r,schema:n}=t,o=(0,yg.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var bg=T(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.assignDefaults=void 0;var Nn=B(),FS=re();function HS(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)xg(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>xg(t,s,o.default))}Si.assignDefaults=HS;function xg(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Nn._)`${s}${(0,Nn.getProperty)(e)}`;if(o){(0,FS.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Nn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Nn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Nn._)`${a} = ${(0,Nn.stringify)(r)}`)}});var ut=T(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var ge=B(),Fl=re(),lr=Jt(),VS=re();function BS(t,e){let{gen:r,data:n,it:o}=t;r.if(Vl(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}le.checkReportMissingProp=BS;function JS({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(Vl(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}le.checkMissingProp=JS;function WS(t,e){t.setParams({missingProperty:e},!0),t.error()}le.reportMissingProp=WS;function wg(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=wg;function Hl(t,e,r){return(0,ge._)`${wg(t)}.call(${e}, ${r})`}le.isOwnProperty=Hl;function KS(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${Hl(t,e,r)}`:o}le.propertyInData=KS;function Vl(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(Hl(t,e,r))):o}le.noPropertyInData=Vl;function $g(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=$g;function GS(t,e){return $g(e).filter(r=>!(0,Fl.alwaysValidSchema)(t,e[r]))}le.schemaProperties=GS;function XS({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[lr.default.instancePath,(0,ge.strConcat)(lr.default.instancePath,s)],[lr.default.parentData,i.parentData],[lr.default.parentDataProperty,i.parentDataProperty],[lr.default.rootData,lr.default.rootData]];i.opts.dynamicRef&&d.push([lr.default.dynamicAnchors,lr.default.dynamicAnchors]);let p=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}le.callValidateCode=XS;var YS=(0,ge._)`new RegExp`;function QS({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?YS:(0,VS.useFunc)(t,o)}(${r}, ${n})`})}le.usePattern=QS;function eE(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Fl.Type.Num},s),e.if((0,ge.not)(s),a)})}}le.validateArray=eE;function tE(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Fl.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}le.validateUnion=tE});var Eg=T(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.validateKeywordUsage=Rt.validSchemaType=Rt.funcKeywordCode=Rt.macroKeywordCode=void 0;var Ve=B(),Xr=Jt(),rE=ut(),nE=Zo();function oE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Sg(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Rt.macroKeywordCode=oE;function sE(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;aE(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Sg(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)h(),e.modifying&&kg(t),y(()=>t.error());else{let _=e.async?m():f();e.modifying&&kg(t),y(()=>iE(t,_))}}function m(){let _=n.let("ruleErrs",null);return n.try(()=>h((0,Ve._)`await `),v=>n.assign(d,!1).if((0,Ve._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,Ve._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,Ve._)`${l}.errors`;return n.assign(_,null),h(Ve.nil),_}function h(_=e.async?(0,Ve._)`await `:Ve.nil){let v=c.opts.passContext?Xr.default.this:Xr.default.self,g=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ve._)`${_}${(0,rE.callValidateCode)(t,l,v,g)}`,e.modifying)}function y(_){var v;n.if((0,Ve.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}Rt.funcKeywordCode=sE;function kg(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function iE(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(Xr.default.vErrors,(0,Ve._)`${Xr.default.vErrors} === null ? ${e} : ${Xr.default.vErrors}.concat(${e})`).assign(Xr.default.errors,(0,Ve._)`${Xr.default.vErrors}.length`),(0,nE.extendErrors)(t)},()=>t.error())}function aE({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Sg(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ve.stringify)(r)})}function cE(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Rt.validSchemaType=cE;function uE({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Rt.validateKeywordUsage=uE});var zg=T(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.extendSubschemaMode=dr.extendSubschemaData=dr.getSubschema=void 0;var It=B(),Tg=re();function lE(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,It._)`${t.schemaPath}${(0,It.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,It._)`${t.schemaPath}${(0,It.getProperty)(e)}${(0,It.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Tg.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}dr.getSubschema=lE;function dE(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,It._)`${e.data}${(0,It.getProperty)(r)}`,!0);c(p),t.errorPath=(0,It.str)`${u}${(0,Tg.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,It._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof It.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}dr.extendSubschemaData=dE;function fE(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}dr.extendSubschemaMode=fE});var Bl=T((_Z,Pg)=>{"use strict";Pg.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Ig=T((vZ,Rg)=>{"use strict";var fr=Rg.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Ei(e,n,o,t,"",t)};fr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};fr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};fr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};fr.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 Ei(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in fr.arrayKeywords)for(var p=0;p<d.length;p++)Ei(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in fr.propsKeywords){if(d&&typeof d=="object")for(var m in d)Ei(t,e,r,d[m],o+"/"+l+"/"+pE(m),s,o,l,n,m)}else(l in fr.keywords||t.allKeys&&!(l in fr.skipKeywords))&&Ei(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function pE(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var qo=T(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.getSchemaRefs=Ye.resolveUrl=Ye.normalizeId=Ye._getFullPath=Ye.getFullPath=Ye.inlineRef=void 0;var mE=re(),hE=Bl(),gE=Ig(),yE=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function _E(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Jl(t):e?Og(t)<=e:!1}Ye.inlineRef=_E;var vE=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Jl(t){for(let e in t){if(vE.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Jl)||typeof r=="object"&&Jl(r))return!0}return!1}function Og(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!yE.has(r)&&(typeof t[r]=="object"&&(0,mE.eachItem)(t[r],n=>e+=Og(n)),e===1/0))return 1/0}return e}function Cg(t,e="",r){r!==!1&&(e=Mn(e));let n=t.parse(e);return Ag(t,n)}Ye.getFullPath=Cg;function Ag(t,e){return t.serialize(e).split("#")[0]+"#"}Ye._getFullPath=Ag;var xE=/#\/?$/;function Mn(t){return t?t.replace(xE,""):""}Ye.normalizeId=Mn;function bE(t,e,r){return r=Mn(r),t.resolve(e,r)}Ye.resolveUrl=bE;var wE=/^[a-z_][-a-z0-9._]*$/i;function $E(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Mn(t[r]||e),s={"":o},i=Cg(n,o,!1),a={},c=new Set;return gE(t,{allKeys:!0},(d,p,m,f)=>{if(f===void 0)return;let h=i+p,y=s[f];typeof d[r]=="string"&&(y=_.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[p]=y;function _(g){let x=this.opts.uriResolver.resolve;if(g=Mn(y?x(y,g):g),c.has(g))throw l(g);c.add(g);let $=this.refs[g];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,g):g!==Mn(h)&&(g[0]==="#"?(u(d,a[g],g),a[g]=d):this.refs[g]=h),g}function v(g){if(typeof g=="string"){if(!wE.test(g))throw new Error(`invalid anchor "${g}"`);_.call(this,`#${g}`)}}}),a;function u(d,p,m){if(p!==void 0&&!hE(d,p))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ye.getSchemaRefs=$E});var Fo=T(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.getData=pr.KeywordCxt=pr.validateFunctionCode=void 0;var Dg=mg(),Ng=Do(),Kl=Dl(),Ti=Do(),kE=bg(),Uo=Eg(),Wl=zg(),A=B(),q=Jt(),SE=qo(),Wt=re(),Lo=Zo();function EE(t){if(Ug(t)&&(Fg(t),Lg(t))){PE(t);return}qg(t,()=>(0,Dg.topBoolOrEmptySchema)(t))}pr.validateFunctionCode=EE;function qg({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,A._)`${q.default.data}, ${q.default.valCxt}`,n.$async,()=>{t.code((0,A._)`"use strict"; ${Mg(r,o)}`),zE(t,o),t.code(s)}):t.func(e,(0,A._)`${q.default.data}, ${TE(o)}`,n.$async,()=>t.code(Mg(r,o)).code(s))}function TE(t){return(0,A._)`{${q.default.instancePath}="", ${q.default.parentData}, ${q.default.parentDataProperty}, ${q.default.rootData}=${q.default.data}${t.dynamicRef?(0,A._)`, ${q.default.dynamicAnchors}={}`:A.nil}}={}`}function zE(t,e){t.if(q.default.valCxt,()=>{t.var(q.default.instancePath,(0,A._)`${q.default.valCxt}.${q.default.instancePath}`),t.var(q.default.parentData,(0,A._)`${q.default.valCxt}.${q.default.parentData}`),t.var(q.default.parentDataProperty,(0,A._)`${q.default.valCxt}.${q.default.parentDataProperty}`),t.var(q.default.rootData,(0,A._)`${q.default.valCxt}.${q.default.rootData}`),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,A._)`${q.default.valCxt}.${q.default.dynamicAnchors}`)},()=>{t.var(q.default.instancePath,(0,A._)`""`),t.var(q.default.parentData,(0,A._)`undefined`),t.var(q.default.parentDataProperty,(0,A._)`undefined`),t.var(q.default.rootData,q.default.data),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,A._)`{}`)})}function PE(t){let{schema:e,opts:r,gen:n}=t;qg(t,()=>{r.$comment&&e.$comment&&Vg(t),AE(t),n.let(q.default.vErrors,null),n.let(q.default.errors,0),r.unevaluated&&RE(t),Hg(t),jE(t)})}function RE(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,A._)`${r}.evaluated`),e.if((0,A._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,A._)`${t.evaluated}.props`,(0,A._)`undefined`)),e.if((0,A._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,A._)`${t.evaluated}.items`,(0,A._)`undefined`))}function Mg(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,A._)`/*# sourceURL=${r} */`:A.nil}function IE(t,e){if(Ug(t)&&(Fg(t),Lg(t))){OE(t,e);return}(0,Dg.boolOrEmptySchema)(t,e)}function Lg({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Ug(t){return typeof t.schema!="boolean"}function OE(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Vg(t),NE(t),ME(t);let s=n.const("_errs",q.default.errors);Hg(t,s),n.var(e,(0,A._)`${s} === ${q.default.errors}`)}function Fg(t){(0,Wt.checkUnknownRules)(t),CE(t)}function Hg(t,e){if(t.opts.jtd)return jg(t,[],!1,e);let r=(0,Ng.getSchemaTypes)(t.schema),n=(0,Ng.coerceAndCheckDataType)(t,r);jg(t,r,!n,e)}function CE(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Wt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function AE(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Wt.checkStrictMode)(t,"default is ignored in the schema root")}function NE(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,SE.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function ME(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Vg({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,A._)`${q.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,A.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,A._)`${q.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function jE(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,A._)`${q.default.errors} === 0`,()=>e.return(q.default.data),()=>e.throw((0,A._)`new ${o}(${q.default.vErrors})`)):(e.assign((0,A._)`${n}.errors`,q.default.vErrors),s.unevaluated&&ZE(t),e.return((0,A._)`${q.default.errors} === 0`))}function ZE({gen:t,evaluated:e,props:r,items:n}){r instanceof A.Name&&t.assign((0,A._)`${e}.props`,r),n instanceof A.Name&&t.assign((0,A._)`${e}.items`,n)}function jg(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Wt.schemaHasRulesButRef)(s,l))){o.block(()=>Jg(t,"$ref",l.all.$ref.definition));return}c.jtd||DE(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Kl.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Ti.checkDataType)(p.type,i,c.strictNumbers)),Zg(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Ti.reportTypeError)(t)),o.endIf()):Zg(t,p),a||o.if((0,A._)`${q.default.errors} === ${n||0}`))}}function Zg(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,kE.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Kl.shouldUseRule)(n,s)&&Jg(t,s.keyword,s.definition,e.type)})}function DE(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(qE(t,e),t.opts.allowUnionTypes||LE(t,e),UE(t,t.dataTypes))}function qE(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Bg(t.dataTypes,r)||Gl(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),HE(t,e)}}function LE(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Gl(t,"use allowUnionTypes to allow union type keyword")}function UE(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Kl.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>FE(e,i))&&Gl(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function FE(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Bg(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function HE(t,e){let r=[];for(let n of t.dataTypes)Bg(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Gl(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Wt.checkStrictMode)(t,e,t.opts.strictTypes)}var zi=class{constructor(e,r,n){if((0,Uo.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Wt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Wg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Uo.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",q.default.errors))}result(e,r,n){this.failResult((0,A.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,A.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,A._)`${r} !== undefined && (${(0,A.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Lo.reportExtraError:Lo.reportError)(this,this.def.error,r)}$dataError(){(0,Lo.reportError)(this,this.def.$dataError||Lo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Lo.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=A.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=A.nil,r=A.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,A.or)((0,A._)`${o} === undefined`,r)),e!==A.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==A.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,A.or)(i(),a());function i(){if(n.length){if(!(r instanceof A.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,A._)`${(0,Ti.checkDataTypes)(c,r,s.opts.strictNumbers,Ti.DataType.Wrong)}`}return A.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,A._)`!${c}(${r})`}return A.nil}}subschema(e,r){let n=(0,Wl.getSubschema)(this.it,e);(0,Wl.extendSubschemaData)(n,this.it,e),(0,Wl.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return IE(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Wt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Wt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,A.Name)),!0}};pr.KeywordCxt=zi;function Jg(t,e,r,n){let o=new zi(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Uo.funcKeywordCode)(o,r):"macro"in r?(0,Uo.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Uo.funcKeywordCode)(o,r)}var VE=/^\/(?:[^~]|~0|~1)*$/,BE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Wg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return q.default.rootData;if(t[0]==="/"){if(!VE.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=q.default.rootData}else{let u=BE.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,A._)`${s}${(0,A.getProperty)((0,Wt.unescapeJsonPointer)(u))}`,i=(0,A._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}pr.getData=Wg});var Pi=T(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var Xl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Yl.default=Xl});var Ho=T(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var Ql=qo(),ed=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ql.resolveUrl)(e,r,n),this.missingSchema=(0,Ql.normalizeId)((0,Ql.getFullPath)(e,this.missingRef))}};td.default=ed});var Ii=T(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.resolveSchema=lt.getCompilingSchema=lt.resolveRef=lt.compileSchema=lt.SchemaEnv=void 0;var vt=B(),JE=Pi(),Yr=Jt(),xt=qo(),Kg=re(),WE=Fo(),jn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,xt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};lt.SchemaEnv=jn;function nd(t){let e=Gg.call(this,t);if(e)return e;let r=(0,xt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new vt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:JE.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Yr.default.data,parentData:Yr.default.parentData,parentDataProperty:Yr.default.parentDataProperty,dataNames:[Yr.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,vt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:vt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,WE.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Yr.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Yr.default.self}`,`${Yr.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:h}=u;m.evaluated={props:f instanceof vt.Name?void 0:f,items:h instanceof vt.Name?void 0:h,dynamicProps:f instanceof vt.Name,dynamicItems:h instanceof vt.Name},m.source&&(m.source.evaluated=(0,vt.stringify)(m.evaluated))}return t.validate=m,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}lt.compileSchema=nd;function KE(t,e,r){var n;r=(0,xt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=YE.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new jn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=GE.call(this,s)}lt.resolveRef=KE;function GE(t){return(0,xt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:nd.call(this,t)}function Gg(t){for(let e of this._compilations)if(XE(e,t))return e}lt.getCompilingSchema=Gg;function XE(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function YE(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ri.call(this,t,e)}function Ri(t,e){let r=this.opts.uriResolver.parse(e),n=(0,xt._getFullPath)(this.opts.uriResolver,r),o=(0,xt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return rd.call(this,r,t);let s=(0,xt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ri.call(this,t,i);return typeof a?.schema!="object"?void 0:rd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||nd.call(this,i),s===(0,xt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,xt.resolveUrl)(this.opts.uriResolver,o,u)),new jn({schema:a,schemaId:c,root:t,baseId:o})}return rd.call(this,r,i)}}lt.resolveSchema=Ri;var QE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function rd(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Kg.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!QE.has(a)&&u&&(e=(0,xt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Kg.schemaHasRulesButRef)(r,this.RULES)){let a=(0,xt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ri.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new jn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Xg=T((SZ,eT)=>{eT.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}});var ud=T((EZ,oy)=>{"use strict";var tT=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),sd=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),rT=RegExp.prototype.test.bind(/^\d*$/u),Qr=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),id=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Qg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),ad=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),nT=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Qe=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Qe[e]="%"+t[e>>4]+t[e&15]}function qe(t){return t<2048?Qe[192|t>>6]+Qe[128|t&63]:t<65536?Qe[224|t>>12]+Qe[128|t>>6&63]+Qe[128|t&63]:Qe[240|t>>18]+Qe[128|t>>12&63]+Qe[128|t>>6&63]+Qe[128|t&63]}function oT(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var sT=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),iT=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),aT=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),cT=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function uT(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!aT(t[e])){if(t[e]==="%"&&e+2<t.length&&Qr(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function Yg(t){let e=-1,r=0,n=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(n===-1&&(n=a),o++,o>r&&(r=o,e=n)):(n=-1,o=0);if(r<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+r).join(":");return s+"::"+i}function lT(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let r=e===-1?t.split(":"):t.slice(0,e).split(":"),n=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let o=r.concat(n),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&n.length===0||!sd(c))return;s+=2;continue}if(!sT(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:Yg(o);if(s>=8)return;let i=o.slice(0,r.length);for(let a=s;a<8;a++)i.push("0");for(let a=r.length;a<o.length;a++)i.push(o[a]);return Yg(i)}function od(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let n=e?t.slice(1,-1):t;if(e&&iT(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(dT(n,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=n.indexOf("%");if(s!==-1){let a=n.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=n.slice(s+a),!uT(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=lT(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function dT(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function fT(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var pT={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},mT=/[@/?#:]/g,hT=/[@/?#]/g;function ey(t,e){let r=e?hT:mT;return r.lastIndex=0,t.replace(r,n=>pT[n])}function ty(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Qr(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&id(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function gT(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(Qr(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&id(i)?e+=i:e+="%"+s,r+=2;continue}}if(Qg(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=ny(o)?n:Qe[o];else if(o<55296||o>57343)e+=qe(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=qe(65536+(o-55296<<10)+(s-56320)),r++):e+=qe(65533)}else e+=qe(65533)}}return e}function yT(t,e=!1){let r="",n=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(Qr(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),Qg(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=Qe[i];else if(i<55296||i>57343)r+=qe(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=qe(65536+(i-55296<<10)+(a-56320)),o++):r+=qe(65533)}else r+=qe(65533)}}return r}function cd(t,e){let r="";for(let n=0;n<t.length;n++){let o=t[n];if(o==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(Qr(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=Qe[s];else if(s<55296||s>57343)r+=qe(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=qe(65536+(s-55296<<10)+(i-56320)),n++):r+=qe(65533)}else r+=qe(65533)}}return r}function ry(t){return cd(t,nT)}function _T(t){return cd(t,ad)}function vT(t){return cd(t,ad)}function ny(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function xT(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(Qr(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));id(i)?e+=i:e+="%"+s,r+=2;continue}}if(ad(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=ny(o)?n:Qe[o];else if(o<55296||o>57343)e+=qe(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=qe(65536+(o-55296<<10)+(s-56320)),r++):e+=qe(65533)}else e+=qe(65533)}}return e}function bT(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Qr(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function wT(t){let e=[];if(t.userinfo!==void 0&&(e.push(ry(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!sd(r)){let n=od(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=ty(r,!0),n=od(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=ey(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!rT(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}oy.exports={nonSimpleDomain:cT,recomposeAuthority:wT,reescapeHostDelimiters:ey,normalizePercentEncoding:ty,normalizePathEncoding:gT,serializePathEncoding:yT,normalizeQueryFragmentEncoding:xT,encodeUserinfo:ry,encodeQuery:_T,encodeFragment:vT,escapePreservingEscapes:bT,removeDotSegments:fT,isIPv4:sd,isUUID:tT,normalizeIPv6:od,stringArrayToHexStripped:oT}});var uy=T((TZ,cy)=>{"use strict";var{isUUID:$T}=ud(),kT=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,ST=["http","https","ws","wss","urn","urn:uuid"];function ET(t){return ST.indexOf(t)!==-1}function ld(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function sy(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function iy(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function TT(t){return t.secure=ld(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function zT(t){if((t.port===(ld(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function PT(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(kT);if(r&&r[0]===t.path){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=dd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function RT(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=dd(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function IT(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!$T(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function OT(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var ay={scheme:"http",domainHost:!0,parse:sy,serialize:iy},CT={scheme:"https",domainHost:ay.domainHost,parse:sy,serialize:iy},Oi={scheme:"ws",domainHost:!0,parse:TT,serialize:zT},AT={scheme:"wss",domainHost:Oi.domainHost,parse:Oi.parse,serialize:Oi.serialize},NT={scheme:"urn",parse:PT,serialize:RT,skipNormalize:!0},MT={scheme:"urn:uuid",parse:IT,serialize:OT,skipNormalize:!0},Ci={http:ay,https:CT,ws:Oi,wss:AT,urn:NT,"urn:uuid":MT};Object.setPrototypeOf(Ci,null);function dd(t){return t&&(Ci[t]||Ci[t.toLowerCase()])||void 0}cy.exports={wsIsSecure:ld,SCHEMES:Ci,isValidSchemeName:ET,getSchemeHandler:dd}});var wy=T((zZ,Mi)=>{"use strict";var{normalizeIPv6:my,removeDotSegments:Bo,recomposeAuthority:jT,normalizePercentEncoding:fd,normalizePathEncoding:ZT,serializePathEncoding:ly,normalizeQueryFragmentEncoding:dy,encodeQuery:DT,encodeFragment:qT,reescapeHostDelimiters:LT,isIPv4:hy,nonSimpleDomain:UT}=ud(),{SCHEMES:gy,getSchemeHandler:pd}=uy(),yy=/^[A-Za-z][A-Za-z0-9+.-]*$/u,_y="URI scheme is malformed.";function fy(t){let e=unescape(String(t));if(!yy.test(e))throw new TypeError(_y);return e}function FT(t,e){return typeof t=="string"?t=XT(t,e):typeof t=="object"&&(t=Ni(en(t,e),e)),t}function HT(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=Ai(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:p,malformedSchemeSpecific:m,malformedHost:f,malformedScheme:h}=Ai(e,n);if(s||d||i||p||a||m||c||f||u||h)throw new Error(o.error||l.error||"URI is malformed.");let y=vy(o,l,n,!0),_=pd(r&&r.scheme||y.scheme),v=y.host,g=v!==void 0&&v!==""&&(hy(v)||my(v).isIPV6);xy(y,r||{},_,g);let x=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(y.error&&!x)throw new Error(y.error);return n.skipEscape=!0,en(y,n)}function vy(t,e,r,n){let o={};return n||(t=Ni(en(t,r),r),e=Ni(en(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Bo(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Bo(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Bo(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Bo(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function VT(t,e,r){let n=py(t,r),o=py(e,r);return n!==void 0&&o!==void 0&&n===o}function en(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[];r.scheme&&(r.scheme=fy(r.scheme));let s=pd(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=!n.skipEscape&&r.scheme===void 0&&!i;r.path!==void 0&&(n.skipEscape?r.path=fd(r.path):r.path=ly(r.path,a)),n.reference!=="suffix"&&r.scheme&&(r.scheme=fy(r.scheme),o.push(r.scheme,":"));let c=jT(r);if(c!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(c),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(u=Bo(u)),a&&(u=ly(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return r.query!==void 0&&o.push("?",DT(r.query)),r.fragment!==void 0&&o.push("#",qT(r.fragment)),o.join("")}var BT=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,JT=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,WT=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function KT(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Vo(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function md(t){return t[0]==="["&&t[t.length-1]==="]"}function GT(t){let e=t[4];return Vo(t[3])||e!==void 0&&!md(e)&&Vo(e)||Vo(t[6])||Vo(t[7])||Vo(t[8])}function xy(t,e,r,n){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!md(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&UT(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(o){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+o,!0}return!1}function Ai(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,c=!1,u=!1,l=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let d=t.match(JT);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let p=t.match(WT);if(p!==null){let f=p[1],h=f.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let m=t.match(BT);if(m){if(n.scheme=m[1],n.userinfo=m[3],n.host=m[4],n.port=parseInt(m[5],10),n.path=m[6]||"",n.query=m[7],n.fragment=m[8],n.scheme!==void 0){let y=unescape(n.scheme);yy.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||_y,u=!0)}s=GT(m),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=m[5]);let f=KT(n,m);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(hy(n.host)===!1){let _=md(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,g=my(n.host);l=g.isIPV6||g.isIPVFuture===!0,c=v&&(!_||g.error===!0),n.host=l?g.host:g.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",o=!0)}else l=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let h=pd(r.scheme||n.scheme);if(c||(a=xy(n,r,h,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=l?n.host:fd(n.host,!0);l||(y=fd(y.toLowerCase())),n.host=LT(y,l)}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=ZT(n.path)),n.query&&(n.query=dy(n.query)),n.fragment&&(n.fragment=dy(n.fragment))),h&&h.parse&&(h.parse(n,r),h===gy.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function Ni(t,e){return Ai(t,e).parsed}function XT(t,e){return by(t,e).normalized}function by(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Ai(t,e);return{normalized:n||o||s||i||a?t:en(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function py(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:en(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=by(r,e);return o||s||i||a||c?void 0:n}var hd={SCHEMES:gy,normalize:FT,resolve:HT,resolveComponent:vy,equal:VT,serialize:en,parse:Ni};Mi.exports=hd;Mi.exports.default=hd;Mi.exports.fastUri=hd});var ky=T(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var $y=wy();$y.code='require("ajv/dist/runtime/uri").default';gd.default=$y});var Oy=T(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=void 0;var YT=Fo();Object.defineProperty(Ce,"KeywordCxt",{enumerable:!0,get:function(){return YT.KeywordCxt}});var Zn=B();Object.defineProperty(Ce,"_",{enumerable:!0,get:function(){return Zn._}});Object.defineProperty(Ce,"str",{enumerable:!0,get:function(){return Zn.str}});Object.defineProperty(Ce,"stringify",{enumerable:!0,get:function(){return Zn.stringify}});Object.defineProperty(Ce,"nil",{enumerable:!0,get:function(){return Zn.nil}});Object.defineProperty(Ce,"Name",{enumerable:!0,get:function(){return Zn.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:!0,get:function(){return Zn.CodeGen}});var QT=Pi(),Py=Ho(),ez=Zl(),Jo=Ii(),tz=B(),Wo=qo(),ji=Do(),_d=re(),Sy=Xg(),rz=ky(),Ry=(t,e)=>new RegExp(t,e);Ry.code="new RegExp";var nz=["removeAdditional","useDefaults","coerceTypes"],oz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),sz={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."},iz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ey=200;function az(t){var e,r,n,o,s,i,a,c,u,l,d,p,m,f,h,y,_,v,g,x,$,D,R,ae,ce;let Te=t.strict,L=(e=t.code)===null||e===void 0?void 0:e.optimize,_e=L===!0||L===void 0?1:L||0,$t=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Ry,xr=(o=t.uriResolver)!==null&&o!==void 0?o:rz.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Te)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Te)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Te)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:Te)!==null&&p!==void 0?p:"log",strictRequired:(f=(m=t.strictRequired)!==null&&m!==void 0?m:Te)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:_e,regExp:$t}:{optimize:_e,regExp:$t},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Ey,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Ey,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(g=t.inlineRefs)!==null&&g!==void 0?g:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(D=t.validateSchema)!==null&&D!==void 0?D:!0,validateFormats:(R=t.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(ae=t.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(ce=t.int32range)!==null&&ce!==void 0?ce:!0,uriResolver:xr}}var Ko=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...az(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new tz.ValueScope({scope:{},prefixes:oz,es5:r,lines:n}),this.logger=pz(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,ez.getRules)(),Ty.call(this,sz,e,"NOT SUPPORTED"),Ty.call(this,iz,e,"DEPRECATED","warn"),this._metaOpts=dz.call(this),e.formats&&uz.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&lz.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),cz.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Sy;n==="id"&&(o={...Sy},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof Py.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Wo.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=zy.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Jo.SchemaEnv({schema:{},schemaId:n});if(r=Jo.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=zy.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Wo.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(hz.call(this,n,r),!r)return(0,_d.eachItem)(n,s=>yd.call(this,s)),this;yz.call(this,r);let o={...r,type:(0,ji.getJSONTypes)(r.type),schemaType:(0,ji.getJSONTypes)(r.schemaType)};return(0,_d.eachItem)(n,o.type.length===0?s=>yd.call(this,s,o):s=>o.type.forEach(i=>yd.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=Iy(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Wo.normalizeId)(i||n);let u=Wo.getSchemaRefs.call(this,e,n);return c=new Jo.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Jo.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Jo.compileSchema.call(this,e)}finally{this.opts=r}}};Ko.ValidationError=QT.default;Ko.MissingRefError=Py.default;Ce.default=Ko;function Ty(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function zy(t){return t=(0,Wo.normalizeId)(t),this.schemas[t]||this.refs[t]}function cz(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function uz(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function lz(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function dz(){let t={...this.opts};for(let e of nz)delete t[e];return t}var fz={log(){},warn(){},error(){}};function pz(t){if(t===!1)return fz;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var mz=/^[a-z_$][a-z0-9_$:-]*$/i;function hz(t,e){let{RULES:r}=this;if((0,_d.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!mz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function yd(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ji.getJSONTypes)(e.type),schemaType:(0,ji.getJSONTypes)(e.schemaType)}};e.before?gz.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function gz(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function yz(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Iy(e)),t.validateSchema=this.compile(e,!0))}var _z={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Iy(t){return{anyOf:[t,_z]}}});var Cy=T(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var vz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vd.default=vz});var jy=T(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.callRef=tn.getValidate=void 0;var xz=Ho(),Ay=ut(),et=B(),Dn=Jt(),Ny=Ii(),Zi=re(),bz={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=Ny.resolveRef.call(c,u,o,r);if(l===void 0)throw new xz.default(n.opts.uriResolver,o,r);if(l instanceof Ny.SchemaEnv)return p(l);return m(l);function d(){if(s===u)return Di(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return Di(t,(0,et._)`${f}.validate`,u,u.$async)}function p(f){let h=My(t,f);Di(t,h,f,f.$async)}function m(f){let h=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,et.stringify)(f)}:{ref:f}),y=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:et.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(_),t.ok(y)}}};function My(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}tn.getValidate=My;function Di(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Dn.default.this:et.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,et._)`await ${(0,Ay.callValidateCode)(t,e,u)}`),m(e),i||o.assign(f,!0)},h=>{o.if((0,et._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,Ay.callValidateCode)(t,e,u),()=>m(e),()=>p(e))}function p(f){let h=(0,et._)`${f}.errors`;o.assign(Dn.default.vErrors,(0,et._)`${Dn.default.vErrors} === null ? ${h} : ${Dn.default.vErrors}.concat(${h})`),o.assign(Dn.default.errors,(0,et._)`${Dn.default.vErrors}.length`)}function m(f){var h;if(!s.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Zi.mergeEvaluated.props(o,y.props,s.props));else{let _=o.var("props",(0,et._)`${f}.evaluated.props`);s.props=Zi.mergeEvaluated.props(o,_,s.props,et.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Zi.mergeEvaluated.items(o,y.items,s.items));else{let _=o.var("items",(0,et._)`${f}.evaluated.items`);s.items=Zi.mergeEvaluated.items(o,_,s.items,et.Name)}}}tn.callRef=Di;tn.default=bz});var Zy=T(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var wz=Cy(),$z=jy(),kz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",wz.default,$z.default];xd.default=kz});var Dy=T(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var qi=B(),mr=qi.operators,Li={maximum:{okStr:"<=",ok:mr.LTE,fail:mr.GT},minimum:{okStr:">=",ok:mr.GTE,fail:mr.LT},exclusiveMaximum:{okStr:"<",ok:mr.LT,fail:mr.GTE},exclusiveMinimum:{okStr:">",ok:mr.GT,fail:mr.LTE}},Sz={message:({keyword:t,schemaCode:e})=>(0,qi.str)`must be ${Li[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qi._)`{comparison: ${Li[t].okStr}, limit: ${e}}`},Ez={keyword:Object.keys(Li),type:"number",schemaType:"number",$data:!0,error:Sz,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,qi._)`${r} ${Li[e].fail} ${n} || isNaN(${r})`)}};bd.default=Ez});var qy=T(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var Go=B(),Tz={message:({schemaCode:t})=>(0,Go.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Go._)`{multipleOf: ${t}}`},zz={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Tz,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Go._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Go._)`${i} !== parseInt(${i})`;t.fail$data((0,Go._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};wd.default=zz});var Uy=T($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});function Ly(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}$d.default=Ly;Ly.code='require("ajv/dist/runtime/ucs2length").default'});var Fy=T(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var rn=B(),Pz=re(),Rz=Uy(),Iz={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,rn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,rn._)`{limit: ${t}}`},Oz={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Iz,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?rn.operators.GT:rn.operators.LT,i=o.opts.unicode===!1?(0,rn._)`${r}.length`:(0,rn._)`${(0,Pz.useFunc)(t.gen,Rz.default)}(${r})`;t.fail$data((0,rn._)`${i} ${s} ${n}`)}};kd.default=Oz});var Hy=T(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Cz=ut(),Az=re(),qn=B(),Nz={message:({schemaCode:t})=>(0,qn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,qn._)`{pattern: ${t}}`},Mz={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Nz,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,qn._)`new RegExp`:(0,Az.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,qn._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,qn._)`!${l}`)}else{let c=(0,Cz.usePattern)(t,o);t.fail$data((0,qn._)`!${c}.test(${r})`)}}};Sd.default=Mz});var Vy=T(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var Xo=B(),jz={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Xo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Xo._)`{limit: ${t}}`},Zz={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:jz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Xo.operators.GT:Xo.operators.LT;t.fail$data((0,Xo._)`Object.keys(${r}).length ${o} ${n}`)}};Ed.default=Zz});var By=T(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Yo=ut(),Qo=B(),Dz=re(),qz={message:({params:{missingProperty:t}})=>(0,Qo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Qo._)`{missingProperty: ${t}}`},Lz={keyword:"required",type:"object",schemaType:"array",$data:!0,error:qz,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:f}=t.it;for(let h of r)if(m?.[h]===void 0&&!f.has(h)){let y=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,Dz.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Qo.nil,d);else for(let m of r)(0,Yo.checkReportMissingProp)(t,m)}function l(){let m=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>p(m,f)),t.ok(f)}else e.if((0,Yo.checkMissingProp)(t,r,m)),(0,Yo.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,Yo.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function p(m,f){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(f,(0,Yo.propertyInData)(e,o,m,a.ownProperties)),e.if((0,Qo.not)(f),()=>{t.error(),e.break()})},Qo.nil)}}};Td.default=Lz});var Jy=T(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var es=B(),Uz={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,es.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,es._)`{limit: ${t}}`},Fz={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Uz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?es.operators.GT:es.operators.LT;t.fail$data((0,es._)`${r}.length ${o} ${n}`)}};zd.default=Fz});var Ui=T(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var Wy=Bl();Wy.code='require("ajv/dist/runtime/equal").default';Pd.default=Wy});var Ky=T(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var Rd=Do(),Ae=B(),Hz=re(),Vz=Ui(),Bz={message:({params:{i:t,j:e}})=>(0,Ae.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ae._)`{i: ${t}, j: ${e}}`},Jz={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Bz,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Rd.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ae._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Ae._)`${r}.length`),h=e.let("j");t.setParams({i:f,j:h}),e.assign(c,!0),e.if((0,Ae._)`${f} > 1`,()=>(d()?p:m)(f,h))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function p(f,h){let y=e.name("item"),_=(0,Rd.checkDataTypes)(u,y,a.opts.strictNumbers,Rd.DataType.Wrong),v=e.const("indices",(0,Ae._)`{}`);e.for((0,Ae._)`;${f}--;`,()=>{e.let(y,(0,Ae._)`${r}[${f}]`),e.if(_,(0,Ae._)`continue`),u.length>1&&e.if((0,Ae._)`typeof ${y} == "string"`,(0,Ae._)`${y} += "_"`),e.if((0,Ae._)`typeof ${v}[${y}] == "number"`,()=>{e.assign(h,(0,Ae._)`${v}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ae._)`${v}[${y}] = ${f}`)})}function m(f,h){let y=(0,Hz.useFunc)(e,Vz.default),_=e.name("outer");e.label(_).for((0,Ae._)`;${f}--;`,()=>e.for((0,Ae._)`${h} = ${f}; ${h}--;`,()=>e.if((0,Ae._)`${y}(${r}[${f}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};Id.default=Jz});var Gy=T(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var Od=B(),Wz=re(),Kz=Ui(),Gz={message:"must be equal to constant",params:({schemaCode:t})=>(0,Od._)`{allowedValue: ${t}}`},Xz={keyword:"const",$data:!0,error:Gz,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Od._)`!${(0,Wz.useFunc)(e,Kz.default)}(${r}, ${o})`):t.fail((0,Od._)`${s} !== ${r}`)}};Cd.default=Xz});var Xy=T(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var ts=B(),Yz=re(),Qz=Ui(),eP={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ts._)`{allowedValues: ${t}}`},tP={keyword:"enum",schemaType:"array",$data:!0,error:eP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,Yz.useFunc)(e,Qz.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);l=(0,ts.or)(...o.map((f,h)=>p(m,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,m=>e.if((0,ts._)`${u()}(${r}, ${m})`,()=>e.assign(l,!0).break()))}function p(m,f){let h=o[f];return typeof h=="object"&&h!==null?(0,ts._)`${u()}(${r}, ${m}[${f}])`:(0,ts._)`${r} === ${h}`}}};Ad.default=tP});var Yy=T(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var rP=Dy(),nP=qy(),oP=Fy(),sP=Hy(),iP=Vy(),aP=By(),cP=Jy(),uP=Ky(),lP=Gy(),dP=Xy(),fP=[rP.default,nP.default,oP.default,sP.default,iP.default,aP.default,cP.default,uP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},lP.default,dP.default];Nd.default=fP});var jd=T(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.validateAdditionalItems=void 0;var nn=B(),Md=re(),pP={message:({params:{len:t}})=>(0,nn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,nn._)`{limit: ${t}}`},mP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:pP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Md.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Qy(t,n)}};function Qy(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,nn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,nn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Md.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,nn._)`${a} <= ${e.length}`);r.if((0,nn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Md.Type.Num},u),i.allErrors||r.if((0,nn.not)(u),()=>r.break())})}}rs.validateAdditionalItems=Qy;rs.default=mP});var Zd=T(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.validateTuple=void 0;var e_=B(),Fi=re(),hP=ut(),gP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return t_(t,"additionalItems",e);r.items=!0,!(0,Fi.alwaysValidSchema)(r,e)&&t.ok((0,hP.validateArray)(t))}};function t_(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Fi.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,e_._)`${s}.length`);r.forEach((d,p)=>{(0,Fi.alwaysValidSchema)(a,d)||(n.if((0,e_._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:m}=a,f=r.length,h=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let y=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Fi.checkStrictMode)(a,y,p.strictTuples)}}}ns.validateTuple=t_;ns.default=gP});var r_=T(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var yP=Zd(),_P={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,yP.validateTuple)(t,"items")};Dd.default=_P});var o_=T(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var n_=B(),vP=re(),xP=ut(),bP=jd(),wP={message:({params:{len:t}})=>(0,n_.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,n_._)`{limit: ${t}}`},$P={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:wP,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,vP.alwaysValidSchema)(n,e)&&(o?(0,bP.validateAdditionalItems)(t,o):t.ok((0,xP.validateArray)(t)))}};qd.default=$P});var s_=T(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var dt=B(),Hi=re(),kP={message:({params:{min:t,max:e}})=>e===void 0?(0,dt.str)`must contain at least ${t} valid item(s)`:(0,dt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dt._)`{minContains: ${t}}`:(0,dt._)`{minContains: ${t}, maxContains: ${e}}`},SP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:kP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,dt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Hi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Hi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Hi.alwaysValidSchema)(s,r)){let h=(0,dt._)`${l} >= ${i}`;a!==void 0&&(h=(0,dt._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,dt._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),y=e.let("count",0);m(h,()=>e.if(h,()=>f(y)))}function m(h,y){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:Hi.Type.Num,compositeRule:!0},h),y()})}function f(h){e.code((0,dt._)`${h}++`),a===void 0?e.if((0,dt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,dt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,dt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};Ld.default=SP});var c_=T(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.validateSchemaDeps=Ot.validatePropertyDeps=Ot.error=void 0;var Ud=B(),EP=re(),os=ut();Ot.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Ud.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Ud._)`{property: ${t},
35
35
  missingProperty: ${n},
36
36
  depsCount: ${e},
37
- deps: ${r}}`};var SP={keyword:"dependencies",type:"object",schemaType:"object",error:Ot.error,code(t){let[e,r]=EP(t);s_(t,e),i_(t,r)}};function EP({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function s_(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,os.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,os.checkReportMissingProp)(t,u)}):(r.if((0,Ld._)`${c} && (${(0,os.checkMissingProp)(t,a,s)})`),(0,os.reportMissingProp)(t,s),r.else())}}Ot.validatePropertyDeps=s_;function i_(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,kP.alwaysValidSchema)(s,e[a])||(r.if((0,os.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ot.validateSchemaDeps=i_;Ot.default=SP});var u_=T(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var c_=B(),TP=re(),zP={message:"property name must be valid",params:({params:t})=>(0,c_._)`{propertyName: ${t.propertyName}}`},PP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:zP,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,TP.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,c_.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ud.default=PP});var Hd=T(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Vi=ut(),bt=B(),RP=Jt(),Bi=re(),IP={message:"must NOT have additional properties",params:({params:t})=>(0,bt._)`{additionalProperty: ${t.additionalProperty}}`},OP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:IP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Bi.alwaysValidSchema)(i,r))return;let u=(0,Vi.allSchemaProperties)(n.properties),l=(0,Vi.allSchemaProperties)(n.patternProperties);d(),t.ok((0,bt._)`${s} === ${RP.default.errors}`);function d(){e.forIn("key",o,y=>{!u.length&&!l.length?f(y):e.if(p(y),()=>f(y))})}function p(y){let _;if(u.length>8){let v=(0,Bi.schemaRefOrVal)(i,n.properties,"properties");_=(0,Vi.isOwnProperty)(e,v,y)}else u.length?_=(0,bt.or)(...u.map(v=>(0,bt._)`${y} === ${v}`)):_=bt.nil;return l.length&&(_=(0,bt.or)(_,...l.map(v=>(0,bt._)`${(0,Vi.usePattern)(t,v)}.test(${y})`))),(0,bt.not)(_)}function m(y){e.code((0,bt._)`delete ${o}[${y}]`)}function f(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Bi.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(h(y,_,!1),e.if((0,bt.not)(_),()=>{t.reset(),m(y)})):(h(y,_),a||e.if((0,bt.not)(_),()=>e.break()))}}function h(y,_,v){let g={keyword:"additionalProperties",dataProp:y,dataPropType:Bi.Type.Str};v===!1&&Object.assign(g,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(g,_)}}};Fd.default=OP});var f_=T(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var CP=Fo(),l_=ut(),Vd=re(),d_=Hd(),AP={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&d_.default.code(new CP.KeywordCxt(s,d_.default,"additionalProperties"));let i=(0,l_.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Vd.mergeEvaluated.props(e,(0,Vd.toHash)(i),s.props));let a=i.filter(d=>!(0,Vd.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,l_.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Bd.default=AP});var g_=T(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var p_=ut(),Ji=B(),m_=re(),h_=re(),NP={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,p_.allSchemaProperties)(r),c=a.filter(h=>(0,m_.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Ji.Name)&&(s.props=(0,h_.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&m(h),s.allErrors?f(h):(e.var(l,!0),f(h),e.if(l))}function m(h){for(let y in u)new RegExp(h).test(y)&&(0,m_.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",n,y=>{e.if((0,Ji._)`${(0,p_.usePattern)(t,h)}.test(${y})`,()=>{let _=c.includes(h);_||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:h_.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ji._)`${d}[${y}]`,!0):!_&&!s.allErrors&&e.if((0,Ji.not)(l),()=>e.break())})})}}};Jd.default=NP});var y_=T(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var MP=re(),jP={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,MP.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Wd.default=jP});var __=T(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var ZP=ut(),DP={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ZP.validateUnion,error:{message:"must match a schema in anyOf"}};Kd.default=DP});var v_=T(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var Wi=B(),qP=re(),LP={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Wi._)`{passingSchemas: ${t.passing}}`},UP={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:LP,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,qP.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Wi._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Wi._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Wi.Name)})})}}};Gd.default=UP});var x_=T(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var FP=re(),HP={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,FP.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Xd.default=HP});var $_=T(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var Ki=B(),w_=re(),VP={message:({params:t})=>(0,Ki.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ki._)`{failingKeyword: ${t.ifClause}}`},BP={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:VP,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,w_.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=b_(n,"then"),s=b_(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Ki.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Ki._)`${l}`):t.setParams({ifClause:l})}}}};function b_(t,e){let r=t.schema[e];return r!==void 0&&!(0,w_.alwaysValidSchema)(t,r)}Yd.default=BP});var k_=T(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var JP=re(),WP={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,JP.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Qd.default=WP});var S_=T(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var KP=Md(),GP=t_(),XP=jd(),YP=n_(),QP=o_(),eR=a_(),tR=u_(),rR=Hd(),nR=f_(),oR=g_(),sR=y_(),iR=__(),aR=v_(),cR=x_(),uR=$_(),lR=k_();function dR(t=!1){let e=[sR.default,iR.default,aR.default,cR.default,uR.default,lR.default,tR.default,rR.default,eR.default,nR.default,oR.default];return t?e.push(GP.default,YP.default):e.push(KP.default,XP.default),e.push(QP.default),e}ef.default=dR});var E_=T(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var ke=B(),fR={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},pR={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:fR,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():m();function p(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ke._)`${f}[${i}]`),y=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,ke._)`${h}.type || "string"`).assign(_,(0,ke._)`${h}.validate`),()=>r.assign(y,(0,ke._)`"string"`).assign(_,h)),t.fail$data((0,ke.or)(v(),g()));function v(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function g(){let x=l.$async?(0,ke._)`(${h}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,$=(0,ke._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${y} === ${e} && !${$}`}}function m(){let f=d.formats[s];if(!f){v();return}if(f===!0)return;let[h,y,_]=g(f);h===e&&t.pass(x());function v(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function g($){let D=$ instanceof RegExp?(0,ke.regexpCode)($):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,R=r.scopeValue("formats",{key:s,ref:$,code:D});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,ke._)`${R}.validate`]:["string",$,R]}function x(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${_}(${n})`}return typeof y=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};tf.default=pR});var T_=T(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var mR=E_(),hR=[mR.default];rf.default=hR});var z_=T(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.contentVocabulary=Ln.metadataVocabulary=void 0;Ln.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ln.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var R_=T(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var gR=jy(),yR=Xy(),_R=S_(),vR=T_(),P_=z_(),xR=[gR.default,yR.default,(0,_R.default)(),vR.default,P_.metadataVocabulary,P_.contentVocabulary];nf.default=xR});var O_=T(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.DiscrError=void 0;var I_;(function(t){t.Tag="tag",t.Mapping="mapping"})(I_||(Gi.DiscrError=I_={}))});var A_=T(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var Un=B(),of=O_(),C_=Ii(),bR=Ho(),wR=re(),$R={message:({params:{discrError:t,tagName:e}})=>t===of.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Un._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},kR={keyword:"discriminator",type:"object",schemaType:"object",error:$R,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Un._)`${r}${(0,Un.getProperty)(a)}`);e.if((0,Un._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:of.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let m=p();e.if(!1);for(let f in m)e.elseIf((0,Un._)`${u} === ${f}`),e.assign(c,d(m[f]));e.else(),t.error(!1,{discrError:of.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(m){let f=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:m},f);return t.mergeEvaluated(h,Un.Name),f}function p(){var m;let f={},h=_(o),y=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,wR.schemaHasRulesButRef)($,s.self.RULES)){let R=$.$ref;if($=C_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),$ instanceof C_.SchemaEnv&&($=$.schema),$===void 0)throw new bR.default(s.opts.uriResolver,s.baseId,R)}let D=(m=$?.properties)===null||m===void 0?void 0:m[a];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||_($)),v(D,x)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return f;function _({required:x}){return Array.isArray(x)&&x.includes(a)}function v(x,$){if(x.const)g(x.const,$);else if(x.enum)for(let D of x.enum)g(D,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function g(x,$){if(typeof x!="string"||x in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[x]=$}}}};sf.default=kR});var N_=T((hD,SR)=>{SR.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}});var cf=T((ye,af)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var ER=Iy(),TR=R_(),zR=A_(),M_=N_(),PR=["/properties"],Xi="http://json-schema.org/draft-07/schema",Fn=class extends ER.default{_addVocabularies(){super._addVocabularies(),TR.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(zR.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(M_,PR):M_;this.addMetaSchema(e,Xi,!1),this.refs["http://json-schema.org/schema"]=Xi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Xi)?Xi:void 0)}};ye.Ajv=Fn;af.exports=ye=Fn;af.exports.Ajv=Fn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Fn;var RR=Fo();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return RR.KeywordCxt}});var Hn=B();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Hn._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Hn.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Hn.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Hn.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Hn.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Hn.CodeGen}});var IR=Pi();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return IR.default}});var OR=Ho();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return OR.default}})});var H_=T(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.formatNames=At.fastFormats=At.fullFormats=void 0;function Ct(t,e){return{validate:t,compare:e}}At.fullFormats={date:Ct(q_,ff),time:Ct(lf(!0),pf),"date-time":Ct(j_(!0),U_),"iso-time":Ct(lf(),L_),"iso-date-time":Ct(j_(),F_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:ZR,"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:VR,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:DR,int32:{type:"number",validate:UR},int64:{type:"number",validate:FR},float:{type:"number",validate:D_},double:{type:"number",validate:D_},password:!0,binary:!0};At.fastFormats={...At.fullFormats,date:Ct(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ff),time:Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,pf),"date-time":Ct(/^\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,U_),"iso-time":Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,L_),"iso-date-time":Ct(/^\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,F_),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};At.formatNames=Object.keys(At.fullFormats);function CR(t){return t%4===0&&(t%100!==0||t%400===0)}var AR=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,NR=[0,31,28,31,30,31,30,31,31,30,31,30,31];function q_(t){let e=AR.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&CR(r)?29:NR[n])}function ff(t,e){if(t&&e)return t>e?1:t<e?-1:0}var uf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function lf(t){return function(r){let n=uf.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function pf(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function L_(t,e){if(!(t&&e))return;let r=uf.exec(t),n=uf.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var df=/t|\s/i;function j_(t){let e=lf(t);return function(n){let o=n.split(df);return o.length===2&&q_(o[0])&&e(o[1])}}function U_(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function F_(t,e){if(!(t&&e))return;let[r,n]=t.split(df),[o,s]=e.split(df),i=ff(r,o);if(i!==void 0)return i||pf(n,s)}var MR=/\/|:/,jR=/^(?:[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 ZR(t){return MR.test(t)&&jR.test(t)}var Z_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function DR(t){return Z_.lastIndex=0,Z_.test(t)}var qR=-(2**31),LR=2**31-1;function UR(t){return Number.isInteger(t)&&t<=LR&&t>=qR}function FR(t){return Number.isInteger(t)}function D_(){return!0}var HR=/[^\\]\\Z/;function VR(t){if(HR.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var V_=T(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.formatLimitDefinition=void 0;var BR=cf(),wt=B(),hr=wt.operators,Yi={formatMaximum:{okStr:"<=",ok:hr.LTE,fail:hr.GT},formatMinimum:{okStr:">=",ok:hr.GTE,fail:hr.LT},formatExclusiveMaximum:{okStr:"<",ok:hr.LT,fail:hr.GTE},formatExclusiveMinimum:{okStr:">",ok:hr.GT,fail:hr.LTE}},JR={message:({keyword:t,schemaCode:e})=>(0,wt.str)`should be ${Yi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wt._)`{comparison: ${Yi[t].okStr}, limit: ${e}}`};Vn.formatLimitDefinition={keyword:Object.keys(Yi),type:"string",schemaType:"string",$data:!0,error:JR,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new BR.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,wt._)`${p}[${c.schemaCode}]`);t.fail$data((0,wt.or)((0,wt._)`typeof ${m} != "object"`,(0,wt._)`${m} instanceof RegExp`,(0,wt._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let p=c.schema,m=a.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let f=e.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,wt._)`${i.code.formats}${(0,wt.getProperty)(p)}`:void 0});t.fail$data(d(f))}function d(p){return(0,wt._)`${p}.compare(${r}, ${n}) ${Yi[o].fail} 0`}},dependencies:["format"]};var WR=t=>(t.addKeyword(Vn.formatLimitDefinition),t);Vn.default=WR});var K_=T((ss,W_)=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});var Bn=H_(),KR=V_(),mf=B(),B_=new mf.Name("fullFormats"),GR=new mf.Name("fastFormats"),hf=(t,e={keywords:!0})=>{if(Array.isArray(e))return J_(t,e,Bn.fullFormats,B_),t;let[r,n]=e.mode==="fast"?[Bn.fastFormats,GR]:[Bn.fullFormats,B_],o=e.formats||Bn.formatNames;return J_(t,o,r,n),e.keywords&&(0,KR.default)(t),t};hf.get=(t,e="full")=>{let n=(e==="fast"?Bn.fastFormats:Bn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function J_(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,mf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}W_.exports=ss=hf;Object.defineProperty(ss,"__esModule",{value:!0});ss.default=hf});var Dv={};eo(Dv,{findEmbeddingModel:()=>Zv,ollamaUrl:()=>Rf,semanticRerank:()=>zI});import{createHash as yI}from"node:crypto";import{existsSync as _I,mkdirSync as vI,readFileSync as xI,writeFileSync as bI}from"node:fs";import{homedir as wI}from"node:os";import{join as Pf}from"node:path";function Rf(t=process.env.OLLAMA_HOST){let e=(t??"").trim(),r="http",n="11434",o=e.indexOf("://");o>=0&&(r=e.slice(0,o),e=e.slice(o+3),r==="http"?n="80":r==="https"&&(n="443"));let s=e.indexOf("/"),i=s>=0?e.slice(s).replace(/\/+$/,""):"",a=s>=0?e.slice(0,s):e,c=/^(\[[^\]]*\]|[^:]*):([^:]*)$/.exec(a);return c?(a=c[1],/^\d+$/.test(c[2])&&Number(c[2])<=65535&&(n=c[2])):a.includes(":")&&!a.startsWith("[")&&(a=`[${a}]`),!a||a==="0.0.0.0"?a="127.0.0.1":a==="[::]"&&(a="[::1]"),`${r}://${a}:${n}${i}`}async function jv(t,e,r=6e4){let n=await fetch(Rf()+t,{method:e?"POST":"GET",headers:e?{"content-type":"application/json"}:void 0,body:e?JSON.stringify(e):void 0,signal:AbortSignal.timeout(r)});if(!n.ok)throw new Error(`${t}: HTTP ${n.status}`);return n.json()}async function Zv(t){let r=((await jv("/api/tags",void 0,2e3)).models??[]).map(n=>String(n.name));return t?r.find(n=>n===t||n.startsWith(t+":"))??t:r.find(n=>$I.test(n))}function pa(){return Pf(process.env.XDG_CACHE_HOME??Pf(wI(),".cache"),"context-doctor","embeddings.json")}function kI(){try{return _I(pa())?JSON.parse(xI(pa(),"utf8")):{}}catch{return{}}}function SI(t){try{let e=Object.keys(t);if(e.length>Mv)for(let r of e.slice(0,e.length-Mv))delete t[r];vI(Pf(pa(),".."),{recursive:!0}),bI(pa(),JSON.stringify(t))}catch{}}async function EI(t,e){let r=[];for(let n=0;n<e.length;n+=Nv){let o=await jv("/api/embed",{model:t,input:e.slice(n,n+Nv),truncate:!0});r.push(...o.embeddings)}return r}function TI(t,e){let r=0,n=0,o=0;for(let s=0;s<t.length;s++)r+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return n&&o?r/Math.sqrt(n*o):0}async function zI(t,e,r={}){let n;try{n=await Zv(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${Rf()} (keyword ranking only)`}}if(!n)return{used:!1,note:"semantic ranking off: Ollama has no embedding model; run `ollama pull nomic-embed-text` (keyword ranking only)"};let o=kI(),s=f=>yI("sha1").update(n+"\0"+f).digest("hex"),i=t.map(f=>(f.heading?f.heading+`
38
- `:"")+f.text),a=[...new Set(i.filter(f=>!o[s(f)]))],c,u;try{let f=await EI(n,[e,...a]);u=f[0],a.forEach((h,y)=>o[s(h)]=f[y+1]),c=i.map(h=>o[s(h)])}catch(f){return{used:!1,model:n,note:`semantic ranking off: ${n} failed (${f.message}); keyword ranking only`}}a.length&&SI(o);let l=60,d=new Map([...t].filter(f=>f.score>0).sort((f,h)=>h.score-f.score).map((f,h)=>[f,h])),p=t.map((f,h)=>({c:f,s:TI(u,c[h])})).sort((f,h)=>h.s-f.s),m=new Map(p.map((f,h)=>[f.c,h]));for(let f of t){let h=d.get(f);f.score=(h===void 0?0:1/(l+h))+1/(l+m.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var $I,Nv,Mv,qv=G(()=>{"use strict";$I=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,Nv=64,Mv=5e4});var Kv,Gv=G(()=>{Kv="x-hono-already-sent"});var Xv,Yv=G(()=>{Xv=t=>((...e)=>{if(typeof e[0]=="function"){let[r,n]=e;return async function(s,i){let a=await t(s,await r(s),n);if(a)return a;await i()}}else{let[r,n,o]=e;return(async()=>{let s=await t(r,n,o);if(!s)throw new Error("Failed to upgrade WebSocket");return s})()}})});import{Http2ServerRequest as Xn,constants as sO}from"node:http2";import{Readable as Qv}from"node:stream";async function zO(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function f0(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(i,o),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function o(a){a&&e.destroy(a)}function s(){t.read().then(i,o)}function i({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",s);else return t.read().then(i,o)}catch(u){o(u)}}}function o0(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:f0(t.getReader(),e)}var Nt,iO,aO,cO,uO,lO,dO,Yn,i0,a0,fO,pO,Nf,Mf,c0,Uf,e0,_a,t0,mO,vr,Kt,Qn,ds,u0,l0,us,jf,Zf,_r,ya,Xt,r0,ls,va,fs,hO,gO,yO,_O,vO,xO,bO,Ff,wO,n0,$O,jt,kO,yr,Df,Gn,Gt,xa,Mt,SO,EO,TO,qf,ba,s0,PO,RO,p0,IO,OO,CO,m0,wa,Lf,h0,g0,AO,Hf,NO,MO,jO,ZO,DO,X2,y0=G(()=>{Gv();Yv();Nt=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},iO=/^\/[!#$&-;=?-\[\]_a-z~]*$/,aO=/\/\.\.?(?:[/?#]|$)/,cO=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,uO=(t,e,r)=>{let n=`${t}://${e}${r}`;if(cO.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Nt("Invalid URL");return!iO.test(r)||aO.test(r)?new URL(n).href:n}else{let o=new URL(n);if(o.hostname.length!==e.length&&o.hostname!==(e.includes(":")?e.replace(/:\d+$/,""):e).toLowerCase())throw new Nt("Invalid host header");return o.href}},lO=t=>t instanceof Nt?t:new Nt(t.message,{cause:t}),dO=global.Request,Yn=class extends dO{constructor(t,e){if(typeof t=="object"&&vr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[Xt]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[vr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},i0=t=>{let e=[],r=t.rawHeaders;for(let n=0,o=r.length;n<o;n+=2){let s=r[n];s.charCodeAt(0)!==58&&e.push([s,r[n+1]])}return new Headers(e)},a0=Symbol("wrapBodyStream"),fO=new Set(["latin1","binary","hex","base64","base64url"]),pO=t=>t===null||fO.has(t),Nf=Symbol("bodyBufferedBeforeDisconnect"),Mf=Symbol("bodyBufferedLengthBeforeDisconnect"),c0=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Uf=t=>!(t instanceof Xn)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&pO(t.readableEncoding),e0=t=>{if(t.readableDidRead||!Uf(t))return;let e=t;e[Mf]??=t.readableLength},_a=(t,e)=>{if(t.readableDidRead&&!e||!Uf(t))return;let r=t;if(r[Nf]!==void 0)return r[Nf];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Mf]!==void 0&&t.readableLength!==r[Mf])n=va();else{let s=e??[],i=t.read();i!==null&&s.push(c0(i,t.readableEncoding));let a=s.length===1?s[0]:Buffer.concat(s);n=a;let c=t.headers["content-length"];if(typeof c=="string"&&/^\d+$/.test(c)){let u=Number(c);Number.isSafeInteger(u)&&a.length!==u&&(n=va())}}return r[Nf]=n,n},t0=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},mO=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new Yn(e,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[a0]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=_a(n);if(l!==void 0){t0(a,l);return}}i||=Qv.toWeb(n).getReader();let{done:c,value:u}=await i.read();c?a.close():a.enqueue(u)}catch(c){a.error(c)}}})}else{let i=_a(n);i!==void 0?s.body=new ReadableStream({start(a){t0(a,i)}}):s.body=Qv.toWeb(n)}return new Yn(e,s)},vr=Symbol("getRequestCache"),Kt=Symbol("requestCache"),Qn=Symbol("incomingKey"),ds=Symbol("urlKey"),u0=Symbol("methodKey"),l0=Symbol("headersKey"),us=Symbol("abortControllerKey"),jf=Symbol("getAbortController"),Zf=Symbol("abortRequest"),_r=Symbol("bodyBuffer"),ya=Symbol("bodyReadPromise"),Xt=Symbol("bodyConsumedDirectly"),r0=Symbol("bodyLockReader"),ls=Symbol("abortReason"),va=()=>new TypeError("Body is unusable"),fs=()=>Promise.reject(va()),hO=new TextDecoder,gO=t=>{if(t[Xt])return fs();t[Xt]=!0},yO=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),_O=t=>(t[l0]||=i0(t[Qn])).get("content-type")||"",vO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,xO=t=>{if(typeof t!="string"||t.length===0)return"GET";switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"PATCH":case"POST":case"PUT":case"QUERY":return t}let e=t.toUpperCase();switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return e;default:return t}},bO=t=>{if(!vO.test(t))return new TypeError(`'${t}' is not a valid HTTP method.`);let e=t.toUpperCase();if(e==="CONNECT"||e==="TRACK"||e==="TRACE"&&t!=="TRACE")return new TypeError(`'${t}' HTTP method is unsupported.`)},Ff=(t,e,r)=>{if(t[Xt])return fs();let n=t.method;if(n==="GET"||n==="HEAD")return t[vr]()[e]();let o=bO(n);if(o)return Promise.reject(o);if(t[Kt]&&n!=="TRACE")return t[Kt][e]();let s=gO(t);if(s)return s;let i=wO(t);if(i){let a=Promise.resolve(r(i,t));return t[_r]=void 0,a}return $O(t).then(a=>{let c=r(a,t);return t[_r]=void 0,c})},wO=t=>{let e=t[Qn];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},n0=(t,e)=>{if(e.errored)return e.errored;let r=t[ls];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},$O=t=>{if(t[_r])return Promise.resolve(t[_r]);if(t[ya])return t[ya];let e=t[Qn];if(e.readableDidRead)return fs();let r=_a(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[_r]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=h=>{a||(a=!0,f(),h())},u=h=>{let y=e.errored??h;return!Uf(e)||y&&y.code!=="ECONNRESET"?!1:(c(()=>{let _=_a(e,i);_ instanceof Error?s(_):_===void 0?s(h??n0(t,e)):(t[_r]=_,o(_))}),!0)},l=h=>{i.push(c0(h,e.readableEncoding))},d=()=>{c(()=>{let h=i.length===1?i[0]:Buffer.concat(i);t[_r]=h,o(h)})},p=h=>{u(h)||c(()=>{s(h)})},m=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(n0(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",p),e.off("close",m),t[ya]=void 0};e.on("data",l),e.on("end",d),e.on("error",p),e.on("close",m),queueMicrotask(()=>{a||(e.readableEnded?d():e.errored?p(e.errored):e.destroyed&&m())})});return t[ya]=n,n},jt={get method(){return this[u0]},get url(){return this[ds]},get headers(){return this[l0]||=i0(this[Qn])},[Zf](t){this[ls]===void 0&&(this[ls]=t);let e=this[us];e&&!e.signal.aborted&&e.abort(t)},[jf](){return this[us]||=new AbortController,this[ls]!==void 0&&!this[us].signal.aborted&&this[us].abort(this[ls]),this[us]},[vr](){let t=this[jf]();if(this[Kt])return this[Kt];let e=this.method;if(this[Xt]&&!(e==="GET"||e==="HEAD")){this[_r]=void 0;let r={method:e==="TRACE"?"GET":e,headers:this.headers,signal:t.signal};e!=="TRACE"&&(r.body=new ReadableStream({start(o){o.close()}}),r.duplex="half");let n=new Yn(this[ds],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[Kt]=n}return this[Kt]=mO(this.method,this[ds],this.headers,this[Qn],t)},get body(){if(!this[Xt])return this[vr]().body;let t=this[vr]();return!this[r0]&&t.body&&(this[r0]=t.body.getReader()),t.body},get bodyUsed(){return this[Xt]?!0:this[Kt]?this[Kt].bodyUsed:!1}};Object.defineProperty(jt,"signal",{get(){return this[jf]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(jt,t,{get(){return this[vr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(jt,t,{value:function(){if(this[Xt]){if(t==="clone")throw va();return fs()}return this[vr]()[t]()}})});Object.defineProperty(jt,"text",{value:function(){return Ff(this,"text",t=>hO.decode(t))}});Object.defineProperty(jt,"arrayBuffer",{value:function(){return Ff(this,"arrayBuffer",t=>yO(t))}});Object.defineProperty(jt,"blob",{value:function(){return Ff(this,"blob",(t,e)=>{let r=_O(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(jt,"json",{value:function(){return this[Xt]?fs():this.text().then(JSON.parse)}});Object.defineProperty(jt,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Request (lightweight) ${r({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Kt]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(jt,Yn.prototype);kO=(t,e)=>{let r=Object.create(jt);r[Qn]=t,r[u0]=xO(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof Xn)throw new Nt("Absolute URL for :path is not allowed in HTTP/2");try{r[ds]=new URL(n).href}catch(i){throw new Nt("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof Xn?t.authority:t.headers.host)||e;if(!o)throw new Nt("Missing host header");let s;if(t instanceof Xn){if(s=t.scheme,!(s==="http"||s==="https"))throw new Nt("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[ds]=uO(s,o,n)}catch(i){throw i instanceof Nt?i:new Nt("Invalid URL",{cause:i})}return r},yr="text/plain; charset=UTF-8",Df=Symbol("responseCache"),Gn=Symbol("getResponseCache"),Gt=Symbol("cache"),xa=global.Response,Mt=class d0{#e;#t;[Gn](){let e=this[Gt],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[Gt],this[Df]||=new xa(this.#e,r?{status:this.#t?.status,statusText:this.#t?.statusText,headers:r}:this.#t)}constructor(e,r){let n;if(this.#e=e,r instanceof xa){let o=r[Df];if(o){this.#t=o,this[Gn]();return}this.#t=r instanceof d0?r.#t:r,n=new Headers(r.headers)}else this.#t=r;(e==null||typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(this[Gt]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[Gt];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":yr}))),e[2]):this[Gn]().headers}get status(){return this[Gt]?.[0]??this[Gn]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Mt.prototype,t,{get(){return this[Gn]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Mt.prototype,t,{value:function(){return this[Gn]()[t]()}})});Object.defineProperty(Mt.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Response (lightweight) ${r({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Df]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Mt,xa);Object.setPrototypeOf(Mt.prototype,xa.prototype);SO=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,EO=t=>t instanceof URL?t.href:SO.test(t)?t:new URL(t).href,TO=new Set([301,302,303,307,308]);Object.defineProperty(Mt,"redirect",{value:function(e,r=302){if(!TO.has(r))throw new RangeError("Invalid status code");return new Mt(null,{status:r,headers:{location:EO(e)}})},writable:!0,configurable:!0});Object.defineProperty(Mt,"json",{value:function(e,r){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("The data is not JSON serializable");let o=r?.headers,s;return o?(s=new Headers(o),s.has("content-type")||s.set("content-type","application/json")):s={"content-type":"application/json"},new Mt(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});qf=(t,e)=>{let r={};if(t instanceof Headers||(t=new Headers(t??void 0)),t.has("set-cookie")){let n=[];for(let[o,s]of t)o==="set-cookie"?n.push(s):r[o]=s;n.length>0&&(r["set-cookie"]=n)}else for(let[n,o]of t)r[n]=o;return e&&(r["content-type"]??=e),r},ba=Symbol("outgoingEnded"),s0=Symbol("incomingDraining"),PO=500,RO=64*1024*1024,p0=t=>{let e=t;if(t.destroyed||e[s0])return;if(e[s0]=!0,t instanceof Xn){try{t.stream?.close?.(sO.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),t.off("data",i),t.off("end",n),t.off("error",n)},o=()=>{n();let a=t.socket;a&&!a.destroyed&&(typeof a.destroySoon=="function"?a.destroySoon():typeof a.destroy=="function"&&a.destroy())},s=setTimeout(o,PO);s.unref?.();let i=a=>{r+=a.length,r>RO&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},IO=(t,e,r,n)=>()=>{e.errored?(e0(e),t[Zf](e.errored.toString())):r.writableFinished||(e0(e),t[Zf]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{p0(e)})})},OO=t=>{if(!(Gt in t))return!1;let e=t[Gt][1];return e===null||typeof e=="string"||e instanceof Uint8Array},CO=()=>new Response(null,{status:400}),m0=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),wa=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},Lf=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},h0=async(t,e)=>{let[r,n,o]=t[Gt];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(e.writeHead(r,{"Content-Type":yr,"Content-Length":Buffer.byteLength(n)}),e.end(n)):n instanceof Uint8Array?(e.writeHead(r,{"Content-Type":yr,"Content-Length":n.byteLength}),e.end(n)):n instanceof Blob?(e.writeHead(r,{"Content-Type":yr,"Content-Length":n.size}),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":yr}),Lf(e),await o0(n,e)?.catch(i=>wa(i,e))),e[ba]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=qf(o,n===null?void 0:yr);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=qf(i,n===null?void 0:yr)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),e.writeHead(r,o),n==null?e.end():typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(Lf(e),await o0(n,e)?.catch(i=>wa(i,e))),e[ba]?.()},g0=t=>typeof t.then=="function",AO=async(t,e,r={})=>{if(g0(t))if(r.errorHandler)try{t=await t}catch(o){let s=await r.errorHandler(o);if(!s)return;t=s}else t=await t.catch(m0);if(Gt in t)return h0(t,e);let n=qf(t.headers,t.body===null?void 0:yr);if(t.body){let o=t.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let u=0;u<c;u++){a||=o.read();let l=await zO(a).catch(d=>{console.error(d),i=!0});if(!l){if(u===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,l.value&&s.push(l.value),l.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((u,l)=>u+l.length,0))}e.writeHead(t.status,n),s.forEach(c=>{e.write(c)}),i?e.end():(s.length===0&&Lf(e),await f0(o,e,a))}else n[Kv]||(e.writeHead(t.status,n),e.end());e[ba]?.()},Hf=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==Yn&&(Object.defineProperty(global,"Request",{value:Yn}),Object.defineProperty(global,"Response",{value:Mt})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",IO(i,n,o,a)))};try{if(i=kO(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[a0]=!0,n instanceof Xn&&(o[ba]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!g0(s)&&OO(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||p0(n)}),h0(s,o);u()}catch(l){if(s)return wa(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:lO(l)),!s)return}else i?s=m0(l):s=CO()}try{return await AO(s,o,e)}catch(l){return wa(l,o)}}},NO=globalThis.CloseEvent??class extends Event{#e;constructor(t,e={}){super(t,e),this.#e=e}get wasClean(){return this.#e.wasClean??!1}get code(){return this.#e.code??0}get reason(){return this.#e.reason??""}},MO=globalThis.ErrorEvent??class extends Event{#e;constructor(t,e={}){super(t,e),this.#e=e}get message(){return this.#e.message??""}get filename(){return this.#e.filename??""}get lineno(){return this.#e.lineno??0}get colno(){return this.#e.colno??0}get error(){return this.#e.error??null}},jO=()=>Symbol("connection"),ZO=Symbol("CONNECTION_SYMBOL_KEY"),DO=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),X2=Xv(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[DO];if(!o||!n.incoming)return new Response(null,{status:500});let s=jO();return n[ZO]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,p)=>{a.push([d,p])};i.on("message",c);let u={binaryType:"arraybuffer",close(d,p){i.close(d,p)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,p){i.send(d,{compress:p?.compress})},url:new URL(t.req.url)};try{e?.onOpen?.(new Event("open"),u)}catch(d){(r?.onError??console.error)(d)}let l=(d,p)=>{let m=Array.isArray(d)?d:[d];for(let f of m)try{e?.onMessage?.(new MessageEvent("message",{data:p?f instanceof ArrayBuffer?f:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength):typeof f=="string"?f:Buffer.from(f).toString("utf-8")}),u)}catch(h){(r?.onError??console.error)(h)}};i.off("message",c);for(let d of a)l(...d);i.on("message",(d,p)=>{l(d,p)}),i.on("close",(d,p)=>{try{e?.onClose?.(new NO("close",{code:d,reason:p.toString()}),u)}catch(m){(r?.onError??console.error)(m)}}),i.on("error",d=>{try{e?.onError?.(new MO("error",{error:d}),u)}catch(p){(r?.onError??console.error)(p)}})})(),new Response})});var b0=T(Vf=>{"use strict";var _0=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,qO=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,v0=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,LO=/\\([\u000b\u0020-\u00ff])/g,UO=/([\\"])/g,x0=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Vf.format=FO;Vf.parse=HO;function FO(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!x0.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var o,s=Object.keys(e).sort(),i=0;i<s.length;i++){if(o=s[i],!v0.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+BO(e[o])}return n}function HO(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?VO(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),n=r!==-1?e.slice(0,r).trim():e.trim();if(!x0.test(n))throw new TypeError("invalid media type");var o=new JO(n.toLowerCase());if(r!==-1){var s,i,a;for(_0.lastIndex=r;i=_0.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,s=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(LO,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function VO(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function BO(t){var e=String(t);if(v0.test(e))return e;if(e.length>0&&!qO.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(UO,"\\$1")+'"'}function JO(t){this.parameters=Object.create(null),this.type=t}});function WO(t){if(t)try{return w0.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function $0(t){return t==="application/json"?!0:WO(t)==="application/json"}var w0,k0=G(()=>{w0=Sa(b0(),1)});function S0(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var E0=G(()=>{});var $a,T0=G(()=>{k0();E0();Vr();$a=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._resumableStreams=new Set,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this._closed=!1,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._keepAliveMs=e.keepAliveMs??15e3}startKeepAlive(e,r){if(this._closed)return;let n=S0(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
37
+ deps: ${r}}`};var TP={keyword:"dependencies",type:"object",schemaType:"object",error:Ot.error,code(t){let[e,r]=zP(t);i_(t,e),a_(t,r)}};function zP({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function i_(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,os.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,os.checkReportMissingProp)(t,u)}):(r.if((0,Ud._)`${c} && (${(0,os.checkMissingProp)(t,a,s)})`),(0,os.reportMissingProp)(t,s),r.else())}}Ot.validatePropertyDeps=i_;function a_(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,EP.alwaysValidSchema)(s,e[a])||(r.if((0,os.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ot.validateSchemaDeps=a_;Ot.default=TP});var l_=T(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var u_=B(),PP=re(),RP={message:"property name must be valid",params:({params:t})=>(0,u_._)`{propertyName: ${t.propertyName}}`},IP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:RP,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,PP.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,u_.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Fd.default=IP});var Vd=T(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Vi=ut(),bt=B(),OP=Jt(),Bi=re(),CP={message:"must NOT have additional properties",params:({params:t})=>(0,bt._)`{additionalProperty: ${t.additionalProperty}}`},AP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:CP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Bi.alwaysValidSchema)(i,r))return;let u=(0,Vi.allSchemaProperties)(n.properties),l=(0,Vi.allSchemaProperties)(n.patternProperties);d(),t.ok((0,bt._)`${s} === ${OP.default.errors}`);function d(){e.forIn("key",o,y=>{!u.length&&!l.length?f(y):e.if(p(y),()=>f(y))})}function p(y){let _;if(u.length>8){let v=(0,Bi.schemaRefOrVal)(i,n.properties,"properties");_=(0,Vi.isOwnProperty)(e,v,y)}else u.length?_=(0,bt.or)(...u.map(v=>(0,bt._)`${y} === ${v}`)):_=bt.nil;return l.length&&(_=(0,bt.or)(_,...l.map(v=>(0,bt._)`${(0,Vi.usePattern)(t,v)}.test(${y})`))),(0,bt.not)(_)}function m(y){e.code((0,bt._)`delete ${o}[${y}]`)}function f(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Bi.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(h(y,_,!1),e.if((0,bt.not)(_),()=>{t.reset(),m(y)})):(h(y,_),a||e.if((0,bt.not)(_),()=>e.break()))}}function h(y,_,v){let g={keyword:"additionalProperties",dataProp:y,dataPropType:Bi.Type.Str};v===!1&&Object.assign(g,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(g,_)}}};Hd.default=AP});var p_=T(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var NP=Fo(),d_=ut(),Bd=re(),f_=Vd(),MP={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&f_.default.code(new NP.KeywordCxt(s,f_.default,"additionalProperties"));let i=(0,d_.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Bd.mergeEvaluated.props(e,(0,Bd.toHash)(i),s.props));let a=i.filter(d=>!(0,Bd.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,d_.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Jd.default=MP});var y_=T(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var m_=ut(),Ji=B(),h_=re(),g_=re(),jP={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,m_.allSchemaProperties)(r),c=a.filter(h=>(0,h_.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Ji.Name)&&(s.props=(0,g_.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&m(h),s.allErrors?f(h):(e.var(l,!0),f(h),e.if(l))}function m(h){for(let y in u)new RegExp(h).test(y)&&(0,h_.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",n,y=>{e.if((0,Ji._)`${(0,m_.usePattern)(t,h)}.test(${y})`,()=>{let _=c.includes(h);_||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:g_.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ji._)`${d}[${y}]`,!0):!_&&!s.allErrors&&e.if((0,Ji.not)(l),()=>e.break())})})}}};Wd.default=jP});var __=T(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var ZP=re(),DP={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,ZP.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Kd.default=DP});var v_=T(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var qP=ut(),LP={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:qP.validateUnion,error:{message:"must match a schema in anyOf"}};Gd.default=LP});var x_=T(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var Wi=B(),UP=re(),FP={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Wi._)`{passingSchemas: ${t.passing}}`},HP={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:FP,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,UP.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Wi._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Wi._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Wi.Name)})})}}};Xd.default=HP});var b_=T(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var VP=re(),BP={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,VP.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Yd.default=BP});var k_=T(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var Ki=B(),$_=re(),JP={message:({params:t})=>(0,Ki.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ki._)`{failingKeyword: ${t.ifClause}}`},WP={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:JP,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,$_.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=w_(n,"then"),s=w_(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Ki.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Ki._)`${l}`):t.setParams({ifClause:l})}}}};function w_(t,e){let r=t.schema[e];return r!==void 0&&!(0,$_.alwaysValidSchema)(t,r)}Qd.default=WP});var S_=T(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var KP=re(),GP={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,KP.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ef.default=GP});var E_=T(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var XP=jd(),YP=r_(),QP=Zd(),eR=o_(),tR=s_(),rR=c_(),nR=l_(),oR=Vd(),sR=p_(),iR=y_(),aR=__(),cR=v_(),uR=x_(),lR=b_(),dR=k_(),fR=S_();function pR(t=!1){let e=[aR.default,cR.default,uR.default,lR.default,dR.default,fR.default,nR.default,oR.default,rR.default,sR.default,iR.default];return t?e.push(YP.default,eR.default):e.push(XP.default,QP.default),e.push(tR.default),e}tf.default=pR});var T_=T(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var ke=B(),mR={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},hR={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:mR,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():m();function p(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ke._)`${f}[${i}]`),y=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,ke._)`${h}.type || "string"`).assign(_,(0,ke._)`${h}.validate`),()=>r.assign(y,(0,ke._)`"string"`).assign(_,h)),t.fail$data((0,ke.or)(v(),g()));function v(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function g(){let x=l.$async?(0,ke._)`(${h}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,$=(0,ke._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${y} === ${e} && !${$}`}}function m(){let f=d.formats[s];if(!f){v();return}if(f===!0)return;let[h,y,_]=g(f);h===e&&t.pass(x());function v(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function g($){let D=$ instanceof RegExp?(0,ke.regexpCode)($):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,R=r.scopeValue("formats",{key:s,ref:$,code:D});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,ke._)`${R}.validate`]:["string",$,R]}function x(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${_}(${n})`}return typeof y=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};rf.default=hR});var z_=T(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var gR=T_(),yR=[gR.default];nf.default=yR});var P_=T(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.contentVocabulary=Ln.metadataVocabulary=void 0;Ln.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ln.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var I_=T(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var _R=Zy(),vR=Yy(),xR=E_(),bR=z_(),R_=P_(),wR=[_R.default,vR.default,(0,xR.default)(),bR.default,R_.metadataVocabulary,R_.contentVocabulary];of.default=wR});var C_=T(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.DiscrError=void 0;var O_;(function(t){t.Tag="tag",t.Mapping="mapping"})(O_||(Gi.DiscrError=O_={}))});var N_=T(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var Un=B(),sf=C_(),A_=Ii(),$R=Ho(),kR=re(),SR={message:({params:{discrError:t,tagName:e}})=>t===sf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Un._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},ER={keyword:"discriminator",type:"object",schemaType:"object",error:SR,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Un._)`${r}${(0,Un.getProperty)(a)}`);e.if((0,Un._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:sf.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let m=p();e.if(!1);for(let f in m)e.elseIf((0,Un._)`${u} === ${f}`),e.assign(c,d(m[f]));e.else(),t.error(!1,{discrError:sf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(m){let f=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:m},f);return t.mergeEvaluated(h,Un.Name),f}function p(){var m;let f={},h=_(o),y=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,kR.schemaHasRulesButRef)($,s.self.RULES)){let R=$.$ref;if($=A_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),$ instanceof A_.SchemaEnv&&($=$.schema),$===void 0)throw new $R.default(s.opts.uriResolver,s.baseId,R)}let D=(m=$?.properties)===null||m===void 0?void 0:m[a];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||_($)),v(D,x)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return f;function _({required:x}){return Array.isArray(x)&&x.includes(a)}function v(x,$){if(x.const)g(x.const,$);else if(x.enum)for(let D of x.enum)g(D,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function g(x,$){if(typeof x!="string"||x in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[x]=$}}}};af.default=ER});var M_=T((gD,TR)=>{TR.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}});var uf=T((ye,cf)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var zR=Oy(),PR=I_(),RR=N_(),j_=M_(),IR=["/properties"],Xi="http://json-schema.org/draft-07/schema",Fn=class extends zR.default{_addVocabularies(){super._addVocabularies(),PR.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(RR.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(j_,IR):j_;this.addMetaSchema(e,Xi,!1),this.refs["http://json-schema.org/schema"]=Xi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Xi)?Xi:void 0)}};ye.Ajv=Fn;cf.exports=ye=Fn;cf.exports.Ajv=Fn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Fn;var OR=Fo();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return OR.KeywordCxt}});var Hn=B();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Hn._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Hn.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Hn.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Hn.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Hn.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Hn.CodeGen}});var CR=Pi();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return CR.default}});var AR=Ho();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return AR.default}})});var V_=T(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.formatNames=At.fastFormats=At.fullFormats=void 0;function Ct(t,e){return{validate:t,compare:e}}At.fullFormats={date:Ct(L_,pf),time:Ct(df(!0),mf),"date-time":Ct(Z_(!0),F_),"iso-time":Ct(df(),U_),"iso-date-time":Ct(Z_(),H_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:qR,"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:JR,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:LR,int32:{type:"number",validate:HR},int64:{type:"number",validate:VR},float:{type:"number",validate:q_},double:{type:"number",validate:q_},password:!0,binary:!0};At.fastFormats={...At.fullFormats,date:Ct(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,pf),time:Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,mf),"date-time":Ct(/^\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,F_),"iso-time":Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,U_),"iso-date-time":Ct(/^\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,H_),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};At.formatNames=Object.keys(At.fullFormats);function NR(t){return t%4===0&&(t%100!==0||t%400===0)}var MR=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,jR=[0,31,28,31,30,31,30,31,31,30,31,30,31];function L_(t){let e=MR.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&NR(r)?29:jR[n])}function pf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var lf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function df(t){return function(r){let n=lf.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function mf(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function U_(t,e){if(!(t&&e))return;let r=lf.exec(t),n=lf.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var ff=/t|\s/i;function Z_(t){let e=df(t);return function(n){let o=n.split(ff);return o.length===2&&L_(o[0])&&e(o[1])}}function F_(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function H_(t,e){if(!(t&&e))return;let[r,n]=t.split(ff),[o,s]=e.split(ff),i=pf(r,o);if(i!==void 0)return i||mf(n,s)}var ZR=/\/|:/,DR=/^(?:[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 qR(t){return ZR.test(t)&&DR.test(t)}var D_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function LR(t){return D_.lastIndex=0,D_.test(t)}var UR=-(2**31),FR=2**31-1;function HR(t){return Number.isInteger(t)&&t<=FR&&t>=UR}function VR(t){return Number.isInteger(t)}function q_(){return!0}var BR=/[^\\]\\Z/;function JR(t){if(BR.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var B_=T(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.formatLimitDefinition=void 0;var WR=uf(),wt=B(),hr=wt.operators,Yi={formatMaximum:{okStr:"<=",ok:hr.LTE,fail:hr.GT},formatMinimum:{okStr:">=",ok:hr.GTE,fail:hr.LT},formatExclusiveMaximum:{okStr:"<",ok:hr.LT,fail:hr.GTE},formatExclusiveMinimum:{okStr:">",ok:hr.GT,fail:hr.LTE}},KR={message:({keyword:t,schemaCode:e})=>(0,wt.str)`should be ${Yi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wt._)`{comparison: ${Yi[t].okStr}, limit: ${e}}`};Vn.formatLimitDefinition={keyword:Object.keys(Yi),type:"string",schemaType:"string",$data:!0,error:KR,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new WR.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,wt._)`${p}[${c.schemaCode}]`);t.fail$data((0,wt.or)((0,wt._)`typeof ${m} != "object"`,(0,wt._)`${m} instanceof RegExp`,(0,wt._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let p=c.schema,m=a.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let f=e.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,wt._)`${i.code.formats}${(0,wt.getProperty)(p)}`:void 0});t.fail$data(d(f))}function d(p){return(0,wt._)`${p}.compare(${r}, ${n}) ${Yi[o].fail} 0`}},dependencies:["format"]};var GR=t=>(t.addKeyword(Vn.formatLimitDefinition),t);Vn.default=GR});var G_=T((ss,K_)=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});var Bn=V_(),XR=B_(),hf=B(),J_=new hf.Name("fullFormats"),YR=new hf.Name("fastFormats"),gf=(t,e={keywords:!0})=>{if(Array.isArray(e))return W_(t,e,Bn.fullFormats,J_),t;let[r,n]=e.mode==="fast"?[Bn.fastFormats,YR]:[Bn.fullFormats,J_],o=e.formats||Bn.formatNames;return W_(t,o,r,n),e.keywords&&(0,XR.default)(t),t};gf.get=(t,e="full")=>{let n=(e==="fast"?Bn.fastFormats:Bn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function W_(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,hf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}K_.exports=ss=gf;Object.defineProperty(ss,"__esModule",{value:!0});ss.default=gf});var qv={};eo(qv,{findEmbeddingModel:()=>Dv,ollamaUrl:()=>If,semanticRerank:()=>RI});import{createHash as vI}from"node:crypto";import{existsSync as xI,mkdirSync as bI,readFileSync as wI,writeFileSync as $I}from"node:fs";import{homedir as kI}from"node:os";import{join as Rf}from"node:path";function If(t=process.env.OLLAMA_HOST){let e=(t??"").trim(),r="http",n="11434",o=e.indexOf("://");o>=0&&(r=e.slice(0,o),e=e.slice(o+3),r==="http"?n="80":r==="https"&&(n="443"));let s=e.indexOf("/"),i=s>=0?e.slice(s).replace(/\/+$/,""):"",a=s>=0?e.slice(0,s):e,c=/^(\[[^\]]*\]|[^:]*):([^:]*)$/.exec(a);return c?(a=c[1],/^\d+$/.test(c[2])&&Number(c[2])<=65535&&(n=c[2])):a.includes(":")&&!a.startsWith("[")&&(a=`[${a}]`),!a||a==="0.0.0.0"?a="127.0.0.1":a==="[::]"&&(a="[::1]"),`${r}://${a}:${n}${i}`}async function Zv(t,e,r=6e4){let n=await fetch(If()+t,{method:e?"POST":"GET",headers:e?{"content-type":"application/json"}:void 0,body:e?JSON.stringify(e):void 0,signal:AbortSignal.timeout(r)});if(!n.ok)throw new Error(`${t}: HTTP ${n.status}`);return n.json()}async function Dv(t){let r=((await Zv("/api/tags",void 0,2e3)).models??[]).map(n=>String(n.name));return t?r.find(n=>n===t||n.startsWith(t+":"))??t:r.find(n=>SI.test(n))}function ma(){return Rf(process.env.XDG_CACHE_HOME??Rf(kI(),".cache"),"context-doctor","embeddings.json")}function EI(){try{return xI(ma())?JSON.parse(wI(ma(),"utf8")):{}}catch{return{}}}function TI(t){try{let e=Object.keys(t);if(e.length>jv)for(let r of e.slice(0,e.length-jv))delete t[r];bI(Rf(ma(),".."),{recursive:!0}),$I(ma(),JSON.stringify(t))}catch{}}async function zI(t,e){let r=[];for(let n=0;n<e.length;n+=Mv){let o=await Zv("/api/embed",{model:t,input:e.slice(n,n+Mv),truncate:!0});r.push(...o.embeddings)}return r}function PI(t,e){let r=0,n=0,o=0;for(let s=0;s<t.length;s++)r+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return n&&o?r/Math.sqrt(n*o):0}async function RI(t,e,r={}){let n;try{n=await Dv(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${If()} (keyword ranking only)`}}if(!n)return{used:!1,note:"semantic ranking off: Ollama has no embedding model; run `ollama pull nomic-embed-text` (keyword ranking only)"};let o=EI(),s=f=>vI("sha1").update(n+"\0"+f).digest("hex"),i=t.map(f=>(f.heading?f.heading+`
38
+ `:"")+f.text),a=[...new Set(i.filter(f=>!o[s(f)]))],c,u;try{let f=await zI(n,[e,...a]);u=f[0],a.forEach((h,y)=>o[s(h)]=f[y+1]),c=i.map(h=>o[s(h)])}catch(f){return{used:!1,model:n,note:`semantic ranking off: ${n} failed (${f.message}); keyword ranking only`}}a.length&&TI(o);let l=60,d=new Map([...t].filter(f=>f.score>0).sort((f,h)=>h.score-f.score).map((f,h)=>[f,h])),p=t.map((f,h)=>({c:f,s:PI(u,c[h])})).sort((f,h)=>h.s-f.s),m=new Map(p.map((f,h)=>[f.c,h]));for(let f of t){let h=d.get(f);f.score=(h===void 0?0:1/(l+h))+1/(l+m.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var SI,Mv,jv,Lv=G(()=>{"use strict";SI=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,Mv=64,jv=5e4});var Xv,Yv=G(()=>{Xv="x-hono-already-sent"});var Qv,e0=G(()=>{Qv=t=>((...e)=>{if(typeof e[0]=="function"){let[r,n]=e;return async function(s,i){let a=await t(s,await r(s),n);if(a)return a;await i()}}else{let[r,n,o]=e;return(async()=>{let s=await t(r,n,o);if(!s)throw new Error("Failed to upgrade WebSocket");return s})()}})});import{Http2ServerRequest as Xn,constants as aO}from"node:http2";import{Readable as t0}from"node:stream";async function RO(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function m0(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(i,o),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function o(a){a&&e.destroy(a)}function s(){t.read().then(i,o)}function i({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",s);else return t.read().then(i,o)}catch(u){o(u)}}}function i0(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:m0(t.getReader(),e)}var Nt,cO,uO,lO,dO,fO,pO,Yn,c0,u0,mO,hO,Mf,jf,l0,Ff,r0,va,n0,gO,vr,Kt,Qn,ds,d0,f0,us,Zf,Df,_r,_a,Xt,o0,ls,xa,fs,yO,_O,vO,xO,bO,wO,$O,Hf,kO,s0,SO,jt,EO,yr,qf,Gn,Gt,ba,Mt,TO,zO,PO,Lf,wa,a0,IO,OO,h0,CO,AO,NO,g0,$a,Uf,y0,_0,MO,Vf,jO,ZO,DO,qO,LO,Q2,v0=G(()=>{Yv();e0();Nt=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},cO=/^\/[!#$&-;=?-\[\]_a-z~]*$/,uO=/\/\.\.?(?:[/?#]|$)/,lO=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,dO=(t,e,r)=>{let n=`${t}://${e}${r}`;if(lO.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Nt("Invalid URL");return!cO.test(r)||uO.test(r)?new URL(n).href:n}else{let o=new URL(n);if(o.hostname.length!==e.length&&o.hostname!==(e.includes(":")?e.replace(/:\d+$/,""):e).toLowerCase())throw new Nt("Invalid host header");return o.href}},fO=t=>t instanceof Nt?t:new Nt(t.message,{cause:t}),pO=global.Request,Yn=class extends pO{constructor(t,e){if(typeof t=="object"&&vr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[Xt]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[vr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},c0=t=>{let e=[],r=t.rawHeaders;for(let n=0,o=r.length;n<o;n+=2){let s=r[n];s.charCodeAt(0)!==58&&e.push([s,r[n+1]])}return new Headers(e)},u0=Symbol("wrapBodyStream"),mO=new Set(["latin1","binary","hex","base64","base64url"]),hO=t=>t===null||mO.has(t),Mf=Symbol("bodyBufferedBeforeDisconnect"),jf=Symbol("bodyBufferedLengthBeforeDisconnect"),l0=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Ff=t=>!(t instanceof Xn)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&hO(t.readableEncoding),r0=t=>{if(t.readableDidRead||!Ff(t))return;let e=t;e[jf]??=t.readableLength},va=(t,e)=>{if(t.readableDidRead&&!e||!Ff(t))return;let r=t;if(r[Mf]!==void 0)return r[Mf];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[jf]!==void 0&&t.readableLength!==r[jf])n=xa();else{let s=e??[],i=t.read();i!==null&&s.push(l0(i,t.readableEncoding));let a=s.length===1?s[0]:Buffer.concat(s);n=a;let c=t.headers["content-length"];if(typeof c=="string"&&/^\d+$/.test(c)){let u=Number(c);Number.isSafeInteger(u)&&a.length!==u&&(n=xa())}}return r[Mf]=n,n},n0=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},gO=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new Yn(e,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[u0]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=va(n);if(l!==void 0){n0(a,l);return}}i||=t0.toWeb(n).getReader();let{done:c,value:u}=await i.read();c?a.close():a.enqueue(u)}catch(c){a.error(c)}}})}else{let i=va(n);i!==void 0?s.body=new ReadableStream({start(a){n0(a,i)}}):s.body=t0.toWeb(n)}return new Yn(e,s)},vr=Symbol("getRequestCache"),Kt=Symbol("requestCache"),Qn=Symbol("incomingKey"),ds=Symbol("urlKey"),d0=Symbol("methodKey"),f0=Symbol("headersKey"),us=Symbol("abortControllerKey"),Zf=Symbol("getAbortController"),Df=Symbol("abortRequest"),_r=Symbol("bodyBuffer"),_a=Symbol("bodyReadPromise"),Xt=Symbol("bodyConsumedDirectly"),o0=Symbol("bodyLockReader"),ls=Symbol("abortReason"),xa=()=>new TypeError("Body is unusable"),fs=()=>Promise.reject(xa()),yO=new TextDecoder,_O=t=>{if(t[Xt])return fs();t[Xt]=!0},vO=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),xO=t=>(t[f0]||=c0(t[Qn])).get("content-type")||"",bO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,wO=t=>{if(typeof t!="string"||t.length===0)return"GET";switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"PATCH":case"POST":case"PUT":case"QUERY":return t}let e=t.toUpperCase();switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return e;default:return t}},$O=t=>{if(!bO.test(t))return new TypeError(`'${t}' is not a valid HTTP method.`);let e=t.toUpperCase();if(e==="CONNECT"||e==="TRACK"||e==="TRACE"&&t!=="TRACE")return new TypeError(`'${t}' HTTP method is unsupported.`)},Hf=(t,e,r)=>{if(t[Xt])return fs();let n=t.method;if(n==="GET"||n==="HEAD")return t[vr]()[e]();let o=$O(n);if(o)return Promise.reject(o);if(t[Kt]&&n!=="TRACE")return t[Kt][e]();let s=_O(t);if(s)return s;let i=kO(t);if(i){let a=Promise.resolve(r(i,t));return t[_r]=void 0,a}return SO(t).then(a=>{let c=r(a,t);return t[_r]=void 0,c})},kO=t=>{let e=t[Qn];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},s0=(t,e)=>{if(e.errored)return e.errored;let r=t[ls];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},SO=t=>{if(t[_r])return Promise.resolve(t[_r]);if(t[_a])return t[_a];let e=t[Qn];if(e.readableDidRead)return fs();let r=va(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[_r]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=h=>{a||(a=!0,f(),h())},u=h=>{let y=e.errored??h;return!Ff(e)||y&&y.code!=="ECONNRESET"?!1:(c(()=>{let _=va(e,i);_ instanceof Error?s(_):_===void 0?s(h??s0(t,e)):(t[_r]=_,o(_))}),!0)},l=h=>{i.push(l0(h,e.readableEncoding))},d=()=>{c(()=>{let h=i.length===1?i[0]:Buffer.concat(i);t[_r]=h,o(h)})},p=h=>{u(h)||c(()=>{s(h)})},m=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(s0(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",p),e.off("close",m),t[_a]=void 0};e.on("data",l),e.on("end",d),e.on("error",p),e.on("close",m),queueMicrotask(()=>{a||(e.readableEnded?d():e.errored?p(e.errored):e.destroyed&&m())})});return t[_a]=n,n},jt={get method(){return this[d0]},get url(){return this[ds]},get headers(){return this[f0]||=c0(this[Qn])},[Df](t){this[ls]===void 0&&(this[ls]=t);let e=this[us];e&&!e.signal.aborted&&e.abort(t)},[Zf](){return this[us]||=new AbortController,this[ls]!==void 0&&!this[us].signal.aborted&&this[us].abort(this[ls]),this[us]},[vr](){let t=this[Zf]();if(this[Kt])return this[Kt];let e=this.method;if(this[Xt]&&!(e==="GET"||e==="HEAD")){this[_r]=void 0;let r={method:e==="TRACE"?"GET":e,headers:this.headers,signal:t.signal};e!=="TRACE"&&(r.body=new ReadableStream({start(o){o.close()}}),r.duplex="half");let n=new Yn(this[ds],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[Kt]=n}return this[Kt]=gO(this.method,this[ds],this.headers,this[Qn],t)},get body(){if(!this[Xt])return this[vr]().body;let t=this[vr]();return!this[o0]&&t.body&&(this[o0]=t.body.getReader()),t.body},get bodyUsed(){return this[Xt]?!0:this[Kt]?this[Kt].bodyUsed:!1}};Object.defineProperty(jt,"signal",{get(){return this[Zf]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(jt,t,{get(){return this[vr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(jt,t,{value:function(){if(this[Xt]){if(t==="clone")throw xa();return fs()}return this[vr]()[t]()}})});Object.defineProperty(jt,"text",{value:function(){return Hf(this,"text",t=>yO.decode(t))}});Object.defineProperty(jt,"arrayBuffer",{value:function(){return Hf(this,"arrayBuffer",t=>vO(t))}});Object.defineProperty(jt,"blob",{value:function(){return Hf(this,"blob",(t,e)=>{let r=xO(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(jt,"json",{value:function(){return this[Xt]?fs():this.text().then(JSON.parse)}});Object.defineProperty(jt,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Request (lightweight) ${r({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Kt]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(jt,Yn.prototype);EO=(t,e)=>{let r=Object.create(jt);r[Qn]=t,r[d0]=wO(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof Xn)throw new Nt("Absolute URL for :path is not allowed in HTTP/2");try{r[ds]=new URL(n).href}catch(i){throw new Nt("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof Xn?t.authority:t.headers.host)||e;if(!o)throw new Nt("Missing host header");let s;if(t instanceof Xn){if(s=t.scheme,!(s==="http"||s==="https"))throw new Nt("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[ds]=dO(s,o,n)}catch(i){throw i instanceof Nt?i:new Nt("Invalid URL",{cause:i})}return r},yr="text/plain; charset=UTF-8",qf=Symbol("responseCache"),Gn=Symbol("getResponseCache"),Gt=Symbol("cache"),ba=global.Response,Mt=class p0{#e;#t;[Gn](){let e=this[Gt],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[Gt],this[qf]||=new ba(this.#e,r?{status:this.#t?.status,statusText:this.#t?.statusText,headers:r}:this.#t)}constructor(e,r){let n;if(this.#e=e,r instanceof ba){let o=r[qf];if(o){this.#t=o,this[Gn]();return}this.#t=r instanceof p0?r.#t:r,n=new Headers(r.headers)}else this.#t=r;(e==null||typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(this[Gt]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[Gt];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":yr}))),e[2]):this[Gn]().headers}get status(){return this[Gt]?.[0]??this[Gn]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Mt.prototype,t,{get(){return this[Gn]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Mt.prototype,t,{value:function(){return this[Gn]()[t]()}})});Object.defineProperty(Mt.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Response (lightweight) ${r({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[qf]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Mt,ba);Object.setPrototypeOf(Mt.prototype,ba.prototype);TO=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,zO=t=>t instanceof URL?t.href:TO.test(t)?t:new URL(t).href,PO=new Set([301,302,303,307,308]);Object.defineProperty(Mt,"redirect",{value:function(e,r=302){if(!PO.has(r))throw new RangeError("Invalid status code");return new Mt(null,{status:r,headers:{location:zO(e)}})},writable:!0,configurable:!0});Object.defineProperty(Mt,"json",{value:function(e,r){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("The data is not JSON serializable");let o=r?.headers,s;return o?(s=new Headers(o),s.has("content-type")||s.set("content-type","application/json")):s={"content-type":"application/json"},new Mt(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});Lf=(t,e)=>{let r={};if(t instanceof Headers||(t=new Headers(t??void 0)),t.has("set-cookie")){let n=[];for(let[o,s]of t)o==="set-cookie"?n.push(s):r[o]=s;n.length>0&&(r["set-cookie"]=n)}else for(let[n,o]of t)r[n]=o;return e&&(r["content-type"]??=e),r},wa=Symbol("outgoingEnded"),a0=Symbol("incomingDraining"),IO=500,OO=64*1024*1024,h0=t=>{let e=t;if(t.destroyed||e[a0])return;if(e[a0]=!0,t instanceof Xn){try{t.stream?.close?.(aO.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),t.off("data",i),t.off("end",n),t.off("error",n)},o=()=>{n();let a=t.socket;a&&!a.destroyed&&(typeof a.destroySoon=="function"?a.destroySoon():typeof a.destroy=="function"&&a.destroy())},s=setTimeout(o,IO);s.unref?.();let i=a=>{r+=a.length,r>OO&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},CO=(t,e,r,n)=>()=>{e.errored?(r0(e),t[Df](e.errored.toString())):r.writableFinished||(r0(e),t[Df]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{h0(e)})})},AO=t=>{if(!(Gt in t))return!1;let e=t[Gt][1];return e===null||typeof e=="string"||e instanceof Uint8Array},NO=()=>new Response(null,{status:400}),g0=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),$a=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},Uf=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},y0=async(t,e)=>{let[r,n,o]=t[Gt];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(e.writeHead(r,{"Content-Type":yr,"Content-Length":Buffer.byteLength(n)}),e.end(n)):n instanceof Uint8Array?(e.writeHead(r,{"Content-Type":yr,"Content-Length":n.byteLength}),e.end(n)):n instanceof Blob?(e.writeHead(r,{"Content-Type":yr,"Content-Length":n.size}),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":yr}),Uf(e),await i0(n,e)?.catch(i=>$a(i,e))),e[wa]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=Lf(o,n===null?void 0:yr);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Lf(i,n===null?void 0:yr)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),e.writeHead(r,o),n==null?e.end():typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(Uf(e),await i0(n,e)?.catch(i=>$a(i,e))),e[wa]?.()},_0=t=>typeof t.then=="function",MO=async(t,e,r={})=>{if(_0(t))if(r.errorHandler)try{t=await t}catch(o){let s=await r.errorHandler(o);if(!s)return;t=s}else t=await t.catch(g0);if(Gt in t)return y0(t,e);let n=Lf(t.headers,t.body===null?void 0:yr);if(t.body){let o=t.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let u=0;u<c;u++){a||=o.read();let l=await RO(a).catch(d=>{console.error(d),i=!0});if(!l){if(u===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,l.value&&s.push(l.value),l.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((u,l)=>u+l.length,0))}e.writeHead(t.status,n),s.forEach(c=>{e.write(c)}),i?e.end():(s.length===0&&Uf(e),await m0(o,e,a))}else n[Xv]||(e.writeHead(t.status,n),e.end());e[wa]?.()},Vf=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==Yn&&(Object.defineProperty(global,"Request",{value:Yn}),Object.defineProperty(global,"Response",{value:Mt})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",CO(i,n,o,a)))};try{if(i=EO(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[u0]=!0,n instanceof Xn&&(o[wa]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!_0(s)&&AO(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||h0(n)}),y0(s,o);u()}catch(l){if(s)return $a(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:fO(l)),!s)return}else i?s=g0(l):s=NO()}try{return await MO(s,o,e)}catch(l){return $a(l,o)}}},jO=globalThis.CloseEvent??class extends Event{#e;constructor(t,e={}){super(t,e),this.#e=e}get wasClean(){return this.#e.wasClean??!1}get code(){return this.#e.code??0}get reason(){return this.#e.reason??""}},ZO=globalThis.ErrorEvent??class extends Event{#e;constructor(t,e={}){super(t,e),this.#e=e}get message(){return this.#e.message??""}get filename(){return this.#e.filename??""}get lineno(){return this.#e.lineno??0}get colno(){return this.#e.colno??0}get error(){return this.#e.error??null}},DO=()=>Symbol("connection"),qO=Symbol("CONNECTION_SYMBOL_KEY"),LO=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),Q2=Qv(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[LO];if(!o||!n.incoming)return new Response(null,{status:500});let s=DO();return n[qO]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,p)=>{a.push([d,p])};i.on("message",c);let u={binaryType:"arraybuffer",close(d,p){i.close(d,p)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,p){i.send(d,{compress:p?.compress})},url:new URL(t.req.url)};try{e?.onOpen?.(new Event("open"),u)}catch(d){(r?.onError??console.error)(d)}let l=(d,p)=>{let m=Array.isArray(d)?d:[d];for(let f of m)try{e?.onMessage?.(new MessageEvent("message",{data:p?f instanceof ArrayBuffer?f:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength):typeof f=="string"?f:Buffer.from(f).toString("utf-8")}),u)}catch(h){(r?.onError??console.error)(h)}};i.off("message",c);for(let d of a)l(...d);i.on("message",(d,p)=>{l(d,p)}),i.on("close",(d,p)=>{try{e?.onClose?.(new jO("close",{code:d,reason:p.toString()}),u)}catch(m){(r?.onError??console.error)(m)}}),i.on("error",d=>{try{e?.onError?.(new ZO("error",{error:d}),u)}catch(p){(r?.onError??console.error)(p)}})})(),new Response})});var $0=T(Bf=>{"use strict";var x0=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,UO=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,b0=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,FO=/\\([\u000b\u0020-\u00ff])/g,HO=/([\\"])/g,w0=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Bf.format=VO;Bf.parse=BO;function VO(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!w0.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var o,s=Object.keys(e).sort(),i=0;i<s.length;i++){if(o=s[i],!b0.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+WO(e[o])}return n}function BO(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?JO(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),n=r!==-1?e.slice(0,r).trim():e.trim();if(!w0.test(n))throw new TypeError("invalid media type");var o=new KO(n.toLowerCase());if(r!==-1){var s,i,a;for(x0.lastIndex=r;i=x0.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,s=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(FO,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function JO(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function WO(t){var e=String(t);if(b0.test(e))return e;if(e.length>0&&!UO.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(HO,"\\$1")+'"'}function KO(t){this.parameters=Object.create(null),this.type=t}});function GO(t){if(t)try{return k0.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function S0(t){return t==="application/json"?!0:GO(t)==="application/json"}var k0,E0=G(()=>{k0=Ea($0(),1)});function T0(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var z0=G(()=>{});var ka,P0=G(()=>{E0();z0();Vr();ka=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._resumableStreams=new Set,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this._closed=!1,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._keepAliveMs=e.keepAliveMs??15e3}startKeepAlive(e,r){if(this._closed)return;let n=T0(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
39
39
 
40
40
  `))}catch{n!==void 0&&clearInterval(n)}});return n}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(e,r,n,o){let s={code:r,message:n};return o?.data!==void 0&&(s.data=o.data),new Response(JSON.stringify({jsonrpc:"2.0",error:s,id:null}),{status:e,headers:{"Content-Type":"application/json",...o?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=e.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=e.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(e,r){if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case"POST":return this.handlePostRequest(e,r);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,r,n,o){if(!this._eventStore||o<"2025-11-25")return;let s=await this._eventStore.storeEvent(n,{}),i=`id: ${s}
41
41
  data:
@@ -48,52 +48,52 @@ data:
48
48
  `;return o&&(s+=`id: ${o}
49
49
  `),s+=`data: ${JSON.stringify(n)}
50
50
 
51
- `,e.enqueue(r.encode(s)),!0}catch(s){return this.onerror?.(s),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,r){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!$0(o))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},i;if(r?.parsedBody!==void 0)i=r.parsedBody;else try{i=await e.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let a;try{Array.isArray(i)?a=i.map(v=>xo.parse(v)):a=[xo.parse(i)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let c=a.some(Xu);if(c){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){let v=this.validateSession(e);if(v)return v;let g=this.validateProtocolVersion(e);if(g)return g}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!a.some(Ft)){for(let v of a)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),d=a.find(v=>Xu(v)),p=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??rh;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let g of a)Ft(g)&&this._requestToStreamMapping.set(g.id,l);for(let g of a)this.onmessage?.(g,{authInfo:r?.authInfo,requestInfo:s})});let m=new TextEncoder,f,h,y=new ReadableStream({start:v=>{f=v},cancel:()=>{h!==void 0&&clearInterval(h),this._streamMapping.get(l)?.controller===f&&this._streamMapping.delete(l)}}),_={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(_["mcp-session-id"]=this.sessionId);for(let v of a)Ft(v)&&(this._streamMapping.set(l,{controller:f,encoder:m,cleanup:()=>{h!==void 0&&clearInterval(h),this._streamMapping.delete(l);try{f.close()}catch{}}}),this._requestToStreamMapping.set(v.id,l));try{await this.writePrimingEvent(f,m,l,p);for(let v of a){let g,x;Ft(v)&&this._eventStore&&p>="2025-11-25"&&(g=()=>{this.closeSSEStream(v.id)},x=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:g,closeStandaloneSSEStream:x})}}catch(v){this._streamMapping.get(l)?.cleanup(),this._resumableStreams.delete(l);for(let g of a)Ft(g)&&this._requestToStreamMapping.delete(g.id);throw v}return this._streamMapping.get(l)?.controller===f&&(h=this.startKeepAlive(f,m)),new Response(y,{status:200,headers:_})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(e){let r=this.validateSession(e);if(r)return r;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=e.headers.get("mcp-session-id");if(!r)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let r=e.headers.get("mcp-protocol-version");if(r!==null&&!kn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${kn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${kn.join(", ")})`)}async close(){this._closed||(this._closed=!0,this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this._resumableStreams.clear(),this.onclose?.())}closeSSEStream(e){let r=this._requestToStreamMapping.get(e);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,r){let n=r?.relatedRequestId;if((Ht(e)||Sn(e))&&(n=e.id),n===void 0){if(Ht(e)||Sn(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;this._eventStore&&(i=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&(i===void 0||!a.replayedEventIds?.has(i))&&this.writeSSEEvent(a.controller,a.encoder,e,i);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let s=this._streamMapping.get(o);if(!this._enableJsonResponse){let i;this._eventStore&&(i=await this._eventStore.storeEvent(o,e),s=this._streamMapping.get(o)),s?.controller&&s?.encoder&&(i===void 0||!s.replayedEventIds?.has(i))&&this.writeSSEEvent(s.controller,s.encoder,e,i)&&i!==void 0&&this._resumableStreams.add(o)}if(Ht(e)||Sn(e)){this._requestResponseMap.set(n,e);let i=Array.from(this._requestToStreamMapping.entries()).filter(([c,u])=>u===o).map(([c])=>c);if(i.every(c=>this._requestResponseMap.has(c))){if(!s){if(this._closed){for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);return}if(!this._enableJsonResponse&&this._eventStore&&this._resumableStreams.has(o)){for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);this._resumableStreams.delete(o);return}for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);throw new Error(`No connection established for request ID: ${String(n)}`)}if(this._enableJsonResponse&&s.resolveJson){let c={"Content-Type":"application/json"};this.sessionId!==void 0&&(c["mcp-session-id"]=this.sessionId);let u=i.map(l=>this._requestResponseMap.get(l));u.length===1?s.resolveJson(new Response(JSON.stringify(u[0]),{status:200,headers:c})):s.resolveJson(new Response(JSON.stringify(u),{status:200,headers:c}))}else s.cleanup();for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);this._resumableStreams.delete(o)}}}}});var z0={};eo(z0,{StreamableHTTPServerTransport:()=>Bf});var Bf,P0=G(()=>{y0();T0();Bf=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new $a(e),this._requestListener=Hf(async r=>{let n=this._requestContext.get(r);return this._webStandardTransport.handleRequest(r,{authInfo:n?.authInfo,parsedBody:n?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,r){return this._webStandardTransport.send(e,r)}async handleRequest(e,r,n){let o=e.auth;await Hf(async i=>this._webStandardTransport.handleRequest(i,{authInfo:o,parsedBody:n}),{overrideGlobalObjects:!1})(e,r)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}});var te={};eo(te,{BRAND:()=>lx,DIRTY:()=>wr,EMPTY_PATH:()=>U0,INVALID:()=>M,NEVER:()=>Jx,OK:()=>Ne,ParseStatus:()=>Pe,Schema:()=>V,ZodAny:()=>er,ZodArray:()=>Lt,ZodBigInt:()=>kr,ZodBoolean:()=>Sr,ZodBranded:()=>ro,ZodCatch:()=>Mr,ZodDate:()=>Er,ZodDefault:()=>Nr,ZodDiscriminatedUnion:()=>gs,ZodEffects:()=>st,ZodEnum:()=>Cr,ZodError:()=>Ve,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>_s,ZodIntersection:()=>Rr,ZodIssueCode:()=>k,ZodLazy:()=>Ir,ZodLiteral:()=>Or,ZodMap:()=>mn,ZodNaN:()=>gn,ZodNativeEnum:()=>Ar,ZodNever:()=>mt,ZodNull:()=>zr,ZodNullable:()=>Et,ZodNumber:()=>$r,ZodObject:()=>Je,ZodOptional:()=>Be,ZodParsedType:()=>z,ZodPipeline:()=>no,ZodPromise:()=>tr,ZodReadonly:()=>jr,ZodRecord:()=>ys,ZodSchema:()=>V,ZodSet:()=>hn,ZodString:()=>Qt,ZodSymbol:()=>fn,ZodTransformer:()=>st,ZodTuple:()=>St,ZodType:()=>V,ZodUndefined:()=>Tr,ZodUnion:()=>Pr,ZodUnknown:()=>qt,ZodVoid:()=>pn,addIssueToContext:()=>E,any:()=>vx,array:()=>$x,bigint:()=>mx,boolean:()=>sp,coerce:()=>Bx,custom:()=>rp,date:()=>hx,datetimeRegex:()=>ep,defaultErrorMap:()=>Zt,discriminatedUnion:()=>Ex,effect:()=>Zx,enum:()=>Nx,function:()=>Ox,getErrorMap:()=>un,getParsedType:()=>kt,instanceof:()=>fx,intersection:()=>Tx,isAborted:()=>ms,isAsync:()=>ln,isDirty:()=>hs,isValid:()=>Yt,late:()=>dx,lazy:()=>Cx,literal:()=>Ax,makeIssue:()=>to,map:()=>Rx,nan:()=>px,nativeEnum:()=>Mx,never:()=>bx,null:()=>_x,nullable:()=>qx,number:()=>op,object:()=>Pa,objectUtil:()=>Ea,oboolean:()=>Vx,onumber:()=>Hx,optional:()=>Dx,ostring:()=>Fx,pipeline:()=>Ux,preprocess:()=>Lx,promise:()=>jx,quotelessJson:()=>D0,record:()=>Px,set:()=>Ix,setErrorMap:()=>L0,strictObject:()=>kx,string:()=>np,symbol:()=>gx,transformer:()=>Zx,tuple:()=>zx,undefined:()=>yx,union:()=>Sx,unknown:()=>xx,util:()=>K,void:()=>wx});var K;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(K||(K={}));var Ea;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ea||(Ea={}));var z=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kt=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}};var k=K.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),D0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ve=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ve.create=t=>new Ve(t);var q0=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,K.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${K.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${K.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${K.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:K.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case k.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case k.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=e.defaultError,K.assertNever(t)}return{message:r}},Zt=q0;var Kf=Zt;function L0(t){Kf=t}function un(){return Kf}var to=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},U0=[];function E(t,e){let r=un(),n=to({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Zt?void 0:Zt].filter(o=>!!o)});t.common.issues.push(n)}var Pe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return M;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return M;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},M=Object.freeze({status:"aborted"}),wr=t=>({status:"dirty",value:t}),Ne=t=>({status:"valid",value:t}),ms=t=>t.status==="aborted",hs=t=>t.status==="dirty",Yt=t=>t.status==="valid",ln=t=>typeof Promise<"u"&&t instanceof Promise;var I;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(I||(I={}));var ot=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Gf=(t,e)=>{if(Yt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ve(t.common.issues);return this._error=r,this._error}}};function U(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var V=class{get description(){return this._def.description}_getType(e){return kt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:kt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Pe,ctx:{common:e.parent.common,data:e.data,parsedType:kt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ln(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Gf(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Yt(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Yt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ln(o)?o:Promise.resolve(o));return Gf(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:k.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new st({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Be.create(this,this._def)}nullable(){return Et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Lt.create(this)}promise(){return tr.create(this,this._def)}or(e){return Pr.create([this,e],this._def)}and(e){return Rr.create(this,e,this._def)}transform(e){return new st({...U(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Nr({...U(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new ro({typeName:S.ZodBranded,type:this,...U(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Mr({...U(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return no.create(this,e)}readonly(){return jr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},F0=/^c[^\s-]{8,}$/i,H0=/^[0-9a-z]+$/,V0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,B0=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,J0=/^[a-z0-9_-]{21}$/i,W0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,K0=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,G0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,X0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ta,Y0=/^(?:(?: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])$/,Q0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,tx=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,rx=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nx=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Yf="((\\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])))",ox=new RegExp(`^${Yf}$`);function Qf(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function sx(t){return new RegExp(`^${Qf(t)}$`)}function ep(t){let e=`${Yf}T${Qf(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function ix(t,e){return!!((e==="v4"||!e)&&Y0.test(t)||(e==="v6"||!e)&&ex.test(t))}function ax(t,e){if(!W0.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function cx(t,e){return!!((e==="v4"||!e)&&Q0.test(t)||(e==="v6"||!e)&&tx.test(t))}var Qt=class t extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:z.string,received:s.parsedType}),M}let n=new Pe,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")G0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Ta||(Ta=new RegExp(X0,"u")),Ta.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")B0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")J0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")F0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")H0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")V0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),E(o,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?ep(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?ox.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?sx(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?K0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?ix(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?ax(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?cx(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?rx.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?nx.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):K.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:k.invalid_string,...I.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...I.errToObj(e)})}url(e){return this._addCheck({kind:"url",...I.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...I.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...I.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...I.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...I.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...I.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...I.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...I.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...I.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...I.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...I.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...I.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...I.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...I.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...I.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...I.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...I.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...I.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...I.errToObj(r)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Qt.create=t=>new Qt({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...U(t)});function ux(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var $r=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:z.number,received:s.parsedType}),M}let n,o=new Pe;for(let s of this._def.checks)s.kind==="int"?K.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?ux(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_finite,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,I.toString(r))}gt(e,r){return this.setLimit("min",e,!1,I.toString(r))}lte(e,r){return this.setLimit("max",e,!0,I.toString(r))}lt(e,r){return this.setLimit("max",e,!1,I.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:I.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:I.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&K.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};$r.create=t=>new $r({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...U(t)});var kr=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let n,o=new Pe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:z.bigint,received:r.parsedType}),M}gte(e,r){return this.setLimit("min",e,!0,I.toString(r))}gt(e,r){return this.setLimit("min",e,!1,I.toString(r))}lte(e,r){return this.setLimit("max",e,!0,I.toString(r))}lt(e,r){return this.setLimit("max",e,!1,I.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};kr.create=t=>new kr({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...U(t)});var Sr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.boolean,received:n.parsedType}),M}return Ne(e.data)}};Sr.create=t=>new Sr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...U(t)});var Er=class t extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:z.date,received:s.parsedType}),M}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_date}),M}let n=new Pe,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):K.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:I.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:I.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Er.create=t=>new Er({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...U(t)});var fn=class extends V{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.symbol,received:n.parsedType}),M}return Ne(e.data)}};fn.create=t=>new fn({typeName:S.ZodSymbol,...U(t)});var Tr=class extends V{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.undefined,received:n.parsedType}),M}return Ne(e.data)}};Tr.create=t=>new Tr({typeName:S.ZodUndefined,...U(t)});var zr=class extends V{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.null,received:n.parsedType}),M}return Ne(e.data)}};zr.create=t=>new zr({typeName:S.ZodNull,...U(t)});var er=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}};er.create=t=>new er({typeName:S.ZodAny,...U(t)});var qt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}};qt.create=t=>new qt({typeName:S.ZodUnknown,...U(t)});var mt=class extends V{_parse(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:z.never,received:r.parsedType}),M}};mt.create=t=>new mt({typeName:S.ZodNever,...U(t)});var pn=class extends V{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.void,received:n.parsedType}),M}return Ne(e.data)}};pn.create=t=>new pn({typeName:S.ZodVoid,...U(t)});var Lt=class t extends V{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return E(r,{code:k.invalid_type,expected:z.array,received:r.parsedType}),M;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(E(r,{code:i?k.too_big:k.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(E(r,{code:k.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(E(r,{code:k.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new ot(r,i,r.path,a)))).then(i=>Pe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new ot(r,i,r.path,a)));return Pe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:I.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:I.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:I.toString(r)}})}nonempty(e){return this.min(1,e)}};Lt.create=(t,e)=>new Lt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...U(e)});function dn(t){if(t instanceof Je){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Be.create(dn(n))}return new Je({...t._def,shape:()=>e})}else return t instanceof Lt?new Lt({...t._def,type:dn(t.element)}):t instanceof Be?Be.create(dn(t.unwrap())):t instanceof Et?Et.create(dn(t.unwrap())):t instanceof St?St.create(t.items.map(e=>dn(e))):t}var Je=class t extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=K.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return E(u,{code:k.invalid_type,expected:z.object,received:u.parsedType}),M}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof mt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ot(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof mt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(E(o,{code:k.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ot(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Pe.mergeObjectSync(n,u)):Pe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return I.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:I.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:S.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of K.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of K.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return dn(this)}partial(e){let r={};for(let n of K.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of K.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Be;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return tp(K.objectKeys(this.shape))}};Je.create=(t,e)=>new Je({shape:()=>t,unknownKeys:"strip",catchall:mt.create(),typeName:S.ZodObject,...U(e)});Je.strictCreate=(t,e)=>new Je({shape:()=>t,unknownKeys:"strict",catchall:mt.create(),typeName:S.ZodObject,...U(e)});Je.lazycreate=(t,e)=>new Je({shape:t,unknownKeys:"strip",catchall:mt.create(),typeName:S.ZodObject,...U(e)});var Pr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ve(a.ctx.common.issues));return E(r,{code:k.invalid_union,unionErrors:i}),M}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ve(c));return E(r,{code:k.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};Pr.create=(t,e)=>new Pr({options:t,typeName:S.ZodUnion,...U(e)});var Dt=t=>t instanceof Ir?Dt(t.schema):t instanceof st?Dt(t.innerType()):t instanceof Or?[t.value]:t instanceof Cr?t.options:t instanceof Ar?K.objectValues(t.enum):t instanceof Nr?Dt(t._def.innerType):t instanceof Tr?[void 0]:t instanceof zr?[null]:t instanceof Be?[void 0,...Dt(t.unwrap())]:t instanceof Et?[null,...Dt(t.unwrap())]:t instanceof ro||t instanceof jr?Dt(t.unwrap()):t instanceof Mr?Dt(t._def.innerType):[],gs=class t extends V{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return E(r,{code:k.invalid_type,expected:z.object,received:r.parsedType}),M;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(E(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Dt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...U(n)})}};function za(t,e){let r=kt(t),n=kt(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=K.objectKeys(e),s=K.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=za(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===z.array&&n===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=za(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Rr=class extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(ms(s)||ms(i))return M;let a=za(s.value,i.value);return a.valid?((hs(s)||hs(i))&&r.dirty(),{status:r.value,value:a.data}):(E(n,{code:k.invalid_intersection_types}),M)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Rr.create=(t,e,r)=>new Rr({left:t,right:e,typeName:S.ZodIntersection,...U(r)});var St=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return E(n,{code:k.invalid_type,expected:z.array,received:n.parsedType}),M;if(n.data.length<this._def.items.length)return E(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&n.data.length>this._def.items.length&&(E(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ot(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Pe.mergeArray(r,i)):Pe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};St.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new St({items:t,typeName:S.ZodTuple,rest:null,...U(e)})};var ys=class t extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return E(n,{code:k.invalid_type,expected:z.object,received:n.parsedType}),M;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new ot(n,a,n.path,a)),value:i._parse(new ot(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Pe.mergeObjectAsync(r,o):Pe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof V?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...U(n)}):new t({keyType:Qt.create(),valueType:e,typeName:S.ZodRecord,...U(r)})}},mn=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return E(n,{code:k.invalid_type,expected:z.map,received:n.parsedType}),M;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new ot(n,a,n.path,[u,"key"])),value:s._parse(new ot(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return M;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return M;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};mn.create=(t,e,r)=>new mn({valueType:e,keyType:t,typeName:S.ZodMap,...U(r)});var hn=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return E(n,{code:k.invalid_type,expected:z.set,received:n.parsedType}),M;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(E(n,{code:k.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(E(n,{code:k.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return M;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new ot(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:I.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:I.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};hn.create=(t,e)=>new hn({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...U(e)});var _s=class t extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return E(r,{code:k.invalid_type,expected:z.function,received:r.parsedType}),M;function n(a,c){return to({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,un(),Zt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return to({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,un(),Zt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof tr){let a=this;return Ne(async function(...c){let u=new Ve([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(n(c,m)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(o(d,m)),u})})}else{let a=this;return Ne(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ve([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ve([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:St.create(e).rest(qt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||St.create([]).rest(qt.create()),returns:r||qt.create(),typeName:S.ZodFunction,...U(n)})}},Ir=class extends V{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ir.create=(t,e)=>new Ir({getter:t,typeName:S.ZodLazy,...U(e)});var Or=class extends V{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return E(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Or.create=(t,e)=>new Or({value:t,typeName:S.ZodLiteral,...U(e)});function tp(t,e){return new Cr({values:t,typeName:S.ZodEnum,...U(e)})}var Cr=class t extends V{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{expected:K.joinValues(n),received:r.parsedType,code:k.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{received:r.data,code:k.invalid_enum_value,options:n}),M}return Ne(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Cr.create=tp;var Ar=class extends V{_parse(e){let r=K.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=K.objectValues(r);return E(n,{expected:K.joinValues(o),received:n.parsedType,code:k.invalid_type}),M}if(this._cache||(this._cache=new Set(K.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=K.objectValues(r);return E(n,{received:n.data,code:k.invalid_enum_value,options:o}),M}return Ne(e.data)}get enum(){return this._def.values}};Ar.create=(t,e)=>new Ar({values:t,typeName:S.ZodNativeEnum,...U(e)});var tr=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return E(r,{code:k.invalid_type,expected:z.promise,received:r.parsedType}),M;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return Ne(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};tr.create=(t,e)=>new tr({type:t,typeName:S.ZodPromise,...U(e)});var st=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{E(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return M;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?M:c.status==="dirty"?wr(c.value):r.value==="dirty"?wr(c.value):c});{if(r.value==="aborted")return M;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?M:a.status==="dirty"?wr(a.value):r.value==="dirty"?wr(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?M:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Yt(i))return M;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Yt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):M);K.assertNever(o)}};st.create=(t,e,r)=>new st({schema:t,typeName:S.ZodEffects,effect:e,...U(r)});st.createWithPreprocess=(t,e,r)=>new st({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...U(r)});var Be=class extends V{_parse(e){return this._getType(e)===z.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Be.create=(t,e)=>new Be({innerType:t,typeName:S.ZodOptional,...U(e)});var Et=class extends V{_parse(e){return this._getType(e)===z.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Et.create=(t,e)=>new Et({innerType:t,typeName:S.ZodNullable,...U(e)});var Nr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Nr.create=(t,e)=>new Nr({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...U(e)});var Mr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ln(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ve(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ve(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Mr.create=(t,e)=>new Mr({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...U(e)});var gn=class extends V{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.nan,received:n.parsedType}),M}return{status:"valid",value:e.data}}};gn.create=t=>new gn({typeName:S.ZodNaN,...U(t)});var lx=Symbol("zod_brand"),ro=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},no=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?M:s.status==="dirty"?(r.dirty(),wr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?M:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:S.ZodPipeline})}},jr=class extends V{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Yt(o)&&(o.value=Object.freeze(o.value)),o);return ln(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};jr.create=(t,e)=>new jr({innerType:t,typeName:S.ZodReadonly,...U(e)});function Xf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function rp(t,e={},r){return t?er.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Xf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Xf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):er.create()}var dx={object:Je.lazycreate},S;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(S||(S={}));var fx=(t,e={message:`Input not instance of ${t.name}`})=>rp(r=>r instanceof t,e),np=Qt.create,op=$r.create,px=gn.create,mx=kr.create,sp=Sr.create,hx=Er.create,gx=fn.create,yx=Tr.create,_x=zr.create,vx=er.create,xx=qt.create,bx=mt.create,wx=pn.create,$x=Lt.create,Pa=Je.create,kx=Je.strictCreate,Sx=Pr.create,Ex=gs.create,Tx=Rr.create,zx=St.create,Px=ys.create,Rx=mn.create,Ix=hn.create,Ox=_s.create,Cx=Ir.create,Ax=Or.create,Nx=Cr.create,Mx=Ar.create,jx=tr.create,Zx=st.create,Dx=Be.create,qx=Et.create,Lx=st.createWithPreprocess,Ux=no.create,Fx=()=>np().optional(),Hx=()=>op().optional(),Vx=()=>sp().optional(),Bx={string:(t=>Qt.create({...t,coerce:!0})),number:(t=>$r.create({...t,coerce:!0})),boolean:(t=>Sr.create({...t,coerce:!0})),bigint:(t=>kr.create({...t,coerce:!0})),date:(t=>Er.create({...t,coerce:!0}))};var Jx=M;qe();qe();qe();qe();var rw=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ce.init(t,e),t.def=e,t.parse=(r,n)=>Ha(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>qr(t,r,n),t.parseAsync=async(r,n)=>Ba(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Lr(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>rt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var nw=w("ZodMiniObject",(t,e)=>{Rs.init(t,e),rw.init(t,e),X.defineLazy(t,"shape",()=>e.shape)});function Ou(t,e){let r={type:"object",get shape(){return X.assignProp(this,"shape",{...t}),this.shape},...X.normalizeParams(e)};return new nw(r)}qe();Os();function Pt(t){return!!t._zod}function Hr(t){let e=Object.values(t);if(e.length===0)return Ou({});let r=e.every(Pt),n=e.every(o=>!Pt(o));if(r)return Ou(t);if(n)return Pa(t);throw new Error("Mixed Zod versions detected in object shape.")}function or(t,e){return Pt(t)?qr(t,e):t.safeParse(e)}async function qs(t,e){return Pt(t)?await Lr(t,e):await t.safeParseAsync(e)}function sr(t){if(!t)return;let e;if(Pt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function bn(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Hr(t)}}if(Pt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function sw(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Ls(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${sw(e.path)}`:e.message).join(`
52
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Tm(t){return t.description}function zm(t){if(Pt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function wn(t){if(Pt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}Vr();function ar(t){return t==="completed"||t==="failed"||t==="cancelled"}var vh=Symbol("Let zodToJsonSchema decide on which parser to use");var _h={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},xh=t=>typeof t=="string"?{..._h,name:t}:{..._h,...t};var bh=t=>{let e=xh(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function cl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Q(t,e,r,n,o){t[e]=r,cl(t,e,n,o)}var fi=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?fi(e,t.currentPath):e.join("/")}}function wh(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=Z(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Q(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Q(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Q(r,"minItems",t.exactLength.value,t.exactLength.message,e),Q(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function $h(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Q(r,"minimum",n.value,n.message,e):Q(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Q(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Q(r,"maximum",n.value,n.message,e):Q(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Q(r,"maximum",n.value,n.message,e));break;case"multipleOf":Q(r,"multipleOf",n.value,n.message,e);break}return r}function kh(){return{type:"boolean"}}function pi(t,e){return Z(t.type._def,e)}var Sh=(t,e)=>Z(t.innerType._def,e);function ul(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>ul(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ik(t,e)}}var Ik=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":Q(r,"minimum",n.value,n.message,e);break;case"max":Q(r,"maximum",n.value,n.message,e);break}return r};function Eh(t,e){return{...Z(t.innerType._def,e),default:t.defaultValue()}}function Th(t,e){return e.effectStrategy==="input"?Z(t.schema._def,e):we(e)}function zh(t){return{type:"string",enum:Array.from(t.values)}}var Ok=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Ph(t,e){let r=[Z(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Z(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Ok(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function Rh(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var ll,gt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ll===void 0&&(ll=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ll),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,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])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function mi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":Q(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":Q(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":yt(r,"email",n.message,e);break;case"format:idn-email":yt(r,"idn-email",n.message,e);break;case"pattern:zod":Ue(r,gt.email,n.message,e);break}break;case"url":yt(r,"uri",n.message,e);break;case"uuid":yt(r,"uuid",n.message,e);break;case"regex":Ue(r,n.regex,n.message,e);break;case"cuid":Ue(r,gt.cuid,n.message,e);break;case"cuid2":Ue(r,gt.cuid2,n.message,e);break;case"startsWith":Ue(r,RegExp(`^${dl(n.value,e)}`),n.message,e);break;case"endsWith":Ue(r,RegExp(`${dl(n.value,e)}$`),n.message,e);break;case"datetime":yt(r,"date-time",n.message,e);break;case"date":yt(r,"date",n.message,e);break;case"time":yt(r,"time",n.message,e);break;case"duration":yt(r,"duration",n.message,e);break;case"length":Q(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),Q(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ue(r,RegExp(dl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&yt(r,"ipv4",n.message,e),n.version!=="v4"&&yt(r,"ipv6",n.message,e);break}case"base64url":Ue(r,gt.base64url,n.message,e);break;case"jwt":Ue(r,gt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ue(r,gt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ue(r,gt.ipv6Cidr,n.message,e);break}case"emoji":Ue(r,gt.emoji(),n.message,e);break;case"ulid":{Ue(r,gt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{yt(r,"binary",n.message,e);break}case"contentEncoding:base64":{Q(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ue(r,gt.base64,n.message,e);break}}break}case"nanoid":Ue(r,gt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function dl(t,e){return e.patternStrategy==="escape"?Ak(t):t}var Ck=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ak(t){let e="";for(let r=0;r<t.length;r++)Ck.has(t[r])||(e+="\\"),e+=t[r];return e}function yt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Q(t,"format",e,r,n)}function Ue(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Ih(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Q(t,"pattern",Ih(e,n),r,n)}function Ih(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
51
+ `,e.enqueue(r.encode(s)),!0}catch(s){return this.onerror?.(s),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,r){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!S0(o))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},i;if(r?.parsedBody!==void 0)i=r.parsedBody;else try{i=await e.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let a;try{Array.isArray(i)?a=i.map(v=>xo.parse(v)):a=[xo.parse(i)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let c=a.some(Yu);if(c){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){let v=this.validateSession(e);if(v)return v;let g=this.validateProtocolVersion(e);if(g)return g}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!a.some(Ft)){for(let v of a)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),d=a.find(v=>Yu(v)),p=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??nh;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let g of a)Ft(g)&&this._requestToStreamMapping.set(g.id,l);for(let g of a)this.onmessage?.(g,{authInfo:r?.authInfo,requestInfo:s})});let m=new TextEncoder,f,h,y=new ReadableStream({start:v=>{f=v},cancel:()=>{h!==void 0&&clearInterval(h),this._streamMapping.get(l)?.controller===f&&this._streamMapping.delete(l)}}),_={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(_["mcp-session-id"]=this.sessionId);for(let v of a)Ft(v)&&(this._streamMapping.set(l,{controller:f,encoder:m,cleanup:()=>{h!==void 0&&clearInterval(h),this._streamMapping.delete(l);try{f.close()}catch{}}}),this._requestToStreamMapping.set(v.id,l));try{await this.writePrimingEvent(f,m,l,p);for(let v of a){let g,x;Ft(v)&&this._eventStore&&p>="2025-11-25"&&(g=()=>{this.closeSSEStream(v.id)},x=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:g,closeStandaloneSSEStream:x})}}catch(v){this._streamMapping.get(l)?.cleanup(),this._resumableStreams.delete(l);for(let g of a)Ft(g)&&this._requestToStreamMapping.delete(g.id);throw v}return this._streamMapping.get(l)?.controller===f&&(h=this.startKeepAlive(f,m)),new Response(y,{status:200,headers:_})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(e){let r=this.validateSession(e);if(r)return r;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=e.headers.get("mcp-session-id");if(!r)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let r=e.headers.get("mcp-protocol-version");if(r!==null&&!kn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${kn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${kn.join(", ")})`)}async close(){this._closed||(this._closed=!0,this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this._resumableStreams.clear(),this.onclose?.())}closeSSEStream(e){let r=this._requestToStreamMapping.get(e);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,r){let n=r?.relatedRequestId;if((Ht(e)||Sn(e))&&(n=e.id),n===void 0){if(Ht(e)||Sn(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;this._eventStore&&(i=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&(i===void 0||!a.replayedEventIds?.has(i))&&this.writeSSEEvent(a.controller,a.encoder,e,i);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let s=this._streamMapping.get(o);if(!this._enableJsonResponse){let i;this._eventStore&&(i=await this._eventStore.storeEvent(o,e),s=this._streamMapping.get(o)),s?.controller&&s?.encoder&&(i===void 0||!s.replayedEventIds?.has(i))&&this.writeSSEEvent(s.controller,s.encoder,e,i)&&i!==void 0&&this._resumableStreams.add(o)}if(Ht(e)||Sn(e)){this._requestResponseMap.set(n,e);let i=Array.from(this._requestToStreamMapping.entries()).filter(([c,u])=>u===o).map(([c])=>c);if(i.every(c=>this._requestResponseMap.has(c))){if(!s){if(this._closed){for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);return}if(!this._enableJsonResponse&&this._eventStore&&this._resumableStreams.has(o)){for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);this._resumableStreams.delete(o);return}for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);throw new Error(`No connection established for request ID: ${String(n)}`)}if(this._enableJsonResponse&&s.resolveJson){let c={"Content-Type":"application/json"};this.sessionId!==void 0&&(c["mcp-session-id"]=this.sessionId);let u=i.map(l=>this._requestResponseMap.get(l));u.length===1?s.resolveJson(new Response(JSON.stringify(u[0]),{status:200,headers:c})):s.resolveJson(new Response(JSON.stringify(u),{status:200,headers:c}))}else s.cleanup();for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);this._resumableStreams.delete(o)}}}}});var R0={};eo(R0,{StreamableHTTPServerTransport:()=>Jf});var Jf,I0=G(()=>{v0();P0();Jf=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new ka(e),this._requestListener=Vf(async r=>{let n=this._requestContext.get(r);return this._webStandardTransport.handleRequest(r,{authInfo:n?.authInfo,parsedBody:n?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,r){return this._webStandardTransport.send(e,r)}async handleRequest(e,r,n){let o=e.auth;await Vf(async i=>this._webStandardTransport.handleRequest(i,{authInfo:o,parsedBody:n}),{overrideGlobalObjects:!1})(e,r)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}});var te={};eo(te,{BRAND:()=>fx,DIRTY:()=>wr,EMPTY_PATH:()=>H0,INVALID:()=>M,NEVER:()=>Kx,OK:()=>Me,ParseStatus:()=>Pe,Schema:()=>V,ZodAny:()=>er,ZodArray:()=>Lt,ZodBigInt:()=>kr,ZodBoolean:()=>Sr,ZodBranded:()=>ro,ZodCatch:()=>Mr,ZodDate:()=>Er,ZodDefault:()=>Nr,ZodDiscriminatedUnion:()=>gs,ZodEffects:()=>st,ZodEnum:()=>Cr,ZodError:()=>Be,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>_s,ZodIntersection:()=>Rr,ZodIssueCode:()=>k,ZodLazy:()=>Ir,ZodLiteral:()=>Or,ZodMap:()=>mn,ZodNaN:()=>gn,ZodNativeEnum:()=>Ar,ZodNever:()=>mt,ZodNull:()=>zr,ZodNullable:()=>Et,ZodNumber:()=>$r,ZodObject:()=>We,ZodOptional:()=>Je,ZodParsedType:()=>z,ZodPipeline:()=>no,ZodPromise:()=>tr,ZodReadonly:()=>jr,ZodRecord:()=>ys,ZodSchema:()=>V,ZodSet:()=>hn,ZodString:()=>Qt,ZodSymbol:()=>fn,ZodTransformer:()=>st,ZodTuple:()=>St,ZodType:()=>V,ZodUndefined:()=>Tr,ZodUnion:()=>Pr,ZodUnknown:()=>qt,ZodVoid:()=>pn,addIssueToContext:()=>E,any:()=>bx,array:()=>Sx,bigint:()=>gx,boolean:()=>ip,coerce:()=>Wx,custom:()=>np,date:()=>yx,datetimeRegex:()=>tp,defaultErrorMap:()=>Zt,discriminatedUnion:()=>zx,effect:()=>qx,enum:()=>jx,function:()=>Ax,getErrorMap:()=>un,getParsedType:()=>kt,instanceof:()=>mx,intersection:()=>Px,isAborted:()=>ms,isAsync:()=>ln,isDirty:()=>hs,isValid:()=>Yt,late:()=>px,lazy:()=>Nx,literal:()=>Mx,makeIssue:()=>to,map:()=>Ox,nan:()=>hx,nativeEnum:()=>Zx,never:()=>$x,null:()=>xx,nullable:()=>Ux,number:()=>sp,object:()=>Ra,objectUtil:()=>Ta,oboolean:()=>Jx,onumber:()=>Bx,optional:()=>Lx,ostring:()=>Vx,pipeline:()=>Hx,preprocess:()=>Fx,promise:()=>Dx,quotelessJson:()=>L0,record:()=>Ix,set:()=>Cx,setErrorMap:()=>F0,strictObject:()=>Ex,string:()=>op,symbol:()=>_x,transformer:()=>qx,tuple:()=>Rx,undefined:()=>vx,union:()=>Tx,unknown:()=>wx,util:()=>K,void:()=>kx});var K;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(K||(K={}));var Ta;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ta||(Ta={}));var z=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kt=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}};var k=K.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),L0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Be=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Be.create=t=>new Be(t);var U0=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,K.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${K.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${K.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${K.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:K.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case k.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case k.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=e.defaultError,K.assertNever(t)}return{message:r}},Zt=U0;var Gf=Zt;function F0(t){Gf=t}function un(){return Gf}var to=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},H0=[];function E(t,e){let r=un(),n=to({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Zt?void 0:Zt].filter(o=>!!o)});t.common.issues.push(n)}var Pe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return M;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return M;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},M=Object.freeze({status:"aborted"}),wr=t=>({status:"dirty",value:t}),Me=t=>({status:"valid",value:t}),ms=t=>t.status==="aborted",hs=t=>t.status==="dirty",Yt=t=>t.status==="valid",ln=t=>typeof Promise<"u"&&t instanceof Promise;var I;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(I||(I={}));var ot=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Xf=(t,e)=>{if(Yt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Be(t.common.issues);return this._error=r,this._error}}};function U(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var V=class{get description(){return this._def.description}_getType(e){return kt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:kt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Pe,ctx:{common:e.parent.common,data:e.data,parsedType:kt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ln(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Xf(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Yt(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Yt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ln(o)?o:Promise.resolve(o));return Xf(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:k.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new st({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Je.create(this,this._def)}nullable(){return Et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Lt.create(this)}promise(){return tr.create(this,this._def)}or(e){return Pr.create([this,e],this._def)}and(e){return Rr.create(this,e,this._def)}transform(e){return new st({...U(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Nr({...U(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new ro({typeName:S.ZodBranded,type:this,...U(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Mr({...U(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return no.create(this,e)}readonly(){return jr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},V0=/^c[^\s-]{8,}$/i,B0=/^[0-9a-z]+$/,J0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,W0=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,K0=/^[a-z0-9_-]{21}$/i,G0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,X0=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Y0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Q0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",za,ex=/^(?:(?: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])$/,tx=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,rx=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,nx=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ox=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sx=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qf="((\\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])))",ix=new RegExp(`^${Qf}$`);function ep(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function ax(t){return new RegExp(`^${ep(t)}$`)}function tp(t){let e=`${Qf}T${ep(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function cx(t,e){return!!((e==="v4"||!e)&&ex.test(t)||(e==="v6"||!e)&&rx.test(t))}function ux(t,e){if(!G0.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function lx(t,e){return!!((e==="v4"||!e)&&tx.test(t)||(e==="v6"||!e)&&nx.test(t))}var Qt=class t extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:z.string,received:s.parsedType}),M}let n=new Pe,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Y0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")za||(za=new RegExp(Q0,"u")),za.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")W0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")K0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")V0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")B0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")J0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),E(o,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?tp(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?ix.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?ax(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?X0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?cx(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?ux(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?lx(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?ox.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?sx.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):K.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:k.invalid_string,...I.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...I.errToObj(e)})}url(e){return this._addCheck({kind:"url",...I.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...I.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...I.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...I.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...I.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...I.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...I.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...I.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...I.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...I.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...I.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...I.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...I.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...I.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...I.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...I.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...I.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...I.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...I.errToObj(r)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Qt.create=t=>new Qt({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...U(t)});function dx(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var $r=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:z.number,received:s.parsedType}),M}let n,o=new Pe;for(let s of this._def.checks)s.kind==="int"?K.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?dx(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_finite,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,I.toString(r))}gt(e,r){return this.setLimit("min",e,!1,I.toString(r))}lte(e,r){return this.setLimit("max",e,!0,I.toString(r))}lt(e,r){return this.setLimit("max",e,!1,I.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:I.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:I.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&K.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};$r.create=t=>new $r({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...U(t)});var kr=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let n,o=new Pe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:z.bigint,received:r.parsedType}),M}gte(e,r){return this.setLimit("min",e,!0,I.toString(r))}gt(e,r){return this.setLimit("min",e,!1,I.toString(r))}lte(e,r){return this.setLimit("max",e,!0,I.toString(r))}lt(e,r){return this.setLimit("max",e,!1,I.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};kr.create=t=>new kr({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...U(t)});var Sr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.boolean,received:n.parsedType}),M}return Me(e.data)}};Sr.create=t=>new Sr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...U(t)});var Er=class t extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:z.date,received:s.parsedType}),M}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_date}),M}let n=new Pe,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):K.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:I.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:I.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Er.create=t=>new Er({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...U(t)});var fn=class extends V{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.symbol,received:n.parsedType}),M}return Me(e.data)}};fn.create=t=>new fn({typeName:S.ZodSymbol,...U(t)});var Tr=class extends V{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.undefined,received:n.parsedType}),M}return Me(e.data)}};Tr.create=t=>new Tr({typeName:S.ZodUndefined,...U(t)});var zr=class extends V{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.null,received:n.parsedType}),M}return Me(e.data)}};zr.create=t=>new zr({typeName:S.ZodNull,...U(t)});var er=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Me(e.data)}};er.create=t=>new er({typeName:S.ZodAny,...U(t)});var qt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Me(e.data)}};qt.create=t=>new qt({typeName:S.ZodUnknown,...U(t)});var mt=class extends V{_parse(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:z.never,received:r.parsedType}),M}};mt.create=t=>new mt({typeName:S.ZodNever,...U(t)});var pn=class extends V{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.void,received:n.parsedType}),M}return Me(e.data)}};pn.create=t=>new pn({typeName:S.ZodVoid,...U(t)});var Lt=class t extends V{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return E(r,{code:k.invalid_type,expected:z.array,received:r.parsedType}),M;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(E(r,{code:i?k.too_big:k.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(E(r,{code:k.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(E(r,{code:k.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new ot(r,i,r.path,a)))).then(i=>Pe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new ot(r,i,r.path,a)));return Pe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:I.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:I.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:I.toString(r)}})}nonempty(e){return this.min(1,e)}};Lt.create=(t,e)=>new Lt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...U(e)});function dn(t){if(t instanceof We){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Je.create(dn(n))}return new We({...t._def,shape:()=>e})}else return t instanceof Lt?new Lt({...t._def,type:dn(t.element)}):t instanceof Je?Je.create(dn(t.unwrap())):t instanceof Et?Et.create(dn(t.unwrap())):t instanceof St?St.create(t.items.map(e=>dn(e))):t}var We=class t extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=K.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return E(u,{code:k.invalid_type,expected:z.object,received:u.parsedType}),M}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof mt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ot(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof mt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(E(o,{code:k.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ot(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Pe.mergeObjectSync(n,u)):Pe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return I.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:I.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:S.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of K.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of K.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return dn(this)}partial(e){let r={};for(let n of K.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of K.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Je;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return rp(K.objectKeys(this.shape))}};We.create=(t,e)=>new We({shape:()=>t,unknownKeys:"strip",catchall:mt.create(),typeName:S.ZodObject,...U(e)});We.strictCreate=(t,e)=>new We({shape:()=>t,unknownKeys:"strict",catchall:mt.create(),typeName:S.ZodObject,...U(e)});We.lazycreate=(t,e)=>new We({shape:t,unknownKeys:"strip",catchall:mt.create(),typeName:S.ZodObject,...U(e)});var Pr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Be(a.ctx.common.issues));return E(r,{code:k.invalid_union,unionErrors:i}),M}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Be(c));return E(r,{code:k.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};Pr.create=(t,e)=>new Pr({options:t,typeName:S.ZodUnion,...U(e)});var Dt=t=>t instanceof Ir?Dt(t.schema):t instanceof st?Dt(t.innerType()):t instanceof Or?[t.value]:t instanceof Cr?t.options:t instanceof Ar?K.objectValues(t.enum):t instanceof Nr?Dt(t._def.innerType):t instanceof Tr?[void 0]:t instanceof zr?[null]:t instanceof Je?[void 0,...Dt(t.unwrap())]:t instanceof Et?[null,...Dt(t.unwrap())]:t instanceof ro||t instanceof jr?Dt(t.unwrap()):t instanceof Mr?Dt(t._def.innerType):[],gs=class t extends V{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return E(r,{code:k.invalid_type,expected:z.object,received:r.parsedType}),M;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(E(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Dt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...U(n)})}};function Pa(t,e){let r=kt(t),n=kt(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=K.objectKeys(e),s=K.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Pa(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===z.array&&n===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Pa(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Rr=class extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(ms(s)||ms(i))return M;let a=Pa(s.value,i.value);return a.valid?((hs(s)||hs(i))&&r.dirty(),{status:r.value,value:a.data}):(E(n,{code:k.invalid_intersection_types}),M)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Rr.create=(t,e,r)=>new Rr({left:t,right:e,typeName:S.ZodIntersection,...U(r)});var St=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return E(n,{code:k.invalid_type,expected:z.array,received:n.parsedType}),M;if(n.data.length<this._def.items.length)return E(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&n.data.length>this._def.items.length&&(E(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ot(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Pe.mergeArray(r,i)):Pe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};St.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new St({items:t,typeName:S.ZodTuple,rest:null,...U(e)})};var ys=class t extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return E(n,{code:k.invalid_type,expected:z.object,received:n.parsedType}),M;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new ot(n,a,n.path,a)),value:i._parse(new ot(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Pe.mergeObjectAsync(r,o):Pe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof V?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...U(n)}):new t({keyType:Qt.create(),valueType:e,typeName:S.ZodRecord,...U(r)})}},mn=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return E(n,{code:k.invalid_type,expected:z.map,received:n.parsedType}),M;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new ot(n,a,n.path,[u,"key"])),value:s._parse(new ot(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return M;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return M;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};mn.create=(t,e,r)=>new mn({valueType:e,keyType:t,typeName:S.ZodMap,...U(r)});var hn=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return E(n,{code:k.invalid_type,expected:z.set,received:n.parsedType}),M;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(E(n,{code:k.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(E(n,{code:k.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return M;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new ot(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:I.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:I.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};hn.create=(t,e)=>new hn({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...U(e)});var _s=class t extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return E(r,{code:k.invalid_type,expected:z.function,received:r.parsedType}),M;function n(a,c){return to({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,un(),Zt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return to({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,un(),Zt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof tr){let a=this;return Me(async function(...c){let u=new Be([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(n(c,m)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(o(d,m)),u})})}else{let a=this;return Me(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Be([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Be([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:St.create(e).rest(qt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||St.create([]).rest(qt.create()),returns:r||qt.create(),typeName:S.ZodFunction,...U(n)})}},Ir=class extends V{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ir.create=(t,e)=>new Ir({getter:t,typeName:S.ZodLazy,...U(e)});var Or=class extends V{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return E(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Or.create=(t,e)=>new Or({value:t,typeName:S.ZodLiteral,...U(e)});function rp(t,e){return new Cr({values:t,typeName:S.ZodEnum,...U(e)})}var Cr=class t extends V{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{expected:K.joinValues(n),received:r.parsedType,code:k.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{received:r.data,code:k.invalid_enum_value,options:n}),M}return Me(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Cr.create=rp;var Ar=class extends V{_parse(e){let r=K.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=K.objectValues(r);return E(n,{expected:K.joinValues(o),received:n.parsedType,code:k.invalid_type}),M}if(this._cache||(this._cache=new Set(K.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=K.objectValues(r);return E(n,{received:n.data,code:k.invalid_enum_value,options:o}),M}return Me(e.data)}get enum(){return this._def.values}};Ar.create=(t,e)=>new Ar({values:t,typeName:S.ZodNativeEnum,...U(e)});var tr=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return E(r,{code:k.invalid_type,expected:z.promise,received:r.parsedType}),M;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return Me(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};tr.create=(t,e)=>new tr({type:t,typeName:S.ZodPromise,...U(e)});var st=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{E(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return M;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?M:c.status==="dirty"?wr(c.value):r.value==="dirty"?wr(c.value):c});{if(r.value==="aborted")return M;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?M:a.status==="dirty"?wr(a.value):r.value==="dirty"?wr(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?M:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Yt(i))return M;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Yt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):M);K.assertNever(o)}};st.create=(t,e,r)=>new st({schema:t,typeName:S.ZodEffects,effect:e,...U(r)});st.createWithPreprocess=(t,e,r)=>new st({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...U(r)});var Je=class extends V{_parse(e){return this._getType(e)===z.undefined?Me(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Je.create=(t,e)=>new Je({innerType:t,typeName:S.ZodOptional,...U(e)});var Et=class extends V{_parse(e){return this._getType(e)===z.null?Me(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Et.create=(t,e)=>new Et({innerType:t,typeName:S.ZodNullable,...U(e)});var Nr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Nr.create=(t,e)=>new Nr({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...U(e)});var Mr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ln(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Be(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Be(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Mr.create=(t,e)=>new Mr({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...U(e)});var gn=class extends V{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.nan,received:n.parsedType}),M}return{status:"valid",value:e.data}}};gn.create=t=>new gn({typeName:S.ZodNaN,...U(t)});var fx=Symbol("zod_brand"),ro=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},no=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?M:s.status==="dirty"?(r.dirty(),wr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?M:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:S.ZodPipeline})}},jr=class extends V{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Yt(o)&&(o.value=Object.freeze(o.value)),o);return ln(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};jr.create=(t,e)=>new jr({innerType:t,typeName:S.ZodReadonly,...U(e)});function Yf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function np(t,e={},r){return t?er.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Yf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Yf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):er.create()}var px={object:We.lazycreate},S;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(S||(S={}));var mx=(t,e={message:`Input not instance of ${t.name}`})=>np(r=>r instanceof t,e),op=Qt.create,sp=$r.create,hx=gn.create,gx=kr.create,ip=Sr.create,yx=Er.create,_x=fn.create,vx=Tr.create,xx=zr.create,bx=er.create,wx=qt.create,$x=mt.create,kx=pn.create,Sx=Lt.create,Ra=We.create,Ex=We.strictCreate,Tx=Pr.create,zx=gs.create,Px=Rr.create,Rx=St.create,Ix=ys.create,Ox=mn.create,Cx=hn.create,Ax=_s.create,Nx=Ir.create,Mx=Or.create,jx=Cr.create,Zx=Ar.create,Dx=tr.create,qx=st.create,Lx=Je.create,Ux=Et.create,Fx=st.createWithPreprocess,Hx=no.create,Vx=()=>op().optional(),Bx=()=>sp().optional(),Jx=()=>ip().optional(),Wx={string:(t=>Qt.create({...t,coerce:!0})),number:(t=>$r.create({...t,coerce:!0})),boolean:(t=>Sr.create({...t,coerce:!0})),bigint:(t=>kr.create({...t,coerce:!0})),date:(t=>Er.create({...t,coerce:!0}))};var Kx=M;Le();Le();Le();Le();var ow=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ue.init(t,e),t.def=e,t.parse=(r,n)=>Va(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>qr(t,r,n),t.parseAsync=async(r,n)=>Ja(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Lr(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>rt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var sw=w("ZodMiniObject",(t,e)=>{Rs.init(t,e),ow.init(t,e),X.defineLazy(t,"shape",()=>e.shape)});function Cu(t,e){let r={type:"object",get shape(){return X.assignProp(this,"shape",{...t}),this.shape},...X.normalizeParams(e)};return new sw(r)}Le();Os();function Pt(t){return!!t._zod}function Hr(t){let e=Object.values(t);if(e.length===0)return Cu({});let r=e.every(Pt),n=e.every(o=>!Pt(o));if(r)return Cu(t);if(n)return Ra(t);throw new Error("Mixed Zod versions detected in object shape.")}function or(t,e){return Pt(t)?qr(t,e):t.safeParse(e)}async function qs(t,e){return Pt(t)?await Lr(t,e):await t.safeParseAsync(e)}function sr(t){if(!t)return;let e;if(Pt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function bn(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Hr(t)}}if(Pt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function aw(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Ls(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${aw(e.path)}`:e.message).join(`
52
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function zm(t){return t.description}function Pm(t){if(Pt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function wn(t){if(Pt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}Vr();function ar(t){return t==="completed"||t==="failed"||t==="cancelled"}var xh=Symbol("Let zodToJsonSchema decide on which parser to use");var vh={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},bh=t=>typeof t=="string"?{...vh,name:t}:{...vh,...t};var wh=t=>{let e=bh(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ul(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Q(t,e,r,n,o){t[e]=r,ul(t,e,n,o)}var fi=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?fi(e,t.currentPath):e.join("/")}}function $h(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=Z(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Q(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Q(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Q(r,"minItems",t.exactLength.value,t.exactLength.message,e),Q(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function kh(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Q(r,"minimum",n.value,n.message,e):Q(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Q(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Q(r,"maximum",n.value,n.message,e):Q(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Q(r,"maximum",n.value,n.message,e));break;case"multipleOf":Q(r,"multipleOf",n.value,n.message,e);break}return r}function Sh(){return{type:"boolean"}}function pi(t,e){return Z(t.type._def,e)}var Eh=(t,e)=>Z(t.innerType._def,e);function ll(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>ll(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ck(t,e)}}var Ck=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":Q(r,"minimum",n.value,n.message,e);break;case"max":Q(r,"maximum",n.value,n.message,e);break}return r};function Th(t,e){return{...Z(t.innerType._def,e),default:t.defaultValue()}}function zh(t,e){return e.effectStrategy==="input"?Z(t.schema._def,e):we(e)}function Ph(t){return{type:"string",enum:Array.from(t.values)}}var Ak=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Rh(t,e){let r=[Z(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Z(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Ak(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function Ih(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var dl,gt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(dl===void 0&&(dl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),dl),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,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])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function mi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":Q(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":Q(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":yt(r,"email",n.message,e);break;case"format:idn-email":yt(r,"idn-email",n.message,e);break;case"pattern:zod":Fe(r,gt.email,n.message,e);break}break;case"url":yt(r,"uri",n.message,e);break;case"uuid":yt(r,"uuid",n.message,e);break;case"regex":Fe(r,n.regex,n.message,e);break;case"cuid":Fe(r,gt.cuid,n.message,e);break;case"cuid2":Fe(r,gt.cuid2,n.message,e);break;case"startsWith":Fe(r,RegExp(`^${fl(n.value,e)}`),n.message,e);break;case"endsWith":Fe(r,RegExp(`${fl(n.value,e)}$`),n.message,e);break;case"datetime":yt(r,"date-time",n.message,e);break;case"date":yt(r,"date",n.message,e);break;case"time":yt(r,"time",n.message,e);break;case"duration":yt(r,"duration",n.message,e);break;case"length":Q(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),Q(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Fe(r,RegExp(fl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&yt(r,"ipv4",n.message,e),n.version!=="v4"&&yt(r,"ipv6",n.message,e);break}case"base64url":Fe(r,gt.base64url,n.message,e);break;case"jwt":Fe(r,gt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Fe(r,gt.ipv4Cidr,n.message,e),n.version!=="v4"&&Fe(r,gt.ipv6Cidr,n.message,e);break}case"emoji":Fe(r,gt.emoji(),n.message,e);break;case"ulid":{Fe(r,gt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{yt(r,"binary",n.message,e);break}case"contentEncoding:base64":{Q(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Fe(r,gt.base64,n.message,e);break}}break}case"nanoid":Fe(r,gt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function fl(t,e){return e.patternStrategy==="escape"?Mk(t):t}var Nk=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Mk(t){let e="";for(let r=0;r<t.length;r++)Nk.has(t[r])||(e+="\\"),e+=t[r];return e}function yt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Q(t,"format",e,r,n)}function Fe(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Oh(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Q(t,"pattern",Oh(e,n),r,n)}function Oh(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
53
53
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
54
54
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
55
55
  `:`[${n[c]}\r
56
- ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function hi(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=mi(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===S.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===S.ZodBranded&&t.keyType._def.type._def.typeName===S.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=pi(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Oh(t,e){if(e.mapStrategy==="record")return hi(t,e);let r=Z(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Ch(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Ah(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function Nh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Po={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function jh(t,e){if(e.target==="openApi3")return Mh(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Po&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Po[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Mh(t,e)}var Mh=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Z(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Zh(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Po[t.innerType._def.typeName],nullable:!0}:{type:[Po[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Z(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Dh(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",cl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Q(r,"minimum",n.value,n.message,e):Q(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Q(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Q(r,"maximum",n.value,n.message,e):Q(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Q(r,"maximum",n.value,n.message,e));break;case"multipleOf":Q(r,"multipleOf",n.value,n.message,e);break}return r}function qh(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=Mk(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Z(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=Nk(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Nk(t,e){if(t.catchall._def.typeName!=="ZodNever")return Z(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Mk(t){try{return t.isOptional()}catch{return!0}}var Lh=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Z(t.innerType._def,e);let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Uh=(t,e)=>{if(e.pipeStrategy==="input")return Z(t.in._def,e);if(e.pipeStrategy==="output")return Z(t.out._def,e);let r=Z(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Z(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Fh(t,e){return Z(t.type._def,e)}function Hh(t,e){let n={type:"array",uniqueItems:!0,items:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Q(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Q(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Vh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Z(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Bh(t){return{not:we(t)}}function Jh(t){return we(t)}var Wh=(t,e)=>Z(t.innerType._def,e);var Kh=(t,e,r)=>{switch(e){case S.ZodString:return mi(t,r);case S.ZodNumber:return Dh(t,r);case S.ZodObject:return qh(t,r);case S.ZodBigInt:return $h(t,r);case S.ZodBoolean:return kh();case S.ZodDate:return ul(t,r);case S.ZodUndefined:return Bh(r);case S.ZodNull:return Nh(r);case S.ZodArray:return wh(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return jh(t,r);case S.ZodIntersection:return Ph(t,r);case S.ZodTuple:return Vh(t,r);case S.ZodRecord:return hi(t,r);case S.ZodLiteral:return Rh(t,r);case S.ZodEnum:return zh(t);case S.ZodNativeEnum:return Ch(t);case S.ZodNullable:return Zh(t,r);case S.ZodOptional:return Lh(t,r);case S.ZodMap:return Oh(t,r);case S.ZodSet:return Hh(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Fh(t,r);case S.ZodNaN:case S.ZodNever:return Ah(r);case S.ZodEffects:return Th(t,r);case S.ZodAny:return we(r);case S.ZodUnknown:return Jh(r);case S.ZodDefault:return Eh(t,r);case S.ZodBranded:return pi(t,r);case S.ZodReadonly:return Wh(t,r);case S.ZodCatch:return Sh(t,r);case S.ZodPipeline:return Uh(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function Z(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==vh)return a}if(n&&!r){let a=jk(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Kh(t,t.typeName,e),i=typeof s=="function"?Z(s(),e):s;if(i&&Zk(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var jk=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:fi(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},Zk=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var fl=(t,e)=>{let r=bh(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Z(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Z(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Dk(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function pl(t,e){return Pt(t)?Iu(t,{target:Dk(e?.target),io:e?.pipeStrategy??"input"}):fl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function ml(t){let r=sr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wn(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function hl(t,e){let r=or(t,e);if(!r.success)throw r.error;return r.data}var qk=6e4,gi=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ws,r=>{this._oncancel(r)}),this.setNotificationHandler(Xs,r=>{this._onprogress(r)}),this.setRequestHandler(Gs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ys,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new O(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ei,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new O(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new O(N.InvalidParams,`Task not found: ${s}`);if(!ar(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(ar(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[ir]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ti,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new O(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ni,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new O(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(ar(o.status))throw new O(N.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new O(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof O?o:new O(N.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),O.fromError(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Ht(s)||Sn(s)?this._onresponse(s):Ft(s)?this._onrequest(s,i):ch(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=O.fromError(N.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[ir]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=sh(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new O(N.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let f=m.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:N.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Ht(e))n(e);else{let i=new O(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Ht(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Ht(e))o(e);else{let i=O.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof O?i:new O(N.InternalError,String(i))}}return}let s;try{let i=await this.request(e,En,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new O(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},ar(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new O(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new O(N.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof O?i:new O(N.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=v=>{l(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){d(v);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[ir]:c}});let f=v=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let g=v instanceof O?v:new O(N.RequestTimeout,String(v));l(g)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let g=or(r,v.result);g.success?u(g.data):l(g.error)}catch(g){l(g)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??qk,y=()=>f(O.fromError(N.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=g=>{let x=this._responseHandlers.get(p);x?x(g):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(_,{type:"request",message:m,timestamp:Date.now()}).catch(g=>{this._cleanupTimeout(p),l(g)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(p),l(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Qs,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ri,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},lh,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ir]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[ir]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[ir]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=ml(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=hl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=ml(e);this._notificationHandlers.set(n,o=>{let s=hl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Ft(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new O(N.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new O(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new O(N.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new O(N.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=So.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ar(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new O(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ar(a.status))throw new O(N.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=So.parse({method:"notifications/tasks/status",params:c});await this.notification(u),ar(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Gh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Xh(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Gh(i)&&Gh(s)?r[o]={...i,...s}:r[o]=s}return r}Vr();var G_=Sa(cf(),1),X_=Sa(K_(),1);function XR(){let t=new G_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,X_.default)(t),t}var Qi=class{constructor(e){this._ajv=e??XR()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};Vr();var ea=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},zo,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Pn,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Y_(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Q_(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var ta=class extends gi{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(To.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Qi,this.setRequestHandler(Ks,n=>this._oninitialize(n)),this.setNotificationHandler(Yu,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(sl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=To.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ea(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Xh(this._capabilities,e)}setRequestHandler(e,r){let o=sr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=wn(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=or(zn,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new O(N.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let f=or(En,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new O(N.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let m=or(li,p);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new O(N.InvalidParams,`Invalid tools/call result: ${f}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Q_(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Y_(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:kn.includes(r)?r:Ju,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Js)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},il,r):this.request({method:"sampling/createMessage",params:e},zo,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Pn,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Pn,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new O(N.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof O?i:new O(N.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},al,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};Vr();var tv=Symbol.for("mcp.completable");function gf(t){return!!t&&typeof t=="object"&&tv in t}function rv(t){return t[tv]?.complete}var ev;(function(t){t.Completable="McpCompletable"})(ev||(ev={}));var YR=/^[A-Za-z0-9._-]{1,128}$/;function QR(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!YR.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function e1(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function yf(t){let e=QR(t);return e1(t,e.warnings),e.isValid}var ra=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var na=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ta(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ra(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(gr(ui)),this.server.assertCanSetRequestHandler(gr(zn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ui,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=bn(r.inputSchema);return o?pl(o,{strictUnions:!0,pipeStrategy:"input"}):t1})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=bn(r.outputSchema);o&&(n.outputSchema=pl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(zn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new O(N.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new O(N.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new O(N.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new O(N.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof O&&n.code===N.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=bn(e.inputSchema)??e.inputSchema,i=await qs(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ls(a);throw new O(N.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new O(N.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=bn(e.outputSchema),s=await qs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ls(i);throw new O(N.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await n.taskStore.getTask(c);if(!d)throw new O(N.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(gr(di)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(di,async e=>{switch(e.params.ref.type){case"ref/prompt":return gh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return yh(e),this.handleResourceCompletion(e,e.params.ref);default:throw new O(N.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new O(N.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new O(N.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return is;let s=sr(n.argsSchema)?.[e.params.argument.name];if(!gf(s))return is;let i=rv(s);if(!i)return is;let a=await i(e.params.argument.value,e.params.context);return ov(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return is;throw new O(N.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return is;let s=await o(e.params.argument.value,e.params.context);return ov(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(gr(oi)),this.server.assertCanSetRequestHandler(gr(si)),this.server.assertCanSetRequestHandler(gr(ii)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(oi,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(si,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ii,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new O(N.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new O(N.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(gr(ai)),this.server.assertCanSetRequestHandler(gr(ci)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ai,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?r1(r.argsSchema):void 0}))})),this.server.setRequestHandler(ci,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new O(N.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new O(N.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=bn(n.argsSchema),s=await qs(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Ls(c);throw new O(N.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Hr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Hr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof Be?c._def?.innerType:c;return gf(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){yf(e);let l={title:r,description:n,inputSchema:nv(o),outputSchema:nv(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&yf(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Hr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Hr(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(_f(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!_f(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var t1={type:"object",properties:{}};function sv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function iv(t){return"_def"in t||"_zod"in t||sv(t)}function _f(t){return typeof t!="object"||t===null||iv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(sv)}function nv(t){if(t){if(_f(t))return Hr(t);if(!iv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function r1(t){let e=sr(t);return e?Object.entries(e).map(([r,n])=>{let o=Tm(n),s=zm(n);return{name:r,description:o,required:!s}}):[]}function gr(t){let r=sr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wn(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function ov(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var is={completion:{values:[],hasMore:!1}};import cv from"node:process";Vr();var n1=10*1024*1024,oa=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??n1}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
57
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),o1(r)}clear(){this._buffer=void 0}};function o1(t){return xo.parse(JSON.parse(t))}function av(t){return JSON.stringify(t)+`
58
- `}var sa=class{constructor(e=cv.stdin,r=cv.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new oa({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=av(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function ia(t){if(typeof t=="string")return{text:t,hasBinary:!1};if(t==null)return{text:"",hasBinary:!1};if(!Array.isArray(t))return{text:JSON.stringify(t??""),hasBinary:!1};let e="",r=!1,n,o,s="",i;for(let a of t){if(a==null||typeof a!="object"){e+=String(a??"");continue}let c=a;switch(c.type){case"text":case"input_text":case"output_text":e+=c.text??"";break;case"tool_use":{o="tool_call",n=c.name??n;let u=`[tool call: ${c.name}] ${JSON.stringify(c.input??{})}`;e+=u,s+=u;break}case"tool_result":{o="tool_result";let u=ia(c.content);r=r||u.hasBinary,e+=u.text,c.is_error===!0&&(i=!0);break}case"image":case"document":r=!0,e+=`[${c.type}]`;break;case"image_url":case"input_image":r=!0,e+="[image]";break;case"input_audio":r=!0,e+="[audio]";break;case"file":case"input_file":r=!0,e+="[file]";break;case"thinking":e+=c.thinking??"";break;case"redacted_thinking":e+="[redacted thinking]";break;default:e+=JSON.stringify(c)}}return{text:e,hasBinary:r,toolName:n,kind:o,toolCallText:s||void 0,isError:i}}function bf(t,e){let r=t&&typeof t=="object"?t:{},n=String(r.role??"user"),o=ia(r.content),s=o.kind??(n==="developer"?"system":["system","user","assistant"].includes(n)?n:"other"),i=o.toolName,a=o.text,c=o.toolCallText;n==="tool"&&(s="tool_result");let u=r.tool_calls,l=Array.isArray(u)?u.filter(d=>d&&typeof d=="object"):void 0;if(l&&l.length>0){s="tool_call",i=l[0]?.function?.name??l[0]?.name;let d=l.map(p=>`[tool call: ${p.function?.name??p.name}] ${p.function?.arguments??JSON.stringify(p.input??{})}`).join(`
59
- `);a+=d,c=(c??"")+d}return{index:e,role:n,kind:s,text:a,toolName:i,toolCallText:c,hasBinary:o.hasBinary,isError:o.isError}}function vf(t,e){let r=t.trimStart()[0];return{sourceFormat:"text",parseWarning:t.trim()===""?"Input is empty \u2014 nothing to profile.":e&&(r==="{"||r==="[")?`Input starts like JSON but does not parse (${e.message}), so it is not a conversation file.`:void 0,messages:t.trim()===""?[]:[{index:0,role:"user",kind:"user",text:t,hasBinary:!1}]}}function s1(t){if(typeof t=="string")return{text:t,hasBinary:!1};if(!t||typeof t!="object")return{text:"",hasBinary:!1};let e=t;if(typeof e.text=="string")return{text:e.text,hasBinary:!1};if(e.inlineData||e.fileData)return{text:"[file]",hasBinary:!0};if(e.functionCall){let r=`[tool call: ${e.functionCall.name}] ${JSON.stringify(e.functionCall.args??{})}`;return{text:r,hasBinary:!1,kind:"tool_call",toolName:e.functionCall.name,call:r}}if(e.functionResponse){let r=e.functionResponse.response;return{text:typeof r?.output=="string"?r.output:typeof r?.content=="string"?r.content:JSON.stringify(r??{}),hasBinary:!1,kind:"tool_result",toolName:e.functionResponse.name}}return e.executableCode?{text:String(e.executableCode.code??""),hasBinary:!1}:e.codeExecutionResult?{text:String(e.codeExecutionResult.output??""),hasBinary:!1}:{text:JSON.stringify(e),hasBinary:!1}}function xf(t,e){let r=t&&typeof t=="object"?t:{},n=r.role==="model"?"assistant":String(r.role??"user"),o=Array.isArray(r.parts)?r.parts:[],s="",i=!1,a,c,u="";for(let d of o){let p=s1(d);s+=(s&&p.text?`
60
- `:"")+p.text,i||=p.hasBinary,p.kind&&(a=p.kind),c??=p.toolName,p.call&&(u+=p.call)}let l=["system","user","assistant"].includes(n)?n:"other";return{index:e,role:n,kind:a??l,text:s,toolName:c,toolCallText:u||void 0,hasBinary:i}}function i1(t,e){if(typeof t=="string")return{index:e,role:"user",kind:"user",text:t,hasBinary:!1};let r=t&&typeof t=="object"?t:{},n=r.type;if(n==="function_call"||n==="custom_tool_call"||n==="local_shell_call"){let o=r.name??(n==="local_shell_call"?"local_shell":void 0),s=typeof r.arguments=="string"?r.arguments:JSON.stringify(r.input??r.action??{}),i=`[tool call: ${o}] ${s}`;return{index:e,role:"assistant",kind:"tool_call",text:i,toolName:o,toolCallText:i,hasBinary:!1}}if(n==="function_call_output"||n==="custom_tool_call_output"||n==="local_shell_call_output"){let o=r.output,s=typeof o=="string"?{text:o,hasBinary:!1}:ia(o);return{index:e,role:"tool",kind:"tool_result",text:s.text,hasBinary:s.hasBinary}}if(n==="reasoning"){let o=Array.isArray(r.summary)?r.summary.map(s=>s?.text??"").join(`
61
- `):"";return{index:e,role:"assistant",kind:"assistant",text:o,hasBinary:!1}}return bf(r,e)}function uv(t){if(typeof t!="string")if(t!==null&&typeof t=="object")try{t=JSON.stringify(t)}catch{return vf("")}else t=t==null?"":String(t);let e;try{e=JSON.parse(t)}catch(l){return vf(t,l)}if(e===null||typeof e!="object")return vf(t);if(Array.isArray(e)){let l=e.length===0||e.some(d=>d&&typeof d=="object"&&("role"in d||"parts"in d));return e.length>0&&e.every(d=>d&&typeof d=="object"&&Array.isArray(d.parts))?{sourceFormat:"gemini",messages:e.map((d,p)=>xf(d,p))}:{sourceFormat:"array",parseWarning:l?void 0:"This is a JSON array, but no element has a `role` field \u2014 it does not look like a conversation.",messages:e.map((d,p)=>bf(d,p))}}let r=e,n=typeof r.model=="string"&&r.model?r.model:void 0;if(r.messages==null&&Array.isArray(r.contents)){let l=[],d=r.systemInstruction??r.system_instruction;if(d!=null){let p=typeof d=="string"?{text:d,hasBinary:!1}:xf(d,-1);l.push({index:-1,role:"system",kind:"system",text:p.text,hasBinary:p.hasBinary})}return l.push(...r.contents.map((p,m)=>xf(p,m))),{sourceFormat:"gemini",messages:l,model:n}}if(r.messages==null&&(typeof r.input=="string"||Array.isArray(r.input))){let l=[];typeof r.instructions=="string"&&r.instructions&&l.push({index:-1,role:"system",kind:"system",text:r.instructions,hasBinary:!1});let d=typeof r.input=="string"?[r.input]:r.input;return l.push(...d.map((p,m)=>i1(p,m))),{sourceFormat:"responses",messages:l,model:n}}let o=r.messages,s=Array.isArray(o)?o:[],i=o!=null&&!Array.isArray(o),a=[];if(r.system!=null){let l=ia(r.system);a.push({index:-1,role:"system",kind:"system",text:l.text,hasBinary:l.hasBinary})}a.push(...s.map((l,d)=>bf(l,d)));let c=r.system!=null||s.some(l=>Array.isArray(l?.content)&&l.content.some(d=>d?.type==="tool_use"||d?.type==="tool_result")),u=i?`\`messages\` is a ${typeof o}, not an array \u2014 this file is malformed.`:a.length===0?'This JSON has no `messages` array (and no `system`) \u2014 it does not look like a conversation. Expected {"messages":[{"role":\u2026,"content":\u2026}]}.':void 0;return{sourceFormat:c?"anthropic":"openai",parseWarning:u,messages:a,model:n}}import{createHash as R1}from"node:crypto";var lv=[[/claude.*haiku/i,2e5],[/claude.*(fable|mythos)|claude.*opus-?(5|4-[678])|claude.*sonnet-?(5|4-6)/i,1e6],[/claude.*sonnet|claude.*opus|claude-\d/i,2e5],[/gpt-5/i,4e5],[/gpt-4o|gpt-4-turbo|gpt-4\.1|o[134](-|$)/i,128e3],[/gpt-4(?!o|\.|-turbo)/i,8192],[/gpt-3\.5/i,16385],[/gemini.*(1\.5|2\.|2-5)/i,1e6],[/gemini-?3/i,1048576],[/llama.*3/i,128e3],[/mistral|mixtral/i,32e3]],YD=Math.max(...lv.map(([,t])=>t));function aa(t){if(t){for(let[e,r]of lv)if(e.test(t))return r}}function on(t){return t?/claude/i.test(t)?"anthropic":/gpt|^o\d/i.test(t)?"openai":/gemini/i.test(t)?"google":"generic":"generic"}function a1(t){return t.length===0?0:(t.match(/[{}[\]()<>;:=_\/\\|"'`#$%&*+^~-]/g)?.length??0)/t.length}var ca={anthropic:{prose:2.75,code:2.4},openai:{prose:4,code:3.2},google:{prose:4,code:3.2},generic:{prose:4,code:3.2}};function c1(t){return a1(t)>.08}function ua(t,e){let r=ca[on(e)];return c1(t)?r.code:r.prose}function sn(t,e){return typeof t!="string"&&(t=String(t??"")),t?Math.ceil(t.length/ua(t,e)):0}var wf=4;function H(t){if(!Number.isFinite(t))return"0";if(t<0)return`-${H(-t)}`;let e=Math.round(t);if(e<1e3)return String(e);let r=Math.round(e/100);if(r<100)return`${(r/10).toFixed(1)}k`;let n=Math.round(e/1e3);if(n<1e3)return`${n}k`;let o=Math.round(e/1e5);return o<1e4?`${(o/10).toFixed(1)}M`:`${(Math.round(e/1e8)/10).toFixed(1)}B`}var me=(t,e,r)=>({inputPerM:t,outputPerM:e,cacheReadPerM:r});function et(t,e,r){return r===void 0?new RegExp(`claude-(?:${t})-${e}(?![.\\d]|-\\d{1,2}(?!\\d))`,"i"):new RegExp(`claude-(?:${t})-${e}[-.]${r}(?!\\d)`,"i")}var u1=[[et("fable|mythos",5,1),me(10,50,.25)],[et("fable|mythos",5),me(10,50,1)],[et("opus",5,5),me(4,20,.2)],[et("opus",5),me(5,25,.5)],[et("opus",4,8),me(5,25,.5)],[et("opus",4,7),me(5,25,.5)],[et("opus",4,6),me(5,25,.5)],[et("opus",4,5),me(5,25,.5)],[et("opus",4,1),me(15,75,1.5)],[et("opus",4),me(15,75,1.5)],[/claude-3-opus/i,me(15,75,1.5)],[et("sonnet",5,5),me(2,10,.2)],[et("sonnet",5),me(2,10,.2)],[et("haiku",5,5),me(.1,.5,.01)],[et("haiku",4,5),me(1,5,.1)],[/claude-3-5-haiku/i,me(.8,4,.08)],[/claude-3-haiku/i,me(.25,1.25,.03)],[/claude.*fable|claude.*mythos/i,me(10,50,1)],[/claude.*opus/i,me(5,25,.5)],[/claude.*sonnet/i,me(3,15,.3)],[/claude.*haiku/i,me(1,5,.1)],[/gpt-5.*(mini|nano)/i,{inputPerM:.25,outputPerM:2,cacheReadPerM:.025}],[/gpt-5/i,{inputPerM:1.25,outputPerM:10,cacheReadPerM:.125}],[/gpt-4o-mini/i,{inputPerM:.15,outputPerM:.6,cacheReadPerM:.075}],[/gpt-4o|gpt-4\.1/i,{inputPerM:2.5,outputPerM:10,cacheReadPerM:1.25}],[/gpt-4-turbo/i,{inputPerM:10,outputPerM:30,cacheReadPerM:10}],[/o[13](-|$)/i,{inputPerM:2,outputPerM:8,cacheReadPerM:1}],[/gemini-3[.\d]*-flash-lite/i,me(.3,2.5,.03)],[/gemini-3\.1-flash-lite/i,me(.25,1.5,.025)],[/gemini-3-flash/i,me(.5,3,.05)],[/gemini-3[.\d]*-flash/i,me(.75,3.75,.075)],[/gemini-3[.\d]*-pro/i,me(2,12,.2)],[/gemini.*flash/i,{inputPerM:.1,outputPerM:.4,cacheReadPerM:.025}],[/gemini.*pro/i,{inputPerM:1.25,outputPerM:5,cacheReadPerM:.31}]];function la(t){if(t){for(let[e,r]of u1)if(e.test(t))return r}}function as(t,e){return t/1e6*e.inputPerM}function $f(t){return t/25e3}function an(t){return Number.isFinite(t)?t>=1?`$${t.toFixed(2)}`:t>=.01?`$${t.toFixed(3)}`:`$${t.toFixed(4)}`:"$0.00"}var dv=/(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g,l1="[context-doctor: base64 blob removed \u2014 use file/image APIs instead]";function fv(t){if(t.startsWith("data:"))return!0;let e=new Map;for(let n of t)e.set(n,(e.get(n)??0)+1);if(e.size<24)return!1;let r=0;for(let n of e.values())n>r&&(r=n);return r/t.length<.35}function Jn(t){for(let e of t.matchAll(dv))if(fv(e[0]))return!0;return!1}function kf(t){return t.replace(dv,e=>fv(e)?l1:e)}import{mkdirSync as a2,readFileSync as b1,writeFileSync as c2}from"node:fs";import{dirname as w1,join as $1}from"node:path";import{appendFileSync as d1,existsSync as f1,mkdirSync as p1,readFileSync as m1,statSync as h1,writeFileSync as g1}from"node:fs";import{homedir as y1}from"node:os";import{dirname as pv,join as mv}from"node:path";var _1={optimizeSaved:0,optimizeUsd:0,proxySaved:0,proxyUsd:0,proxyRequests:0,checks:0,warnings:0,shrinkage:0};function v1(t){let e={..._1},r=new Map;for(let n of t){if(n.ev==="rollup"&&n.carried){e.optimizeSaved+=n.carried.optimizeSaved,e.optimizeUsd+=n.carried.optimizeUsd,e.proxySaved+=n.carried.proxySaved,e.proxyUsd+=n.carried.proxyUsd,e.proxyRequests+=n.carried.proxyRequests,e.checks+=n.carried.checks,e.warnings+=n.carried.warnings,e.shrinkage+=n.carried.shrinkage,n.carried.since&&(e.since=Math.min(e.since??n.carried.since,n.carried.since));continue}e.since=Math.min(e.since??n.ts,n.ts),n.ev==="optimize"?(e.optimizeSaved+=n.saved??0,e.optimizeUsd+=n.usd??0):n.ev==="proxy"?(e.proxySaved+=n.saved??0,e.proxyUsd+=n.usd??0,e.proxyRequests+=n.requests??0):(n.ev==="check"||n.ev===void 0)&&n.sid!=="doctor-probe"&&(e.checks++,n.warn&&e.warnings++,n.sid&&n.sid!=="mcp-sketch"&&typeof n.tok=="number"&&r.set(n.sid,[...r.get(n.sid)??[],n.tok]))}for(let n of r.values())for(let o=1;o<n.length;o++)n[o]<n[o-1]&&(e.shrinkage+=n[o-1]-n[o]);return e}function Sf(){return process.env.CONTEXT_DOCTOR_HOOK_STATE??mv(y1(),".claude",".context-doctor-hook-state.json")}function x1(){return mv(pv(Sf()),".context-doctor-ledger.jsonl")}function da(t){let e=x1();try{if(p1(pv(e),{recursive:!0}),f1(e)&&h1(e).size>256*1024){let r=m1(e,"utf8").trimEnd().split(`
62
- `),n=c=>{try{return[JSON.parse(c)]}catch{return[]}},o=r.slice(-500),s=r.slice(0,-500).flatMap(n),i=v1(s),a={ts:Date.now(),ev:"rollup",carried:i};g1(e,[JSON.stringify(a),...o].join(`
56
+ ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function hi(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=mi(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===S.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===S.ZodBranded&&t.keyType._def.type._def.typeName===S.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=pi(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Ch(t,e){if(e.mapStrategy==="record")return hi(t,e);let r=Z(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Ah(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Nh(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function Mh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Po={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Zh(t,e){if(e.target==="openApi3")return jh(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Po&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Po[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return jh(t,e)}var jh=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Z(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Dh(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Po[t.innerType._def.typeName],nullable:!0}:{type:[Po[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Z(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function qh(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ul(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Q(r,"minimum",n.value,n.message,e):Q(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Q(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Q(r,"maximum",n.value,n.message,e):Q(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Q(r,"maximum",n.value,n.message,e));break;case"multipleOf":Q(r,"multipleOf",n.value,n.message,e);break}return r}function Lh(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=Zk(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Z(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=jk(t,e);return i!==void 0&&(n.additionalProperties=i),n}function jk(t,e){if(t.catchall._def.typeName!=="ZodNever")return Z(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Zk(t){try{return t.isOptional()}catch{return!0}}var Uh=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Z(t.innerType._def,e);let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Fh=(t,e)=>{if(e.pipeStrategy==="input")return Z(t.in._def,e);if(e.pipeStrategy==="output")return Z(t.out._def,e);let r=Z(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Z(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Hh(t,e){return Z(t.type._def,e)}function Vh(t,e){let n={type:"array",uniqueItems:!0,items:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Q(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Q(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Bh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Z(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Jh(t){return{not:we(t)}}function Wh(t){return we(t)}var Kh=(t,e)=>Z(t.innerType._def,e);var Gh=(t,e,r)=>{switch(e){case S.ZodString:return mi(t,r);case S.ZodNumber:return qh(t,r);case S.ZodObject:return Lh(t,r);case S.ZodBigInt:return kh(t,r);case S.ZodBoolean:return Sh();case S.ZodDate:return ll(t,r);case S.ZodUndefined:return Jh(r);case S.ZodNull:return Mh(r);case S.ZodArray:return $h(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Zh(t,r);case S.ZodIntersection:return Rh(t,r);case S.ZodTuple:return Bh(t,r);case S.ZodRecord:return hi(t,r);case S.ZodLiteral:return Ih(t,r);case S.ZodEnum:return Ph(t);case S.ZodNativeEnum:return Ah(t);case S.ZodNullable:return Dh(t,r);case S.ZodOptional:return Uh(t,r);case S.ZodMap:return Ch(t,r);case S.ZodSet:return Vh(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Hh(t,r);case S.ZodNaN:case S.ZodNever:return Nh(r);case S.ZodEffects:return zh(t,r);case S.ZodAny:return we(r);case S.ZodUnknown:return Wh(r);case S.ZodDefault:return Th(t,r);case S.ZodBranded:return pi(t,r);case S.ZodReadonly:return Kh(t,r);case S.ZodCatch:return Eh(t,r);case S.ZodPipeline:return Fh(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function Z(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==xh)return a}if(n&&!r){let a=Dk(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Gh(t,t.typeName,e),i=typeof s=="function"?Z(s(),e):s;if(i&&qk(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Dk=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:fi(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},qk=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var pl=(t,e)=>{let r=wh(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Z(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Z(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Lk(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ml(t,e){return Pt(t)?Ou(t,{target:Lk(e?.target),io:e?.pipeStrategy??"input"}):pl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function hl(t){let r=sr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wn(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function gl(t,e){let r=or(t,e);if(!r.success)throw r.error;return r.data}var Uk=6e4,gi=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ws,r=>{this._oncancel(r)}),this.setNotificationHandler(Xs,r=>{this._onprogress(r)}),this.setRequestHandler(Gs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ys,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new O(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ei,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new O(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new O(N.InvalidParams,`Task not found: ${s}`);if(!ar(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(ar(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[ir]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ti,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new O(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ni,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new O(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(ar(o.status))throw new O(N.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new O(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof O?o:new O(N.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),O.fromError(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Ht(s)||Sn(s)?this._onresponse(s):Ft(s)?this._onrequest(s,i):uh(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=O.fromError(N.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[ir]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=ih(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new O(N.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let f=m.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:N.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Ht(e))n(e);else{let i=new O(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Ht(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Ht(e))o(e);else{let i=O.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof O?i:new O(N.InternalError,String(i))}}return}let s;try{let i=await this.request(e,En,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new O(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},ar(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new O(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new O(N.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof O?i:new O(N.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=v=>{l(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){d(v);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[ir]:c}});let f=v=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let g=v instanceof O?v:new O(N.RequestTimeout,String(v));l(g)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let g=or(r,v.result);g.success?u(g.data):l(g.error)}catch(g){l(g)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??Uk,y=()=>f(O.fromError(N.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=g=>{let x=this._responseHandlers.get(p);x?x(g):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(_,{type:"request",message:m,timestamp:Date.now()}).catch(g=>{this._cleanupTimeout(p),l(g)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(p),l(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Qs,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ri,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},dh,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ir]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[ir]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[ir]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=hl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=gl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=hl(e);this._notificationHandlers.set(n,o=>{let s=gl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Ft(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new O(N.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new O(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new O(N.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new O(N.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=So.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ar(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new O(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ar(a.status))throw new O(N.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=So.parse({method:"notifications/tasks/status",params:c});await this.notification(u),ar(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Xh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Yh(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Xh(i)&&Xh(s)?r[o]={...i,...s}:r[o]=s}return r}Vr();var X_=Ea(uf(),1),Y_=Ea(G_(),1);function QR(){let t=new X_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Y_.default)(t),t}var Qi=class{constructor(e){this._ajv=e??QR()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};Vr();var ea=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},zo,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Pn,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Q_(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function ev(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var ta=class extends gi{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(To.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Qi,this.setRequestHandler(Ks,n=>this._oninitialize(n)),this.setNotificationHandler(Qu,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(il,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=To.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ea(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Yh(this._capabilities,e)}setRequestHandler(e,r){let o=sr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=wn(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=or(zn,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new O(N.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let f=or(En,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new O(N.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let m=or(li,p);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new O(N.InvalidParams,`Invalid tools/call result: ${f}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){ev(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Q_(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:kn.includes(r)?r:Wu,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Js)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},al,r):this.request({method:"sampling/createMessage",params:e},zo,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Pn,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Pn,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new O(N.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof O?i:new O(N.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},cl,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};Vr();var rv=Symbol.for("mcp.completable");function yf(t){return!!t&&typeof t=="object"&&rv in t}function nv(t){return t[rv]?.complete}var tv;(function(t){t.Completable="McpCompletable"})(tv||(tv={}));var e1=/^[A-Za-z0-9._-]{1,128}$/;function t1(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!e1.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function r1(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function _f(t){let e=t1(t);return r1(t,e.warnings),e.isValid}var ra=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var na=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ta(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ra(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(gr(ui)),this.server.assertCanSetRequestHandler(gr(zn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ui,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=bn(r.inputSchema);return o?ml(o,{strictUnions:!0,pipeStrategy:"input"}):n1})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=bn(r.outputSchema);o&&(n.outputSchema=ml(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(zn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new O(N.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new O(N.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new O(N.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new O(N.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof O&&n.code===N.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=bn(e.inputSchema)??e.inputSchema,i=await qs(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ls(a);throw new O(N.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new O(N.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=bn(e.outputSchema),s=await qs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ls(i);throw new O(N.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await n.taskStore.getTask(c);if(!d)throw new O(N.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(gr(di)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(di,async e=>{switch(e.params.ref.type){case"ref/prompt":return yh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return _h(e),this.handleResourceCompletion(e,e.params.ref);default:throw new O(N.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new O(N.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new O(N.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return is;let s=sr(n.argsSchema)?.[e.params.argument.name];if(!yf(s))return is;let i=nv(s);if(!i)return is;let a=await i(e.params.argument.value,e.params.context);return sv(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return is;throw new O(N.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return is;let s=await o(e.params.argument.value,e.params.context);return sv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(gr(oi)),this.server.assertCanSetRequestHandler(gr(si)),this.server.assertCanSetRequestHandler(gr(ii)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(oi,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(si,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ii,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new O(N.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new O(N.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(gr(ai)),this.server.assertCanSetRequestHandler(gr(ci)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ai,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?o1(r.argsSchema):void 0}))})),this.server.setRequestHandler(ci,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new O(N.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new O(N.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=bn(n.argsSchema),s=await qs(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Ls(c);throw new O(N.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Hr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Hr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof Je?c._def?.innerType:c;return yf(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){_f(e);let l={title:r,description:n,inputSchema:ov(o),outputSchema:ov(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&_f(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Hr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Hr(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(vf(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!vf(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var n1={type:"object",properties:{}};function iv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function av(t){return"_def"in t||"_zod"in t||iv(t)}function vf(t){return typeof t!="object"||t===null||av(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(iv)}function ov(t){if(t){if(vf(t))return Hr(t);if(!av(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function o1(t){let e=sr(t);return e?Object.entries(e).map(([r,n])=>{let o=zm(n),s=Pm(n);return{name:r,description:o,required:!s}}):[]}function gr(t){let r=sr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wn(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function sv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var is={completion:{values:[],hasMore:!1}};import uv from"node:process";Vr();var s1=10*1024*1024,oa=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??s1}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
57
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),i1(r)}clear(){this._buffer=void 0}};function i1(t){return xo.parse(JSON.parse(t))}function cv(t){return JSON.stringify(t)+`
58
+ `}var sa=class{constructor(e=uv.stdin,r=uv.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new oa({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=cv(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function ia(t){if(typeof t=="string")return{text:t,hasBinary:!1};if(t==null)return{text:"",hasBinary:!1};if(!Array.isArray(t))return{text:JSON.stringify(t??""),hasBinary:!1};let e="",r=!1,n,o,s="",i;for(let a of t){if(a==null||typeof a!="object"){e+=String(a??"");continue}let c=a;switch(c.type){case"text":case"input_text":case"output_text":e+=c.text??"";break;case"tool_use":{o="tool_call",n=c.name??n;let u=`[tool call: ${c.name}] ${JSON.stringify(c.input??{})}`;e+=u,s+=u;break}case"tool_result":{o="tool_result";let u=ia(c.content);r=r||u.hasBinary,e+=u.text,c.is_error===!0&&(i=!0);break}case"image":case"document":r=!0,e+=`[${c.type}]`;break;case"image_url":case"input_image":r=!0,e+="[image]";break;case"input_audio":r=!0,e+="[audio]";break;case"file":case"input_file":r=!0,e+="[file]";break;case"thinking":e+=c.thinking??"";break;case"redacted_thinking":e+="[redacted thinking]";break;default:e+=JSON.stringify(c)}}return{text:e,hasBinary:r,toolName:n,kind:o,toolCallText:s||void 0,isError:i}}function wf(t,e){let r=t&&typeof t=="object"?t:{},n=String(r.role??"user"),o=ia(r.content),s=o.kind??(n==="developer"?"system":["system","user","assistant"].includes(n)?n:"other"),i=o.toolName,a=o.text,c=o.toolCallText;n==="tool"&&(s="tool_result");let u=r.tool_calls,l=Array.isArray(u)?u.filter(d=>d&&typeof d=="object"):void 0;if(l&&l.length>0){s="tool_call",i=l[0]?.function?.name??l[0]?.name;let d=l.map(p=>`[tool call: ${p.function?.name??p.name}] ${p.function?.arguments??JSON.stringify(p.input??{})}`).join(`
59
+ `);a+=d,c=(c??"")+d}return{index:e,role:n,kind:s,text:a,toolName:i,toolCallText:c,hasBinary:o.hasBinary,isError:o.isError}}function xf(t,e){let r=t.trimStart()[0];return{sourceFormat:"text",parseWarning:t.trim()===""?"Input is empty \u2014 nothing to profile.":e&&(r==="{"||r==="[")?`Input starts like JSON but does not parse (${e.message}), so it is not a conversation file.`:void 0,messages:t.trim()===""?[]:[{index:0,role:"user",kind:"user",text:t,hasBinary:!1}]}}function a1(t){if(typeof t=="string")return{text:t,hasBinary:!1};if(!t||typeof t!="object")return{text:"",hasBinary:!1};let e=t;if(typeof e.text=="string")return{text:e.text,hasBinary:!1};if(e.inlineData||e.fileData)return{text:"[file]",hasBinary:!0};if(e.functionCall){let r=`[tool call: ${e.functionCall.name}] ${JSON.stringify(e.functionCall.args??{})}`;return{text:r,hasBinary:!1,kind:"tool_call",toolName:e.functionCall.name,call:r}}if(e.functionResponse){let r=e.functionResponse.response;return{text:typeof r?.output=="string"?r.output:typeof r?.content=="string"?r.content:JSON.stringify(r??{}),hasBinary:!1,kind:"tool_result",toolName:e.functionResponse.name}}return e.executableCode?{text:String(e.executableCode.code??""),hasBinary:!1}:e.codeExecutionResult?{text:String(e.codeExecutionResult.output??""),hasBinary:!1}:{text:JSON.stringify(e),hasBinary:!1}}function bf(t,e){let r=t&&typeof t=="object"?t:{},n=r.role==="model"?"assistant":String(r.role??"user"),o=Array.isArray(r.parts)?r.parts:[],s="",i=!1,a,c,u="";for(let d of o){let p=a1(d);s+=(s&&p.text?`
60
+ `:"")+p.text,i||=p.hasBinary,p.kind&&(a=p.kind),c??=p.toolName,p.call&&(u+=p.call)}let l=["system","user","assistant"].includes(n)?n:"other";return{index:e,role:n,kind:a??l,text:s,toolName:c,toolCallText:u||void 0,hasBinary:i}}function c1(t,e){if(typeof t=="string")return{index:e,role:"user",kind:"user",text:t,hasBinary:!1};let r=t&&typeof t=="object"?t:{},n=r.type;if(n==="function_call"||n==="custom_tool_call"||n==="local_shell_call"){let o=r.name??(n==="local_shell_call"?"local_shell":void 0),s=typeof r.arguments=="string"?r.arguments:JSON.stringify(r.input??r.action??{}),i=`[tool call: ${o}] ${s}`;return{index:e,role:"assistant",kind:"tool_call",text:i,toolName:o,toolCallText:i,hasBinary:!1}}if(n==="function_call_output"||n==="custom_tool_call_output"||n==="local_shell_call_output"){let o=r.output,s=typeof o=="string"?{text:o,hasBinary:!1}:ia(o);return{index:e,role:"tool",kind:"tool_result",text:s.text,hasBinary:s.hasBinary}}if(n==="reasoning"){let o=Array.isArray(r.summary)?r.summary.map(s=>s?.text??"").join(`
61
+ `):"";return{index:e,role:"assistant",kind:"assistant",text:o,hasBinary:!1}}return wf(r,e)}function lv(t){if(typeof t!="string")if(t!==null&&typeof t=="object")try{t=JSON.stringify(t)}catch{return xf("")}else t=t==null?"":String(t);let e;try{e=JSON.parse(t)}catch(l){return xf(t,l)}if(e===null||typeof e!="object")return xf(t);if(Array.isArray(e)){let l=e.length===0||e.some(d=>d&&typeof d=="object"&&("role"in d||"parts"in d));return e.length>0&&e.every(d=>d&&typeof d=="object"&&Array.isArray(d.parts))?{sourceFormat:"gemini",messages:e.map((d,p)=>bf(d,p))}:{sourceFormat:"array",parseWarning:l?void 0:"This is a JSON array, but no element has a `role` field \u2014 it does not look like a conversation.",messages:e.map((d,p)=>wf(d,p))}}let r=e,n=typeof r.model=="string"&&r.model?r.model:void 0;if(r.messages==null&&Array.isArray(r.contents)){let l=[],d=r.systemInstruction??r.system_instruction;if(d!=null){let p=typeof d=="string"?{text:d,hasBinary:!1}:bf(d,-1);l.push({index:-1,role:"system",kind:"system",text:p.text,hasBinary:p.hasBinary})}return l.push(...r.contents.map((p,m)=>bf(p,m))),{sourceFormat:"gemini",messages:l,model:n}}if(r.messages==null&&(typeof r.input=="string"||Array.isArray(r.input))){let l=[];typeof r.instructions=="string"&&r.instructions&&l.push({index:-1,role:"system",kind:"system",text:r.instructions,hasBinary:!1});let d=typeof r.input=="string"?[r.input]:r.input;return l.push(...d.map((p,m)=>c1(p,m))),{sourceFormat:"responses",messages:l,model:n}}let o=r.messages,s=Array.isArray(o)?o:[],i=o!=null&&!Array.isArray(o),a=[];if(r.system!=null){let l=ia(r.system);a.push({index:-1,role:"system",kind:"system",text:l.text,hasBinary:l.hasBinary})}a.push(...s.map((l,d)=>wf(l,d)));let c=r.system!=null||s.some(l=>Array.isArray(l?.content)&&l.content.some(d=>d?.type==="tool_use"||d?.type==="tool_result")),u=i?`\`messages\` is a ${typeof o}, not an array \u2014 this file is malformed.`:a.length===0?'This JSON has no `messages` array (and no `system`) \u2014 it does not look like a conversation. Expected {"messages":[{"role":\u2026,"content":\u2026}]}.':void 0;return{sourceFormat:c?"anthropic":"openai",parseWarning:u,messages:a,model:n}}import{createHash as O1}from"node:crypto";var dv=[[/claude.*haiku/i,2e5],[/claude.*(fable|mythos)|claude.*opus-?(5|4-[678])|claude.*sonnet-?(5|4-6)/i,1e6],[/claude.*sonnet|claude.*opus|claude-\d/i,2e5],[/gpt-5/i,4e5],[/gpt-4o|gpt-4-turbo|gpt-4\.1|o[134](-|$)/i,128e3],[/gpt-4(?!o|\.|-turbo)/i,8192],[/gpt-3\.5/i,16385],[/gemini.*(1\.5|2\.|2-5)/i,1e6],[/gemini-?3/i,1048576],[/llama.*3/i,128e3],[/mistral|mixtral/i,32e3]],QD=Math.max(...dv.map(([,t])=>t));function aa(t){if(t){for(let[e,r]of dv)if(e.test(t))return r}}function on(t){return t?/claude/i.test(t)?"anthropic":/gpt|^o\d/i.test(t)?"openai":/gemini/i.test(t)?"google":"generic":"generic"}function u1(t){return t.length===0?0:(t.match(/[{}[\]()<>;:=_\/\\|"'`#$%&*+^~-]/g)?.length??0)/t.length}var ca={anthropic:{prose:2.75,code:2.4},openai:{prose:4,code:3.2},google:{prose:4,code:3.2},generic:{prose:4,code:3.2}};function l1(t){return u1(t)>.08}function ua(t,e){let r=ca[on(e)];return l1(t)?r.code:r.prose}function sn(t,e){return typeof t!="string"&&(t=String(t??"")),t?Math.ceil(t.length/ua(t,e)):0}var $f=4;function H(t){if(!Number.isFinite(t))return"0";if(t<0)return`-${H(-t)}`;let e=Math.round(t);if(e<1e3)return String(e);let r=Math.round(e/100);if(r<100)return`${(r/10).toFixed(1)}k`;let n=Math.round(e/1e3);if(n<1e3)return`${n}k`;let o=Math.round(e/1e5);return o<1e4?`${(o/10).toFixed(1)}M`:`${(Math.round(e/1e8)/10).toFixed(1)}B`}var ie=(t,e,r)=>({inputPerM:t,outputPerM:e,cacheReadPerM:r});function Ne(t,e,r){return r===void 0?new RegExp(`claude-(?:${t})-${e}(?![.\\d]|-\\d{1,2}(?!\\d))`,"i"):new RegExp(`claude-(?:${t})-${e}[-.]${r}(?!\\d)`,"i")}var la=[/claude.*fable|claude.*mythos/i,/claude.*opus/i,/claude.*sonnet/i,/claude.*haiku/i],d1=[[Ne("fable|mythos",5,1),ie(10,50,.25)],[Ne("fable|mythos",5),ie(10,50,1)],[Ne("opus",5,5),ie(4,20,.2)],[Ne("opus",5),ie(5,25,.5)],[Ne("opus",4,8),ie(5,25,.5)],[Ne("opus",4,7),ie(5,25,.5)],[Ne("opus",4,6),ie(5,25,.5)],[Ne("opus",4,5),ie(5,25,.5)],[Ne("opus",4,1),ie(15,75,1.5)],[Ne("opus",4),ie(15,75,1.5)],[/claude-3-opus/i,ie(15,75,1.5)],[Ne("sonnet",5,5),ie(2,10,.2)],[Ne("sonnet",5),ie(2,10,.2)],[Ne("haiku",5,5),ie(.1,.5,.01)],[Ne("haiku",4,5),ie(1,5,.1)],[/claude-3-5-haiku/i,ie(.8,4,.08)],[/claude-3-haiku/i,ie(.25,1.25,.03)],[Ne("sonnet",4,6),ie(3,15,.3)],[Ne("sonnet",4,5),ie(3,15,.3)],[Ne("sonnet",4),ie(3,15,.3)],[/claude-3-[57]-sonnet/i,ie(3,15,.3)],[la[0],ie(10,50,1)],[la[1],ie(5,25,.5)],[la[2],ie(3,15,.3)],[la[3],ie(1,5,.1)],[/gpt-5.*(mini|nano)/i,{inputPerM:.25,outputPerM:2,cacheReadPerM:.025}],[/gpt-5/i,{inputPerM:1.25,outputPerM:10,cacheReadPerM:.125}],[/gpt-4o-mini/i,{inputPerM:.15,outputPerM:.6,cacheReadPerM:.075}],[/gpt-4o|gpt-4\.1/i,{inputPerM:2.5,outputPerM:10,cacheReadPerM:1.25}],[/gpt-4-turbo/i,{inputPerM:10,outputPerM:30,cacheReadPerM:10}],[/o[13](-|$)/i,{inputPerM:2,outputPerM:8,cacheReadPerM:1}],[/gemini-3[.\d]*-flash-lite/i,ie(.3,2.5,.03)],[/gemini-3\.1-flash-lite/i,ie(.25,1.5,.025)],[/gemini-3-flash/i,ie(.5,3,.05)],[/gemini-3[.\d]*-flash/i,ie(.75,3.75,.075)],[/gemini-3[.\d]*-pro/i,ie(2,12,.2)],[/gemini.*flash/i,{inputPerM:.1,outputPerM:.4,cacheReadPerM:.025}],[/gemini.*pro/i,{inputPerM:1.25,outputPerM:5,cacheReadPerM:.31}]];function da(t){if(t){for(let[e,r]of d1)if(e.test(t))return r}}function as(t,e){return t/1e6*e.inputPerM}function kf(t){return t/25e3}function an(t){return Number.isFinite(t)?t>=1?`$${t.toFixed(2)}`:t>=.01?`$${t.toFixed(3)}`:`$${t.toFixed(4)}`:"$0.00"}var fv=/(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g,f1="[context-doctor: base64 blob removed \u2014 use file/image APIs instead]";function pv(t){if(t.startsWith("data:"))return!0;let e=new Map;for(let n of t)e.set(n,(e.get(n)??0)+1);if(e.size<24)return!1;let r=0;for(let n of e.values())n>r&&(r=n);return r/t.length<.35}function Jn(t){for(let e of t.matchAll(fv))if(pv(e[0]))return!0;return!1}function Sf(t){return t.replace(fv,e=>pv(e)?f1:e)}import{mkdirSync as c2,readFileSync as $1,writeFileSync as u2}from"node:fs";import{dirname as k1,join as S1}from"node:path";import{appendFileSync as p1,existsSync as m1,mkdirSync as h1,readFileSync as g1,statSync as y1,writeFileSync as _1}from"node:fs";import{homedir as v1}from"node:os";import{dirname as mv,join as hv}from"node:path";var x1={optimizeSaved:0,optimizeUsd:0,proxySaved:0,proxyUsd:0,proxyRequests:0,checks:0,warnings:0,shrinkage:0};function b1(t){let e={...x1},r=new Map;for(let n of t){if(n.ev==="rollup"&&n.carried){e.optimizeSaved+=n.carried.optimizeSaved,e.optimizeUsd+=n.carried.optimizeUsd,e.proxySaved+=n.carried.proxySaved,e.proxyUsd+=n.carried.proxyUsd,e.proxyRequests+=n.carried.proxyRequests,e.checks+=n.carried.checks,e.warnings+=n.carried.warnings,e.shrinkage+=n.carried.shrinkage,n.carried.since&&(e.since=Math.min(e.since??n.carried.since,n.carried.since));continue}e.since=Math.min(e.since??n.ts,n.ts),n.ev==="optimize"?(e.optimizeSaved+=n.saved??0,e.optimizeUsd+=n.usd??0):n.ev==="proxy"?(e.proxySaved+=n.saved??0,e.proxyUsd+=n.usd??0,e.proxyRequests+=n.requests??0):(n.ev==="check"||n.ev===void 0)&&n.sid!=="doctor-probe"&&(e.checks++,n.warn&&e.warnings++,n.sid&&n.sid!=="mcp-sketch"&&typeof n.tok=="number"&&r.set(n.sid,[...r.get(n.sid)??[],n.tok]))}for(let n of r.values())for(let o=1;o<n.length;o++)n[o]<n[o-1]&&(e.shrinkage+=n[o-1]-n[o]);return e}function Ef(){return process.env.CONTEXT_DOCTOR_HOOK_STATE??hv(v1(),".claude",".context-doctor-hook-state.json")}function w1(){return hv(mv(Ef()),".context-doctor-ledger.jsonl")}function fa(t){let e=w1();try{if(h1(mv(e),{recursive:!0}),m1(e)&&y1(e).size>256*1024){let r=g1(e,"utf8").trimEnd().split(`
62
+ `),n=c=>{try{return[JSON.parse(c)]}catch{return[]}},o=r.slice(-500),s=r.slice(0,-500).flatMap(n),i=b1(s),a={ts:Date.now(),ev:"rollup",carried:i};_1(e,[JSON.stringify(a),...o].join(`
63
63
  `)+`
64
- `)}d1(e,JSON.stringify({ts:Date.now(),...t})+`
65
- `)}catch{}}var k1=2,S1=.5,E1=2;function T1(){return $1(w1(Sf()),".context-doctor-calibration.json")}function z1(t){let e=(t??"").toLowerCase();return e.includes("claude")?"claude":/gpt|^o\d/.test(e)?"gpt":e.includes("gemini")?"gemini":e?e.split(/[-_/]/)[0]:"unknown"}function P1(){try{return JSON.parse(b1(T1(),"utf8"))}catch{return{}}}function hv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=P1()[z1(t)];if(!e||e.v!==k1||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<S1||r>E1?{factor:1,samples:0}:{factor:r,samples:e.samples}}function I1(t){switch(t.kind){case"system":return"system";case"user":return"user";case"assistant":return"assistant";case"tool_call":return"tool_calls";case"tool_result":return"tool_results";default:return"other"}}function O1(t,e){let r=new Map,n=0;for(let a of t){if(a.estSavings<=0)continue;if(a.messages.length===0){n+=a.estSavings;continue}let c=a.id==="near_duplicate"&&a.messages.length>2?a.messages.slice(1):[a.messages[a.messages.length-1]],u=a.estSavings/c.length;for(let l of c)r.set(l,Math.max(r.get(l)??0,u))}let o=Math.round([...r.values()].reduce((a,c)=>a+c,0)),s=Math.max(0,e-o),i=o+Math.min(n,s);return Math.min(i,Math.round(e*.9))}function C1(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function gv(t){return R1("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function A1(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return e>>>0}function N1(t){let e=t.toLowerCase().replace(/\s+/g," ").trim().split(" "),r=e.length>1500,n=new Set;for(let o=0;o+8<=e.length;o++){let s=A1(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var yv=.6;function M1(t,e){if(t.size===0||e.size===0)return 0;let r=0,[n,o]=t.size<=e.size?[t,e]:[e,t];for(let s of n)o.has(s)&&r++;return r/(t.size+e.size-r)}var _v=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function j1(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function Z1(t,e){if(/read|open|cat|view|get_file/i.test(t??"")){let n=/"(?:file_path|filePath|path|file)"\s*:\s*"([^"]{3,})"/.exec(e);if(n)return[n[1]]}if(!/bash|shell|terminal|exec|run_command/i.test(t??""))return[];let r=new Set;_v.lastIndex=0;for(let n of e.matchAll(_v)){let o=n[2].replace(/\\+$/,"");j1(o)&&r.add(o)}return[...r]}function vv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=hv(r),o=t.messages.map(g=>({msg:g,tokens:Math.round(sn(g.text,r)*n.factor)+wf})),s=o.reduce((g,x)=>g+x.tokens,0),i={system:0,user:0,assistant:0,tool_calls:0,tool_results:0,other:0};for(let g of o)i[I1(g.msg)]+=g.tokens;let a=[];for(let g of o)g.msg.kind==="tool_result"&&g.tokens>2e3&&a.push({id:"large_tool_result",severity:g.tokens>8e3?"high":"warn",estSavings:Math.round(g.tokens*.8),message:`Tool result at message #${g.msg.index}${g.msg.toolName?` (${g.msg.toolName})`:""} is ~${g.tokens} tokens.`,suggestion:"Truncate or summarize large tool outputs before they enter history; keep only the fields the model actually used.",messages:[g.msg.index]});for(let g of o)g.msg.kind==="tool_call"&&g.tokens>2e3&&a.push({id:"large_tool_call",severity:g.tokens>8e3?"high":"warn",estSavings:Math.round(g.tokens*.8),message:`Tool call at message #${g.msg.index}${g.msg.toolName?` (${g.msg.toolName})`:""} carries ~${g.tokens} tokens of arguments.`,suggestion:'Usually a whole file being written inline. Once it has run, replace the arguments with a reference ("wrote <path>") \u2014 or write files in smaller pieces so no single call carries the entire content.',messages:[g.msg.index]});let c=new Map;for(let g of o){if(g.msg.text.length<300)continue;let x=gv(g.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:g.tokens-wf,message:`Message #${g.msg.index} duplicates the content of message #${$} (~${g.tokens} tokens).`,suggestion:"Replace repeated content with a short reference to the first occurrence.",messages:[$,g.msg.index]}):c.set(x,g.msg.index)}{let g=o.filter(L=>L.msg.text.length>=300).sort((L,_e)=>_e.tokens-L.tokens).slice(0,150),x=g.map(L=>N1(L.msg.text)),$=x.map(L=>L.size),D=new Set(a.filter(L=>L.id==="duplicate_content").flatMap(L=>L.messages)),R=g.map((L,_e)=>_e),ie=L=>{for(;R[L]!==L;)L=R[L]=R[R[L]];return L},ae=g.map(()=>({sim:0,partnerTokens:0}));for(let L=0;L<g.length;L++)for(let _e=L+1;_e<g.length;_e++){let $t=g[L],xr=g[_e];if(D.has($t.msg.index)&&D.has(xr.msg.index))continue;let ps=Math.min($[L],$[_e]),cn=Math.max($[L],$[_e]);if(cn===0||ps/cn<yv)continue;let ft=M1(x[L],x[_e]);ft<yv||(R[ie(L)]=ie(_e),ft>ae[L].sim&&(ae[L]={sim:ft,partnerTokens:xr.tokens}),ft>ae[_e].sim&&(ae[_e]={sim:ft,partnerTokens:$t.tokens}))}let Te=new Map;g.forEach((L,_e)=>{if(ae[_e].sim===0)return;let $t=ie(_e);Te.set($t,[...Te.get($t)??[],_e])});for(let L of Te.values()){if(L.length<2)continue;L.sort((pt,br)=>g[pt].msg.index-g[br].msg.index);let _e=L.slice(1),$t=_e.reduce((pt,br)=>pt+Math.round(Math.min(g[br].tokens,ae[br].partnerTokens)*ae[br].sim*.9),0),xr=L.map(pt=>ae[pt].sim),ps=Math.round(Math.min(...xr)*100),cn=Math.round(Math.max(...xr)*100),ft=L.map(pt=>g[pt].msg.index),Wf=ps===cn?`~${cn}%`:`${ps}-${cn}%`,O0=_e.reduce((pt,br)=>pt+g[br].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:$t,message:L.length===2?`Messages #${ft[0]} and #${ft[1]} are ${Wf} similar (~${Math.min(g[L[0]].tokens,g[L[1]].tokens)} tokens repeated with different framing).`:`${L.length} messages are ${Wf} similar to each other (${ft.slice(0,6).map(pt=>`#${pt}`).join(", ")}${ft.length>6?", \u2026":""}): ~${H(O0)} tokens in the ${_e.length} later copies repeat the first with different framing.`,suggestion:"Replace the later copies with a short reference to the first \u2014 repeats survive even when the surrounding words differ.",messages:ft})}}let u=new Map;for(let g of o){if(g.msg.kind!=="tool_call"||!g.msg.toolCallText)continue;let x=gv(g.msg.toolCallText),$=u.get(x)??[];$.push(g.msg.index),u.set(x,$)}let l=g=>o.find(x=>x.msg.index>g&&x.msg.kind==="tool_result")?.msg;for(let[,g]of u){if(g.length<2)continue;let x=g.slice(1).filter((D,R)=>l(g[R])?.isError===!0).length,$=g.length-1-x;x>0&&a.push({id:"retried_tool_call",severity:x>=3?"warn":"info",estSavings:0,message:`The same tool call was retried ${x} time(s) after it failed (messages #${g.join(", #")}).`,suggestion:x>=3?"Three or more identical retries of a failing command is a loop. Each attempt keeps its error output in context; the answer is in the first error, not in the fourth attempt.":"A retry after a failure is normal once. The failed attempt's output stays in context though, so once the fix is understood the earlier error can go.",messages:g}),$>0&&a.push({id:"repeated_tool_call",severity:"info",estSavings:0,message:`The same tool call (with identical arguments) was repeated ${$} time(s) after it had already succeeded (messages #${g.join(", #")}).`,suggestion:"Repeating a call that already succeeded means the earlier result scrolled out of the model's attention \u2014 keep results in a compact recap instead of re-calling.",messages:g})}{let g=new Map;for(let x of o)if(!(x.msg.kind!=="tool_call"||!x.msg.toolCallText))for(let $ of Z1(x.msg.toolName,x.msg.toolCallText))g.set($,[...g.get($)??[],x.msg.index]);for(let[x,$]of g){if($.length<3)continue;let D=o.filter(ie=>ie.msg.kind==="tool_result"&&$.some(ae=>ie.msg.index===ae+1)).reduce((ie,ae)=>ie+ae.tokens,0),R=Math.round(D*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:R>4e3?"high":"warn",estSavings:R,message:`${x.split("/").pop()} was read ${$.length} times (messages #${$.join(", #")}), keeping ${$.length} copies in context.`,suggestion:"Re-read a file only after it changes; otherwise refer back to the copy already in context.",messages:$})}}for(let g of o)g.msg.kind!=="tool_result"||g.tokens<500||!/Traceback \(most recent call last\)|command not found|npm error|ERR!|\bexit code [1-9]|Exception in thread|FAILED|error TS\d+/i.test(g.msg.text)||a.push({id:"retained_error_output",severity:"warn",estSavings:Math.round(g.tokens*.85),message:`Message #${g.msg.index} holds ~${g.tokens} tokens of failed tool output (errors, stack trace or non-zero exit).`,suggestion:"Keep the one line that identifies the failure and drop the rest \u2014 a full trace has no value once the fix is understood.",messages:[g.msg.index]});for(let g of o)Jn(g.msg.text)&&a.push({id:"base64_blob",severity:"high",estSavings:Math.round(g.tokens*.9),message:`Message #${g.msg.index} contains a base64/binary blob (~${g.tokens} tokens of mostly meaningless characters).`,suggestion:"Never put base64 in text content \u2014 use the provider's file/image APIs or replace with a file reference.",messages:[g.msg.index]});let d=t.messages.filter(g=>g.kind==="user"||g.kind==="assistant").length;if(d>40){let x=o.slice(0,Math.floor(o.length/2)).reduce(($,D)=>$+D.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${x} tokens.`,suggestion:"Summarize the older half of the conversation into a compact recap and drop the raw turns (context-doctor optimize --strategy prune-history).",messages:[]})}s>0&&i.system/s>.25&&i.system>2e3&&a.push({id:"large_system_prompt",severity:"info",estSavings:0,message:`System prompt is ~${i.system} tokens (${Math.round(i.system/s*100)}% of the context).`,suggestion:"A big system prompt is fine IF it is stable \u2014 put it first and use prompt caching (Anthropic: cache_control; OpenAI: automatic prefix caching) so you stop paying full price for it every call.",messages:[]}),(on(e)==="anthropic"||on(e)==="openai")&&a.push({id:"cache_ordering",severity:"info",estSavings:0,message:"Prompt caching only matches a byte-identical prefix.",suggestion:"Keep stable content (system prompt, tool definitions, reference docs) at the start and never interleave it with per-request content \u2014 a single changed byte early in the prompt invalidates the cache for everything after it.",messages:[]});let p=aa(e),m=p?s/p*100:void 0;m!==void 0&&m>70&&a.push({id:"near_window_limit",severity:m>90?"high":"warn",estSavings:0,message:`Context is at ~${m.toFixed(0)}% of ${e}'s window.`,suggestion:"Models degrade well before the hard limit (lost-in-the-middle). Compact now rather than when the request fails.",messages:[]});let f=o.map(g=>({index:g.msg.index,role:g.msg.role,kind:g.msg.kind,tokens:g.tokens,preview:C1(g.msg.text),toolName:g.msg.toolName})).sort((g,x)=>x.tokens-g.tokens).slice(0,5),h={high:0,warn:1,info:2};a.sort((g,x)=>h[g.severity]-h[x.severity]||x.estSavings-g.estSavings);let y=O1(a,s),_=la(e),v;if(_){let g=as(s,_),x=as(y,_);v={perCallUsd:g,per1kCallsUsd:g*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:$f(s),ttftSavedSeconds:$f(y)}}return{totalTokens:s,model:e,contextWindow:p,usagePct:m,messageCount:t.messages.length,categories:i,largestMessages:f,findings:a,totalEstSavings:y,cost:v,sourceFormat:t.sourceFormat,calibration:n.samples>0?n:void 0,parseWarning:t.parseWarning}}import{createHash as D1}from"node:crypto";var wv=10,fa={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:wv};function q1(t){if(t?.name==="Write"&&typeof t.input?.file_path=="string")return t.input.file_path;let e=t?.name==="Bash"?String(t.input?.command??""):"",r=/(?:cat|tee)\s*>+\s*([^\s<]+)\s*<</.exec(e);return r?r[1]:null}function L1(t,e,r){if(!r)return!1;for(let n=e+1;n<t.length;n++){let o=t[n]?.content;if(Array.isArray(o))for(let s of o){if(s?.type!=="tool_use")continue;let i=s.input?.file_path,a=s.name==="Bash"?String(s.input?.command??""):"";if(i===r||a.includes(r)){if(s.name==="Read"||/\b(cat|head|tail|sed|less)\b/.test(a))return!1;if(s.name==="Edit"||s.name==="MultiEdit")return!0}}}return!1}function xv(t,e,r){let n=Math.round(e*ua("",r)),o={};for(let[s,i]of Object.entries(t))typeof i=="string"&&i.length>n?o[s]=i.slice(0,n)+`
66
- [context-doctor: ${i.length-n} more chars trimmed \u2014 this call already ran]`:o[s]=i;return o}function Ef(t,e,r=wv){let n=t-e;return n<=0?0:n<r?n:Math.floor(n/r)*r}function U1(t){return D1("sha1").update(t.trim()).digest("hex")}function Wn(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"?e.text??"":e?.type==="tool_result"?Wn(e.content):e?.type==="tool_use"?JSON.stringify(e.input??{}):"").join(`
67
- `):JSON.stringify(t)}function Tf(t,e){let r=t?.content,n=t?.role==="tool"?"tool_result":"text",o=(s,i)=>{let a=s.filter(d=>d?.type==="text"&&typeof d.text=="string");if(a.length===0)return s;let c=a.map(d=>d.text).join(`
68
- `),u=e(c,i);if(u===c)return s;let l=!1;return s.map(d=>d?.type==="text"&&typeof d.text=="string"?l?null:(l=!0,{...d,text:u}):d).filter(d=>d!==null)};return typeof r=="string"?e(r,n):Array.isArray(r)?n==="tool_result"?o(r,n):r.map(s=>{if(s?.type==="text"&&typeof s.text=="string"){let i=e(s.text,"text");return i===s.text?s:{...s,text:i}}if(s?.type==="tool_result"){if(typeof s.content=="string"){let i=e(s.content,"tool_result");return i===s.content?s:{...s,content:i}}if(Array.isArray(s.content)){let i=o(s.content,"tool_result");return i===s.content?s:{...s,content:i}}}return s}):r}function zf(t){return typeof t=="string"?Jn(t)?kf(t):t:Array.isArray(t)?t.map(zf):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,zf(r)])):t}function F1(t,e,r){let n=Math.round(e*ua(t,r));if(t.length<=n)return t;let o=t.slice(0,n),s=t.length-n;return`${o}
69
- \u2026[context-doctor: trimmed ${s} chars of stale tool output]`}function H1(t){let e=new Set;for(let r of t)if(Array.isArray(r?.content))for(let n of r.content)n?.type==="tool_use"&&n.id&&e.add(n.id);for(let r of t){if(!Array.isArray(r?.content))continue;let n=r.content.filter(o=>o?.type!=="tool_result"||o.tool_use_id&&e.has(o.tool_use_id));n.length!==r.content.length&&(r.content=n.length>0?n:[{type:"text",text:"[context-doctor: earlier tool result dropped with the pruned history]"}])}}function bv(t){return t?.role==="tool"?!0:Array.isArray(t?.content)?t.content.some(e=>e?.type==="tool_result"):!1}function $v(t,e={}){let r={strategies:e.strategies??fa.strategies,keepRecent:e.keepRecent??fa.keepRecent,maxToolResultTokens:e.maxToolResultTokens??fa.maxToolResultTokens,trimBoundaryStep:e.trimBoundaryStep&&e.trimBoundaryStep>0?Math.floor(e.trimBoundaryStep):fa.trimBoundaryStep},n;try{n=JSON.parse(t)}catch{throw new Error("optimize requires a JSON conversation (message array, or object with a `messages` field)")}let o=Array.isArray(n)?n:n?.messages;if(!Array.isArray(o))throw Array.isArray(n?.contents)||typeof n?.input=="string"||Array.isArray(n?.input)?new Error(`optimize rewrites a \`messages\` array (Anthropic or OpenAI chat); this is ${Array.isArray(n?.contents)?"a Gemini `contents`":"an OpenAI Responses `input`"} request. Profile it with analyze (or profile_context); the autopilot proxy slims these requests live.`):new Error("No `messages` array found in input");for(let y=o.length-1;y>=0;y--)(!o[y]||typeof o[y]!="object")&&o.splice(y,1);let s=!Array.isArray(n)&&n?.system!=null||o.some(y=>Array.isArray(y?.content)&&y.content.some(_=>_?.type==="tool_use"||_?.type==="tool_result")),i=e.model??(!Array.isArray(n)&&typeof n?.model=="string"?n.model:void 0)??(s?"claude":void 0),a=y=>sn(y,i),c=Array.isArray(n)?0:(n?.system!=null?a(typeof n.system=="string"?n.system:Wn(n.system)):0)+(n?.tools!=null?a(JSON.stringify(n.tools)):0),u=y=>{let _=a(Wn(y.content));for(let v of Array.isArray(y.tool_calls)?y.tool_calls:[]){let g=v?.function;g&&(_+=a(`${g.name??""} ${typeof g.arguments=="string"?g.arguments:JSON.stringify(g.arguments??{})}`))}return y.function_call&&(_+=a(`${y.function_call.name??""} ${y.function_call.arguments??""}`)),_},l=c+o.reduce((y,_)=>y+u(_),0),d=[];if(r.strategies.includes("strip-base64")&&o.forEach((y,_)=>{let v=Wn(y.content);if(!Jn(v))return;let g=a(v),x=Tf(y,D=>Jn(D)?kf(D):D);Array.isArray(x)&&(x=x.map(D=>D?.type==="tool_use"&&D.input!=null?{...D,input:zf(D.input)}:D));let $=g-a(Wn(x));$>50&&(y.content=x,d.push({strategy:"strip-base64",messageIndex:_,tokensSaved:$,note:"Removed inline base64 data"}))}),r.strategies.includes("dedupe")){let y=Ef(o.length,r.keepRecent,r.trimBoundaryStep),_=new Map;o.forEach((v,g)=>{let x=0,$,D=Tf(v,R=>{if(R.length<300)return R;let ie=U1(R),ae=_.get(ie);if(ae===void 0)return _.set(ie,g),R;if(g>=y)return R;let Te=`[context-doctor: identical to message #${ae} \u2014 content removed]`;return x+=a(R)-a(Te),$??=ae,Te});x<=0||(v.content=D,d.push({strategy:"dedupe",messageIndex:g,tokensSaved:x,note:`Duplicate of message #${$}`}))})}if(r.strategies.includes("trim-tool-results")){let y=Ef(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=y||!bv(_))return;let g=0,x=Tf(_,($,D)=>{if(D!=="tool_result")return $;let R=a($);if(R<=r.maxToolResultTokens)return $;let ie=F1($,r.maxToolResultTokens,i),ae=a(ie);return ae>=R?$:(g+=R-ae,ie)});g<=0||(_.content=x,d.push({strategy:"trim-tool-results",messageIndex:v,tokensSaved:g,note:"Stale tool result truncated"}))})}if(r.strategies.includes("trim-tool-calls")){let y=Ef(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=y)return;let g=0;if(Array.isArray(_.content))for(let x of _.content){if(x?.type!=="tool_use"||x.input==null||typeof x.input!="object"||L1(o,v,q1(x)))continue;let $=a(JSON.stringify(x.input));if($<=r.maxToolResultTokens)continue;let D=xv(x.input,r.maxToolResultTokens,i),R=a(JSON.stringify(D));R>=$||(x.input=D,g+=$-R)}for(let x of _.tool_calls??[]){let $=x?.function?.arguments;if(typeof $!="string")continue;let D=a($);if(D<=r.maxToolResultTokens)continue;let R;try{R=JSON.parse($)}catch{continue}if(!R||typeof R!="object"||Array.isArray(R))continue;let ie=JSON.stringify(xv(R,r.maxToolResultTokens,i)),ae=a(ie);ae>=D||(x.function.arguments=ie,g+=D-ae)}g>0&&d.push({strategy:"trim-tool-calls",messageIndex:v,tokensSaved:g,note:"Arguments of a completed tool call truncated"})})}let p,m=0;for(;m<o.length&&(o[m]?.role==="system"||o[m]?.role==="developer");)m++;let f=Math.max(2,r.keepRecent);if(r.strategies.includes("prune-history")&&o.length-m>f*2){let y=o.length-f;for(;y<o.length&&bv(o[y]);)y++;if(o.length-y>=2){H1(o.slice(y));let _=o.slice(m,y),v=_.reduce((x,$)=>x+u($),0);p=_.map((x,$)=>`[${m+$}:${x.role}] ${Wn(x.content).replace(/\s+/g," ").slice(0,200)}`).join(`
70
- `);let g={role:"user",content:`[context-doctor: ${_.length} earlier messages (~${v} tokens) pruned. Replace this stub with an LLM-written summary of those turns for best results.]`};o.splice(m,y-m,g),d.push({strategy:"prune-history",messageIndex:m,tokensSaved:v-a(g.content),note:`Pruned ${_.length} old messages`})}}let h=c+o.reduce((y,_)=>y+u(_),0);return{conversation:n,tokensBefore:l,tokensAfter:h,applied:d,prunedDigest:p}}var kv={system:"System prompt",user:"User messages",assistant:"Assistant replies",tool_calls:"Tool calls",tool_results:"Tool results",other:"Other"},V1={high:"\u2716",warn:"\u25B2",info:"\u2139"};function B1(t,e=28){let r=Math.round(t*e);return"\u2588".repeat(r)+"\u2591".repeat(e-r)}function J1(t){return t.replace(/(?:[A-Za-z]:)?(?:~|\.{1,2})?(?:[\\/][\w.@+-]+)+|[\w.@~+-]+(?:[\\/][\w.@+-]+)+/g,"[path]").replace(/(?<![\w.@+-])[\w@+-][\w.@+-]*\.[A-Za-z][A-Za-z0-9]{0,9}(?![\w@+-]|\.\w)/g,"[file]")}function Sv(t,e={}){let r=[],n=t;if(r.push("CONTEXT DOCTOR \u2014 profile"),r.push("\u2550".repeat(56)),n.parseWarning&&(r.push(`\u26A0 ${n.parseWarning}${n.sourceFormat==="text"&&n.messageCount>0?" Profiled as raw text below, which is almost certainly not what you want.":""}`),r.push("")),r.push(`Total: ~${H(n.totalTokens)} tokens across ${n.messageCount} messages (${n.sourceFormat} format)`),n.calibration){let i=Math.round((n.calibration.factor-1)*100);r.push(` estimates calibrated ${i>=0?"+":""}${i}% from ${n.calibration.samples} exact count(s) you ran on this machine (analyze --exact)`)}if(n.model){let i=n.contextWindow?` of ${H(n.contextWindow)} window (${n.usagePct.toFixed(1)}%)`:" (unknown window size)";r.push(`Model: ${n.model}${i}`)}n.cost&&r.push(`Cost: ~${an(n.cost.perCallUsd)} input per call \xB7 ~${an(n.cost.per1kCallsUsd)} per 1k calls \xB7 ~${n.cost.ttftSeconds.toFixed(1)}s of latency per call (estimates)`),r.push(""),r.push("Where the tokens go"),r.push("\u2500".repeat(56));let o=Object.entries(n.categories).filter(([,i])=>i>0).sort((i,a)=>a[1]-i[1]),s=Math.max(...o.map(([i])=>kv[i].length));for(let[i,a]of o){let c=n.totalTokens>0?a/n.totalTokens:0;r.push(`${kv[i].padEnd(s)} ${B1(c)} ${String(Math.round(c*100)).padStart(3)}% ~${H(a)}`)}r.push(""),r.push("Largest messages"),r.push("\u2500".repeat(56));for(let i of n.largestMessages){let a=i.toolName?`${i.kind}:${i.toolName}`:i.kind,c=e.redact?"[redacted]":i.preview;r.push(` #${i.index} [${a}] ~${H(i.tokens)} ${c}`)}if(r.push(""),n.findings.length>0){r.push(`Findings (${n.findings.length})`),r.push("\u2500".repeat(56));let i=3,a=new Map,c=new Map;for(let u of n.findings){let l=a.get(u.id)??0;if(l>=i){let m=c.get(u.id)??{count:0,savings:0};c.set(u.id,{count:m.count+1,savings:m.savings+u.estSavings});continue}a.set(u.id,l+1);let d=u.estSavings>0?` [save ~${H(u.estSavings)}]`:"";r.push(`${V1[u.severity]} ${e.redact?J1(u.message):u.message}${d}`),r.push(` \u2192 ${u.suggestion}`);let p=c.get(u.id);l+1===i&&p===void 0&&c.set(u.id,{count:0,savings:0})}for(let[u,l]of c){if(l.count===0)continue;let d=Math.min(l.savings,n.totalEstSavings),p=d>0?`, up to ~${H(d)} more recoverable`:"";r.push(` \u2026 and ${l.count} more of the same kind (${u})${p}. Use --json for the full list.`)}if(r.push(""),n.totalEstSavings>0){let u=n.totalTokens>0?Math.round(n.totalEstSavings/n.totalTokens*100):0,l=`Potential recovery: ~${H(n.totalEstSavings)} tokens (~${u}% of context)`;n.cost&&n.cost.savingsPerCallUsd>0&&(l+=` \u2248 ${an(n.cost.savingsPer1kCallsUsd)} per 1k calls, ${n.cost.ttftSavedSeconds.toFixed(1)}s faster per call`),r.push(l),r.push("Run `context-doctor optimize <file>` to apply the safe fixes automatically.")}}else r.push("No issues found \u2014 this context is in good shape.");return r.join(`
71
- `)}var W1=2060,K1={code:42,tool_result:56,paste:56,text:80,base64:76,image:0},G1=6.3,X1={paste:2400,code:2400,tool_result:2400,text:900,base64:12e3,image:0},Y1=1500,Ev=2e3,Q1=30,Tv=300,eI=6;function tI(t,e){let r=ca[on(e)];return t==="code"||t==="tool_result"||t==="base64"?r.code:r.prose}function rI(t,e){if(t.kind==="image")return t.approx_tokens&&t.approx_tokens>0?Math.round(t.approx_tokens):Y1;if(t.approx_tokens&&t.approx_tokens>0)return Math.round(t.approx_tokens);let r=t.approx_chars&&t.approx_chars>0?t.approx_chars:t.approx_lines&&t.approx_lines>0?t.approx_lines*K1[t.kind]:t.approx_words&&t.approx_words>0?t.approx_words*G1:X1[t.kind];return Math.round(r/tI(t.kind,e))}function nI(t){return Math.round(W1/ca[on(t)].prose)}var zv=60;function oI(t){let e=String(t??"").replace(/\s+/g," ").trim()||"unnamed block";return e.length>zv?e.slice(0,zv-1)+"\u2026":e}function sI(t){let e=Math.max(0,Math.floor(t.turns||0)),r=(Array.isArray(t.blocks)?t.blocks:[]).map(_=>({..._,label:oI(_?.label)})),n=nI(t.model),o=e*n,s=r.map(_=>({block:_,tokens:rI(_,t.model),copies:Math.max(1,Math.floor(_.repeated??1))})),i=s.reduce((_,v)=>_+v.tokens*v.copies,0),a=o+i,c=[];for(let{block:_,tokens:v,copies:g}of s){if(g>1&&c.push({id:"duplicate_block",severity:"warn",estSavings:v*(g-1),message:`"${_.label}" appears ${g} times (~${H(v)} each).`,action:`Refer to "${_.label}" by name from now on; never re-quote it.`}),_.kind==="base64"){c.push({id:"base64_blob",severity:"high",estSavings:Math.max(0,v-50),message:`"${_.label}" is inline base64 (~${H(v)}), which the model cannot read anyway.`,action:`Drop it: describe "${_.label}" in one line and ask the user to attach it as a file if needed.`});continue}if(_.kind!=="image"&&v>=Ev){let x=_.stale?Math.max(0,v-100):Math.round(v*.7);c.push({id:"large_block",severity:v>=4*Ev?"high":"warn",estSavings:x,message:`"${_.label}" (turn ${_.turn}, ${_.kind}) is ~${H(v)}${_.stale?" and already acted on":""}.`,action:_.stale?`Replace "${_.label}" with a one-line note of what it was and what came of it.`:`Summarize "${_.label}" into the points still needed (facts, identifiers, decisions) and work from the summary.`})}}let u=s.filter(_=>_.block.kind==="image");if(u.length>=3){let _=u.reduce((v,g)=>v+g.tokens*g.copies,0);c.push({id:"many_images",severity:"info",estSavings:0,message:`${u.length} images (~${H(_)}) ride along on every turn.`,action:"Once an image has been read, describe what it showed in a sentence so it need not be looked at again; new chats should get only the images still needed."})}if(e>=Q1){let _=eI*n+Tv;c.push({id:"long_history",severity:a>1e5?"high":"warn",estSavings:Math.max(0,a-_),message:`${e} turns: every new message re-reads ~${H(a)}.`,action:`Offer a handoff: write a \u2264${Tv}-token summary (decisions, current state, open items, key identifiers) for the user to start a new chat with. A fresh chat re-reads ~${H(_)} of conversation instead, plus the app's own system prompt, which every chat carries.`})}let l=aa(t.model),d=l?Math.round(a/l*100):void 0;d!==void 0&&d>=70&&c.push({id:"near_window_limit",severity:"high",estSavings:0,message:`~${d}% of the ${H(l)} window. Quality drops and the app may start dropping early turns.`,action:"Do the handoff now rather than at the next problem."});let p={high:0,warn:1,info:2};c.sort((_,v)=>p[_.severity]-p[v.severity]||v.estSavings-_.estSavings);let m=c.find(_=>_.id==="long_history")?.estSavings??0,f=c.filter(_=>_.id!=="long_history").reduce((_,v)=>_+v.estSavings,0),h=Math.min(a,Math.max(m,f)),y=la(t.model);return{totalTokens:a,baselineTokens:o,blockTokens:i,turns:e,model:t.model,contextWindow:l,usagePct:d,findings:c,totalEstSavings:h,perTurnUsd:y?as(a,y):void 0,perTurnCachedUsd:y?a/1e6*y.cacheReadPerM:void 0}}function iI(t){let e=[],r=t.usagePct!==void 0?` (~${t.usagePct}% of ${H(t.contextWindow)})`:"";return e.push(`Context estimate from sketch: ~${H(t.totalTokens)} tokens${r}, ${t.turns} turns.`),e.push(` ${H(t.baselineTokens)} plain conversation + ${H(t.blockTokens)} in pastes, tool output and images. Estimate, usually within \xB120%.`),t.perTurnUsd!==void 0?e.push(` Re-read on every turn: ${an(t.perTurnUsd)} at list price, ${an(t.perTurnCachedUsd)} when cached. On a subscription this is what spends the usage limit.`):e.push(" Re-read on every turn. On a subscription this is what spends the usage limit."),t.findings.length===0?(e.push("No findings: nothing large, repeated, or stale in the sketch. Keep going."),e.join(`
64
+ `)}p1(e,JSON.stringify({ts:Date.now(),...t})+`
65
+ `)}catch{}}var E1=2,T1=.5,z1=2;function P1(){return S1(k1(Ef()),".context-doctor-calibration.json")}function R1(t){let e=(t??"").toLowerCase();return e.includes("claude")?"claude":/gpt|^o\d/.test(e)?"gpt":e.includes("gemini")?"gemini":e?e.split(/[-_/]/)[0]:"unknown"}function I1(){try{return JSON.parse($1(P1(),"utf8"))}catch{return{}}}function gv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=I1()[R1(t)];if(!e||e.v!==E1||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<T1||r>z1?{factor:1,samples:0}:{factor:r,samples:e.samples}}function C1(t){switch(t.kind){case"system":return"system";case"user":return"user";case"assistant":return"assistant";case"tool_call":return"tool_calls";case"tool_result":return"tool_results";default:return"other"}}function A1(t,e){let r=new Map,n=0;for(let a of t){if(a.estSavings<=0)continue;if(a.messages.length===0){n+=a.estSavings;continue}let c=a.id==="near_duplicate"&&a.messages.length>2?a.messages.slice(1):[a.messages[a.messages.length-1]],u=a.estSavings/c.length;for(let l of c)r.set(l,Math.max(r.get(l)??0,u))}let o=Math.round([...r.values()].reduce((a,c)=>a+c,0)),s=Math.max(0,e-o),i=o+Math.min(n,s);return Math.min(i,Math.round(e*.9))}function N1(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function yv(t){return O1("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function M1(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return e>>>0}function j1(t){let e=t.toLowerCase().replace(/\s+/g," ").trim().split(" "),r=e.length>1500,n=new Set;for(let o=0;o+8<=e.length;o++){let s=M1(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var _v=.6;function Z1(t,e){if(t.size===0||e.size===0)return 0;let r=0,[n,o]=t.size<=e.size?[t,e]:[e,t];for(let s of n)o.has(s)&&r++;return r/(t.size+e.size-r)}var vv=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function D1(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function q1(t,e){if(/read|open|cat|view|get_file/i.test(t??"")){let n=/"(?:file_path|filePath|path|file)"\s*:\s*"([^"]{3,})"/.exec(e);if(n)return[n[1]]}if(!/bash|shell|terminal|exec|run_command/i.test(t??""))return[];let r=new Set;vv.lastIndex=0;for(let n of e.matchAll(vv)){let o=n[2].replace(/\\+$/,"");D1(o)&&r.add(o)}return[...r]}function xv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=gv(r),o=t.messages.map(g=>({msg:g,tokens:Math.round(sn(g.text,r)*n.factor)+$f})),s=o.reduce((g,x)=>g+x.tokens,0),i={system:0,user:0,assistant:0,tool_calls:0,tool_results:0,other:0};for(let g of o)i[C1(g.msg)]+=g.tokens;let a=[];for(let g of o)g.msg.kind==="tool_result"&&g.tokens>2e3&&a.push({id:"large_tool_result",severity:g.tokens>8e3?"high":"warn",estSavings:Math.round(g.tokens*.8),message:`Tool result at message #${g.msg.index}${g.msg.toolName?` (${g.msg.toolName})`:""} is ~${g.tokens} tokens.`,suggestion:"Truncate or summarize large tool outputs before they enter history; keep only the fields the model actually used.",messages:[g.msg.index]});for(let g of o)g.msg.kind==="tool_call"&&g.tokens>2e3&&a.push({id:"large_tool_call",severity:g.tokens>8e3?"high":"warn",estSavings:Math.round(g.tokens*.8),message:`Tool call at message #${g.msg.index}${g.msg.toolName?` (${g.msg.toolName})`:""} carries ~${g.tokens} tokens of arguments.`,suggestion:'Usually a whole file being written inline. Once it has run, replace the arguments with a reference ("wrote <path>") \u2014 or write files in smaller pieces so no single call carries the entire content.',messages:[g.msg.index]});let c=new Map;for(let g of o){if(g.msg.text.length<300)continue;let x=yv(g.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:g.tokens-$f,message:`Message #${g.msg.index} duplicates the content of message #${$} (~${g.tokens} tokens).`,suggestion:"Replace repeated content with a short reference to the first occurrence.",messages:[$,g.msg.index]}):c.set(x,g.msg.index)}{let g=o.filter(L=>L.msg.text.length>=300).sort((L,_e)=>_e.tokens-L.tokens).slice(0,150),x=g.map(L=>j1(L.msg.text)),$=x.map(L=>L.size),D=new Set(a.filter(L=>L.id==="duplicate_content").flatMap(L=>L.messages)),R=g.map((L,_e)=>_e),ae=L=>{for(;R[L]!==L;)L=R[L]=R[R[L]];return L},ce=g.map(()=>({sim:0,partnerTokens:0}));for(let L=0;L<g.length;L++)for(let _e=L+1;_e<g.length;_e++){let $t=g[L],xr=g[_e];if(D.has($t.msg.index)&&D.has(xr.msg.index))continue;let ps=Math.min($[L],$[_e]),cn=Math.max($[L],$[_e]);if(cn===0||ps/cn<_v)continue;let ft=Z1(x[L],x[_e]);ft<_v||(R[ae(L)]=ae(_e),ft>ce[L].sim&&(ce[L]={sim:ft,partnerTokens:xr.tokens}),ft>ce[_e].sim&&(ce[_e]={sim:ft,partnerTokens:$t.tokens}))}let Te=new Map;g.forEach((L,_e)=>{if(ce[_e].sim===0)return;let $t=ae(_e);Te.set($t,[...Te.get($t)??[],_e])});for(let L of Te.values()){if(L.length<2)continue;L.sort((pt,br)=>g[pt].msg.index-g[br].msg.index);let _e=L.slice(1),$t=_e.reduce((pt,br)=>pt+Math.round(Math.min(g[br].tokens,ce[br].partnerTokens)*ce[br].sim*.9),0),xr=L.map(pt=>ce[pt].sim),ps=Math.round(Math.min(...xr)*100),cn=Math.round(Math.max(...xr)*100),ft=L.map(pt=>g[pt].msg.index),Kf=ps===cn?`~${cn}%`:`${ps}-${cn}%`,A0=_e.reduce((pt,br)=>pt+g[br].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:$t,message:L.length===2?`Messages #${ft[0]} and #${ft[1]} are ${Kf} similar (~${Math.min(g[L[0]].tokens,g[L[1]].tokens)} tokens repeated with different framing).`:`${L.length} messages are ${Kf} similar to each other (${ft.slice(0,6).map(pt=>`#${pt}`).join(", ")}${ft.length>6?", \u2026":""}): ~${H(A0)} tokens in the ${_e.length} later copies repeat the first with different framing.`,suggestion:"Replace the later copies with a short reference to the first \u2014 repeats survive even when the surrounding words differ.",messages:ft})}}let u=new Map;for(let g of o){if(g.msg.kind!=="tool_call"||!g.msg.toolCallText)continue;let x=yv(g.msg.toolCallText),$=u.get(x)??[];$.push(g.msg.index),u.set(x,$)}let l=g=>o.find(x=>x.msg.index>g&&x.msg.kind==="tool_result")?.msg;for(let[,g]of u){if(g.length<2)continue;let x=g.slice(1).filter((D,R)=>l(g[R])?.isError===!0).length,$=g.length-1-x;x>0&&a.push({id:"retried_tool_call",severity:x>=3?"warn":"info",estSavings:0,message:`The same tool call was retried ${x} time(s) after it failed (messages #${g.join(", #")}).`,suggestion:x>=3?"Three or more identical retries of a failing command is a loop. Each attempt keeps its error output in context; the answer is in the first error, not in the fourth attempt.":"A retry after a failure is normal once. The failed attempt's output stays in context though, so once the fix is understood the earlier error can go.",messages:g}),$>0&&a.push({id:"repeated_tool_call",severity:"info",estSavings:0,message:`The same tool call (with identical arguments) was repeated ${$} time(s) after it had already succeeded (messages #${g.join(", #")}).`,suggestion:"Repeating a call that already succeeded means the earlier result scrolled out of the model's attention \u2014 keep results in a compact recap instead of re-calling.",messages:g})}{let g=new Map;for(let x of o)if(!(x.msg.kind!=="tool_call"||!x.msg.toolCallText))for(let $ of q1(x.msg.toolName,x.msg.toolCallText))g.set($,[...g.get($)??[],x.msg.index]);for(let[x,$]of g){if($.length<3)continue;let D=o.filter(ae=>ae.msg.kind==="tool_result"&&$.some(ce=>ae.msg.index===ce+1)).reduce((ae,ce)=>ae+ce.tokens,0),R=Math.round(D*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:R>4e3?"high":"warn",estSavings:R,message:`${x.split("/").pop()} was read ${$.length} times (messages #${$.join(", #")}), keeping ${$.length} copies in context.`,suggestion:"Re-read a file only after it changes; otherwise refer back to the copy already in context.",messages:$})}}for(let g of o)g.msg.kind!=="tool_result"||g.tokens<500||!/Traceback \(most recent call last\)|command not found|npm error|ERR!|\bexit code [1-9]|Exception in thread|FAILED|error TS\d+/i.test(g.msg.text)||a.push({id:"retained_error_output",severity:"warn",estSavings:Math.round(g.tokens*.85),message:`Message #${g.msg.index} holds ~${g.tokens} tokens of failed tool output (errors, stack trace or non-zero exit).`,suggestion:"Keep the one line that identifies the failure and drop the rest \u2014 a full trace has no value once the fix is understood.",messages:[g.msg.index]});for(let g of o)Jn(g.msg.text)&&a.push({id:"base64_blob",severity:"high",estSavings:Math.round(g.tokens*.9),message:`Message #${g.msg.index} contains a base64/binary blob (~${g.tokens} tokens of mostly meaningless characters).`,suggestion:"Never put base64 in text content \u2014 use the provider's file/image APIs or replace with a file reference.",messages:[g.msg.index]});let d=t.messages.filter(g=>g.kind==="user"||g.kind==="assistant").length;if(d>40){let x=o.slice(0,Math.floor(o.length/2)).reduce(($,D)=>$+D.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${x} tokens.`,suggestion:"Summarize the older half of the conversation into a compact recap and drop the raw turns (context-doctor optimize --strategy prune-history).",messages:[]})}s>0&&i.system/s>.25&&i.system>2e3&&a.push({id:"large_system_prompt",severity:"info",estSavings:0,message:`System prompt is ~${i.system} tokens (${Math.round(i.system/s*100)}% of the context).`,suggestion:"A big system prompt is fine IF it is stable \u2014 put it first and use prompt caching (Anthropic: cache_control; OpenAI: automatic prefix caching) so you stop paying full price for it every call.",messages:[]}),(on(e)==="anthropic"||on(e)==="openai")&&a.push({id:"cache_ordering",severity:"info",estSavings:0,message:"Prompt caching only matches a byte-identical prefix.",suggestion:"Keep stable content (system prompt, tool definitions, reference docs) at the start and never interleave it with per-request content \u2014 a single changed byte early in the prompt invalidates the cache for everything after it.",messages:[]});let p=aa(e),m=p?s/p*100:void 0;m!==void 0&&m>70&&a.push({id:"near_window_limit",severity:m>90?"high":"warn",estSavings:0,message:`Context is at ~${m.toFixed(0)}% of ${e}'s window.`,suggestion:"Models degrade well before the hard limit (lost-in-the-middle). Compact now rather than when the request fails.",messages:[]});let f=o.map(g=>({index:g.msg.index,role:g.msg.role,kind:g.msg.kind,tokens:g.tokens,preview:N1(g.msg.text),toolName:g.msg.toolName})).sort((g,x)=>x.tokens-g.tokens).slice(0,5),h={high:0,warn:1,info:2};a.sort((g,x)=>h[g.severity]-h[x.severity]||x.estSavings-g.estSavings);let y=A1(a,s),_=da(e),v;if(_){let g=as(s,_),x=as(y,_);v={perCallUsd:g,per1kCallsUsd:g*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:kf(s),ttftSavedSeconds:kf(y)}}return{totalTokens:s,model:e,contextWindow:p,usagePct:m,messageCount:t.messages.length,categories:i,largestMessages:f,findings:a,totalEstSavings:y,cost:v,sourceFormat:t.sourceFormat,calibration:n.samples>0?n:void 0,parseWarning:t.parseWarning}}import{createHash as L1}from"node:crypto";var $v=10,pa={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:$v};function U1(t){if(t?.name==="Write"&&typeof t.input?.file_path=="string")return t.input.file_path;let e=t?.name==="Bash"?String(t.input?.command??""):"",r=/(?:cat|tee)\s*>+\s*([^\s<]+)\s*<</.exec(e);return r?r[1]:null}function F1(t,e,r){if(!r)return!1;for(let n=e+1;n<t.length;n++){let o=t[n]?.content;if(Array.isArray(o))for(let s of o){if(s?.type!=="tool_use")continue;let i=s.input?.file_path,a=s.name==="Bash"?String(s.input?.command??""):"";if(i===r||a.includes(r)){if(s.name==="Read"||/\b(cat|head|tail|sed|less)\b/.test(a))return!1;if(s.name==="Edit"||s.name==="MultiEdit")return!0}}}return!1}function bv(t,e,r){let n=Math.round(e*ua("",r)),o={};for(let[s,i]of Object.entries(t))typeof i=="string"&&i.length>n?o[s]=i.slice(0,n)+`
66
+ [context-doctor: ${i.length-n} more chars trimmed \u2014 this call already ran]`:o[s]=i;return o}function Tf(t,e,r=$v){let n=t-e;return n<=0?0:n<r?n:Math.floor(n/r)*r}function H1(t){return L1("sha1").update(t.trim()).digest("hex")}function Wn(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"?e.text??"":e?.type==="tool_result"?Wn(e.content):e?.type==="tool_use"?JSON.stringify(e.input??{}):"").join(`
67
+ `):JSON.stringify(t)}function zf(t,e){let r=t?.content,n=t?.role==="tool"?"tool_result":"text",o=(s,i)=>{let a=s.filter(d=>d?.type==="text"&&typeof d.text=="string");if(a.length===0)return s;let c=a.map(d=>d.text).join(`
68
+ `),u=e(c,i);if(u===c)return s;let l=!1;return s.map(d=>d?.type==="text"&&typeof d.text=="string"?l?null:(l=!0,{...d,text:u}):d).filter(d=>d!==null)};return typeof r=="string"?e(r,n):Array.isArray(r)?n==="tool_result"?o(r,n):r.map(s=>{if(s?.type==="text"&&typeof s.text=="string"){let i=e(s.text,"text");return i===s.text?s:{...s,text:i}}if(s?.type==="tool_result"){if(typeof s.content=="string"){let i=e(s.content,"tool_result");return i===s.content?s:{...s,content:i}}if(Array.isArray(s.content)){let i=o(s.content,"tool_result");return i===s.content?s:{...s,content:i}}}return s}):r}function Pf(t){return typeof t=="string"?Jn(t)?Sf(t):t:Array.isArray(t)?t.map(Pf):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,Pf(r)])):t}function V1(t,e,r){let n=Math.round(e*ua(t,r));if(t.length<=n)return t;let o=t.slice(0,n),s=t.length-n;return`${o}
69
+ \u2026[context-doctor: trimmed ${s} chars of stale tool output]`}function B1(t){let e=new Set;for(let r of t)if(Array.isArray(r?.content))for(let n of r.content)n?.type==="tool_use"&&n.id&&e.add(n.id);for(let r of t){if(!Array.isArray(r?.content))continue;let n=r.content.filter(o=>o?.type!=="tool_result"||o.tool_use_id&&e.has(o.tool_use_id));n.length!==r.content.length&&(r.content=n.length>0?n:[{type:"text",text:"[context-doctor: earlier tool result dropped with the pruned history]"}])}}function wv(t){return t?.role==="tool"?!0:Array.isArray(t?.content)?t.content.some(e=>e?.type==="tool_result"):!1}function kv(t,e={}){let r={strategies:e.strategies??pa.strategies,keepRecent:e.keepRecent??pa.keepRecent,maxToolResultTokens:e.maxToolResultTokens??pa.maxToolResultTokens,trimBoundaryStep:e.trimBoundaryStep&&e.trimBoundaryStep>0?Math.floor(e.trimBoundaryStep):pa.trimBoundaryStep},n;try{n=JSON.parse(t)}catch{throw new Error("optimize requires a JSON conversation (message array, or object with a `messages` field)")}let o=Array.isArray(n)?n:n?.messages;if(!Array.isArray(o))throw Array.isArray(n?.contents)||typeof n?.input=="string"||Array.isArray(n?.input)?new Error(`optimize rewrites a \`messages\` array (Anthropic or OpenAI chat); this is ${Array.isArray(n?.contents)?"a Gemini `contents`":"an OpenAI Responses `input`"} request. Profile it with analyze (or profile_context); the autopilot proxy slims these requests live.`):new Error("No `messages` array found in input");for(let y=o.length-1;y>=0;y--)(!o[y]||typeof o[y]!="object")&&o.splice(y,1);let s=!Array.isArray(n)&&n?.system!=null||o.some(y=>Array.isArray(y?.content)&&y.content.some(_=>_?.type==="tool_use"||_?.type==="tool_result")),i=e.model??(!Array.isArray(n)&&typeof n?.model=="string"?n.model:void 0)??(s?"claude":void 0),a=y=>sn(y,i),c=Array.isArray(n)?0:(n?.system!=null?a(typeof n.system=="string"?n.system:Wn(n.system)):0)+(n?.tools!=null?a(JSON.stringify(n.tools)):0),u=y=>{let _=a(Wn(y.content));for(let v of Array.isArray(y.tool_calls)?y.tool_calls:[]){let g=v?.function;g&&(_+=a(`${g.name??""} ${typeof g.arguments=="string"?g.arguments:JSON.stringify(g.arguments??{})}`))}return y.function_call&&(_+=a(`${y.function_call.name??""} ${y.function_call.arguments??""}`)),_},l=c+o.reduce((y,_)=>y+u(_),0),d=[];if(r.strategies.includes("strip-base64")&&o.forEach((y,_)=>{let v=Wn(y.content);if(!Jn(v))return;let g=a(v),x=zf(y,D=>Jn(D)?Sf(D):D);Array.isArray(x)&&(x=x.map(D=>D?.type==="tool_use"&&D.input!=null?{...D,input:Pf(D.input)}:D));let $=g-a(Wn(x));$>50&&(y.content=x,d.push({strategy:"strip-base64",messageIndex:_,tokensSaved:$,note:"Removed inline base64 data"}))}),r.strategies.includes("dedupe")){let y=Tf(o.length,r.keepRecent,r.trimBoundaryStep),_=new Map;o.forEach((v,g)=>{let x=0,$,D=zf(v,R=>{if(R.length<300)return R;let ae=H1(R),ce=_.get(ae);if(ce===void 0)return _.set(ae,g),R;if(g>=y)return R;let Te=`[context-doctor: identical to message #${ce} \u2014 content removed]`;return x+=a(R)-a(Te),$??=ce,Te});x<=0||(v.content=D,d.push({strategy:"dedupe",messageIndex:g,tokensSaved:x,note:`Duplicate of message #${$}`}))})}if(r.strategies.includes("trim-tool-results")){let y=Tf(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=y||!wv(_))return;let g=0,x=zf(_,($,D)=>{if(D!=="tool_result")return $;let R=a($);if(R<=r.maxToolResultTokens)return $;let ae=V1($,r.maxToolResultTokens,i),ce=a(ae);return ce>=R?$:(g+=R-ce,ae)});g<=0||(_.content=x,d.push({strategy:"trim-tool-results",messageIndex:v,tokensSaved:g,note:"Stale tool result truncated"}))})}if(r.strategies.includes("trim-tool-calls")){let y=Tf(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=y)return;let g=0;if(Array.isArray(_.content))for(let x of _.content){if(x?.type!=="tool_use"||x.input==null||typeof x.input!="object"||F1(o,v,U1(x)))continue;let $=a(JSON.stringify(x.input));if($<=r.maxToolResultTokens)continue;let D=bv(x.input,r.maxToolResultTokens,i),R=a(JSON.stringify(D));R>=$||(x.input=D,g+=$-R)}for(let x of _.tool_calls??[]){let $=x?.function?.arguments;if(typeof $!="string")continue;let D=a($);if(D<=r.maxToolResultTokens)continue;let R;try{R=JSON.parse($)}catch{continue}if(!R||typeof R!="object"||Array.isArray(R))continue;let ae=JSON.stringify(bv(R,r.maxToolResultTokens,i)),ce=a(ae);ce>=D||(x.function.arguments=ae,g+=D-ce)}g>0&&d.push({strategy:"trim-tool-calls",messageIndex:v,tokensSaved:g,note:"Arguments of a completed tool call truncated"})})}let p,m=0;for(;m<o.length&&(o[m]?.role==="system"||o[m]?.role==="developer");)m++;let f=Math.max(2,r.keepRecent);if(r.strategies.includes("prune-history")&&o.length-m>f*2){let y=o.length-f;for(;y<o.length&&wv(o[y]);)y++;if(o.length-y>=2){B1(o.slice(y));let _=o.slice(m,y),v=_.reduce((x,$)=>x+u($),0);p=_.map((x,$)=>`[${m+$}:${x.role}] ${Wn(x.content).replace(/\s+/g," ").slice(0,200)}`).join(`
70
+ `);let g={role:"user",content:`[context-doctor: ${_.length} earlier messages (~${v} tokens) pruned. Replace this stub with an LLM-written summary of those turns for best results.]`};o.splice(m,y-m,g),d.push({strategy:"prune-history",messageIndex:m,tokensSaved:v-a(g.content),note:`Pruned ${_.length} old messages`})}}let h=c+o.reduce((y,_)=>y+u(_),0);return{conversation:n,tokensBefore:l,tokensAfter:h,applied:d,prunedDigest:p}}var Sv={system:"System prompt",user:"User messages",assistant:"Assistant replies",tool_calls:"Tool calls",tool_results:"Tool results",other:"Other"},J1={high:"\u2716",warn:"\u25B2",info:"\u2139"};function W1(t,e=28){let r=Math.round(t*e);return"\u2588".repeat(r)+"\u2591".repeat(e-r)}function K1(t){return t.replace(/(?:[A-Za-z]:)?(?:~|\.{1,2})?(?:[\\/][\w.@+-]+)+|[\w.@~+-]+(?:[\\/][\w.@+-]+)+/g,"[path]").replace(/(?<![\w.@+-])[\w@+-][\w.@+-]*\.[A-Za-z][A-Za-z0-9]{0,9}(?![\w@+-]|\.\w)/g,"[file]")}function Ev(t,e={}){let r=[],n=t;if(r.push("CONTEXT DOCTOR \u2014 profile"),r.push("\u2550".repeat(56)),n.parseWarning&&(r.push(`\u26A0 ${n.parseWarning}${n.sourceFormat==="text"&&n.messageCount>0?" Profiled as raw text below, which is almost certainly not what you want.":""}`),r.push("")),r.push(`Total: ~${H(n.totalTokens)} tokens across ${n.messageCount} messages (${n.sourceFormat} format)`),n.calibration){let i=Math.round((n.calibration.factor-1)*100);r.push(` estimates calibrated ${i>=0?"+":""}${i}% from ${n.calibration.samples} exact count(s) you ran on this machine (analyze --exact)`)}if(n.model){let i=n.contextWindow?` of ${H(n.contextWindow)} window (${n.usagePct.toFixed(1)}%)`:" (unknown window size)";r.push(`Model: ${n.model}${i}`)}n.cost&&r.push(`Cost: ~${an(n.cost.perCallUsd)} input per call \xB7 ~${an(n.cost.per1kCallsUsd)} per 1k calls \xB7 ~${n.cost.ttftSeconds.toFixed(1)}s of latency per call (estimates)`),r.push(""),r.push("Where the tokens go"),r.push("\u2500".repeat(56));let o=Object.entries(n.categories).filter(([,i])=>i>0).sort((i,a)=>a[1]-i[1]),s=Math.max(...o.map(([i])=>Sv[i].length));for(let[i,a]of o){let c=n.totalTokens>0?a/n.totalTokens:0;r.push(`${Sv[i].padEnd(s)} ${W1(c)} ${String(Math.round(c*100)).padStart(3)}% ~${H(a)}`)}r.push(""),r.push("Largest messages"),r.push("\u2500".repeat(56));for(let i of n.largestMessages){let a=i.toolName?`${i.kind}:${i.toolName}`:i.kind,c=e.redact?"[redacted]":i.preview;r.push(` #${i.index} [${a}] ~${H(i.tokens)} ${c}`)}if(r.push(""),n.findings.length>0){r.push(`Findings (${n.findings.length})`),r.push("\u2500".repeat(56));let i=3,a=new Map,c=new Map;for(let u of n.findings){let l=a.get(u.id)??0;if(l>=i){let m=c.get(u.id)??{count:0,savings:0};c.set(u.id,{count:m.count+1,savings:m.savings+u.estSavings});continue}a.set(u.id,l+1);let d=u.estSavings>0?` [save ~${H(u.estSavings)}]`:"";r.push(`${J1[u.severity]} ${e.redact?K1(u.message):u.message}${d}`),r.push(` \u2192 ${u.suggestion}`);let p=c.get(u.id);l+1===i&&p===void 0&&c.set(u.id,{count:0,savings:0})}for(let[u,l]of c){if(l.count===0)continue;let d=Math.min(l.savings,n.totalEstSavings),p=d>0?`, up to ~${H(d)} more recoverable`:"";r.push(` \u2026 and ${l.count} more of the same kind (${u})${p}. Use --json for the full list.`)}if(r.push(""),n.totalEstSavings>0){let u=n.totalTokens>0?Math.round(n.totalEstSavings/n.totalTokens*100):0,l=`Potential recovery: ~${H(n.totalEstSavings)} tokens (~${u}% of context)`;n.cost&&n.cost.savingsPerCallUsd>0&&(l+=` \u2248 ${an(n.cost.savingsPer1kCallsUsd)} per 1k calls, ${n.cost.ttftSavedSeconds.toFixed(1)}s faster per call`),r.push(l),r.push("Run `context-doctor optimize <file>` to apply the safe fixes automatically.")}}else r.push("No issues found \u2014 this context is in good shape.");return r.join(`
71
+ `)}var G1=2060,X1={code:42,tool_result:56,paste:56,text:80,base64:76,image:0},Y1=6.3,Q1={paste:2400,code:2400,tool_result:2400,text:900,base64:12e3,image:0},eI=1500,Tv=2e3,tI=30,zv=300,rI=6;function nI(t,e){let r=ca[on(e)];return t==="code"||t==="tool_result"||t==="base64"?r.code:r.prose}function oI(t,e){if(t.kind==="image")return t.approx_tokens&&t.approx_tokens>0?Math.round(t.approx_tokens):eI;if(t.approx_tokens&&t.approx_tokens>0)return Math.round(t.approx_tokens);let r=t.approx_chars&&t.approx_chars>0?t.approx_chars:t.approx_lines&&t.approx_lines>0?t.approx_lines*X1[t.kind]:t.approx_words&&t.approx_words>0?t.approx_words*Y1:Q1[t.kind];return Math.round(r/nI(t.kind,e))}function sI(t){return Math.round(G1/ca[on(t)].prose)}var Pv=60;function iI(t){let e=String(t??"").replace(/\s+/g," ").trim()||"unnamed block";return e.length>Pv?e.slice(0,Pv-1)+"\u2026":e}function aI(t){let e=Math.max(0,Math.floor(t.turns||0)),r=(Array.isArray(t.blocks)?t.blocks:[]).map(_=>({..._,label:iI(_?.label)})),n=sI(t.model),o=e*n,s=r.map(_=>({block:_,tokens:oI(_,t.model),copies:Math.max(1,Math.floor(_.repeated??1))})),i=s.reduce((_,v)=>_+v.tokens*v.copies,0),a=o+i,c=[];for(let{block:_,tokens:v,copies:g}of s){if(g>1&&c.push({id:"duplicate_block",severity:"warn",estSavings:v*(g-1),message:`"${_.label}" appears ${g} times (~${H(v)} each).`,action:`Refer to "${_.label}" by name from now on; never re-quote it.`}),_.kind==="base64"){c.push({id:"base64_blob",severity:"high",estSavings:Math.max(0,v-50),message:`"${_.label}" is inline base64 (~${H(v)}), which the model cannot read anyway.`,action:`Drop it: describe "${_.label}" in one line and ask the user to attach it as a file if needed.`});continue}if(_.kind!=="image"&&v>=Tv){let x=_.stale?Math.max(0,v-100):Math.round(v*.7);c.push({id:"large_block",severity:v>=4*Tv?"high":"warn",estSavings:x,message:`"${_.label}" (turn ${_.turn}, ${_.kind}) is ~${H(v)}${_.stale?" and already acted on":""}.`,action:_.stale?`Replace "${_.label}" with a one-line note of what it was and what came of it.`:`Summarize "${_.label}" into the points still needed (facts, identifiers, decisions) and work from the summary.`})}}let u=s.filter(_=>_.block.kind==="image");if(u.length>=3){let _=u.reduce((v,g)=>v+g.tokens*g.copies,0);c.push({id:"many_images",severity:"info",estSavings:0,message:`${u.length} images (~${H(_)}) ride along on every turn.`,action:"Once an image has been read, describe what it showed in a sentence so it need not be looked at again; new chats should get only the images still needed."})}if(e>=tI){let _=rI*n+zv;c.push({id:"long_history",severity:a>1e5?"high":"warn",estSavings:Math.max(0,a-_),message:`${e} turns: every new message re-reads ~${H(a)}.`,action:`Offer a handoff: write a \u2264${zv}-token summary (decisions, current state, open items, key identifiers) for the user to start a new chat with. A fresh chat re-reads ~${H(_)} of conversation instead, plus the app's own system prompt, which every chat carries.`})}let l=aa(t.model),d=l?Math.round(a/l*100):void 0;d!==void 0&&d>=70&&c.push({id:"near_window_limit",severity:"high",estSavings:0,message:`~${d}% of the ${H(l)} window. Quality drops and the app may start dropping early turns.`,action:"Do the handoff now rather than at the next problem."});let p={high:0,warn:1,info:2};c.sort((_,v)=>p[_.severity]-p[v.severity]||v.estSavings-_.estSavings);let m=c.find(_=>_.id==="long_history")?.estSavings??0,f=c.filter(_=>_.id!=="long_history").reduce((_,v)=>_+v.estSavings,0),h=Math.min(a,Math.max(m,f)),y=da(t.model);return{totalTokens:a,baselineTokens:o,blockTokens:i,turns:e,model:t.model,contextWindow:l,usagePct:d,findings:c,totalEstSavings:h,perTurnUsd:y?as(a,y):void 0,perTurnCachedUsd:y?a/1e6*y.cacheReadPerM:void 0}}function cI(t){let e=[],r=t.usagePct!==void 0?` (~${t.usagePct}% of ${H(t.contextWindow)})`:"";return e.push(`Context estimate from sketch: ~${H(t.totalTokens)} tokens${r}, ${t.turns} turns.`),e.push(` ${H(t.baselineTokens)} plain conversation + ${H(t.blockTokens)} in pastes, tool output and images. Estimate, usually within \xB120%.`),t.perTurnUsd!==void 0?e.push(` Re-read on every turn: ${an(t.perTurnUsd)} at list price, ${an(t.perTurnCachedUsd)} when cached. On a subscription this is what spends the usage limit.`):e.push(" Re-read on every turn. On a subscription this is what spends the usage limit."),t.findings.length===0?(e.push("No findings: nothing large, repeated, or stale in the sketch. Keep going."),e.join(`
72
72
  `)):(e.push(""),e.push(`Findings (recoverable ~${H(t.totalEstSavings)} tokens):`),t.findings.forEach((n,o)=>{let s=n.estSavings>0?` [~${H(n.estSavings)}]`:"";e.push(`${o+1}. ${n.severity.toUpperCase()}${s} ${n.message}`),e.push(` \u2192 ${n.action}`)}),e.push(""),e.push("Act on #1 in your reply (do it, do not just suggest it), and tell the user in one line what you dropped and roughly what it saves per turn."),e.join(`
73
- `))}function Pv(t){let e=sI(t);return da({ev:"check",src:"mcp",tok:e.totalTokens,warn:e.findings.some(r=>r.severity!=="info"),model:t.model}),iI(e)}import{spawnSync as Uv}from"node:child_process";import{existsSync as Fv,lstatSync as PI,readdirSync as RI,readFileSync as II,realpathSync as Cf,statSync as OI}from"node:fs";import{homedir as CI}from"node:os";import{basename as Af,extname as ga,isAbsolute as AI,join as Kn,relative as Hv,resolve as NI,sep as MI}from"node:path";import{spawnSync as Iv}from"node:child_process";import{existsSync as aI,mkdtempSync as cI,readFileSync as uI,rmSync as lI}from"node:fs";import{tmpdir as dI}from"node:os";import{dirname as fI,extname as pI,join as Rv}from"node:path";var Ov=new Set([".pdf",".docx",".doc",".rtf",".odt",".pptx"]),Cv={encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024};function cs(t,e){try{let r=Iv(t,e,Cv);return r.status===0&&typeof r.stdout=="string"&&r.stdout.trim()?r.stdout:void 0}catch{return}}var mI='ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';function hI(t){let e=cs("pdftotext",["-enc","UTF-8",t,"-"])??cs("pdftotext",[t,"-"]);if(e)return e;let r=Rv(cI(Rv(dI(),"cd-pdf-")),"out.txt");try{Iv("pdftotext",[t,r],Cv);let n=aI(r)?uI(r,"utf8"):"";return n.trim()?n:void 0}catch{return}finally{lI(fI(r),{recursive:!0,force:!0})}}function gI(t,e){let r=cs("unzip",["-p",t,...e]);if(r)return r.replace(/<\/(w:p|a:p|text:p|text:h)>/g,`
73
+ `))}function Rv(t){let e=aI(t);return fa({ev:"check",src:"mcp",tok:e.totalTokens,warn:e.findings.some(r=>r.severity!=="info"),model:t.model}),cI(e)}import{spawnSync as Fv}from"node:child_process";import{existsSync as Hv,lstatSync as II,readdirSync as OI,readFileSync as CI,realpathSync as Af,statSync as AI}from"node:fs";import{homedir as NI}from"node:os";import{basename as Nf,extname as ya,isAbsolute as MI,join as Kn,relative as Vv,resolve as jI,sep as ZI}from"node:path";import{spawnSync as Ov}from"node:child_process";import{existsSync as uI,mkdtempSync as lI,readFileSync as dI,rmSync as fI}from"node:fs";import{tmpdir as pI}from"node:os";import{dirname as mI,extname as hI,join as Iv}from"node:path";var Cv=new Set([".pdf",".docx",".doc",".rtf",".odt",".pptx"]),Av={encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024};function cs(t,e){try{let r=Ov(t,e,Av);return r.status===0&&typeof r.stdout=="string"&&r.stdout.trim()?r.stdout:void 0}catch{return}}var gI='ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';function yI(t){let e=cs("pdftotext",["-enc","UTF-8",t,"-"])??cs("pdftotext",[t,"-"]);if(e)return e;let r=Iv(lI(Iv(pI(),"cd-pdf-")),"out.txt");try{Ov("pdftotext",[t,r],Av);let n=uI(r)?dI(r,"utf8"):"";return n.trim()?n:void 0}catch{return}finally{fI(mI(r),{recursive:!0,force:!0})}}function _I(t,e){let r=cs("unzip",["-p",t,...e]);if(r)return r.replace(/<\/(w:p|a:p|text:p|text:h)>/g,`
74
74
 
75
75
  `).replace(/<(w:tab|w:br)\/>/g," ").replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&amp;/g,"&").replace(/\n{3,}/g,`
76
76
 
77
- `).trim()}function Av(t){let e=pI(t).toLowerCase(),r=process.platform==="darwin",n;if(e===".pdf"){if(n=hI(t)?.replace(/\f/g,`
77
+ `).trim()}function Nv(t){let e=hI(t).toLowerCase(),r=process.platform==="darwin",n;if(e===".pdf"){if(n=yI(t)?.replace(/\f/g,`
78
78
 
79
- `),!n&&r&&(n=cs("osascript",["-l","JavaScript","-e",mI,t])),!n)return{error:r?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}else{if(r&&e!==".pptx"&&(n=cs("textutil",["-convert","txt","-stdout",t])),!n){let o=e===".docx"?["word/document.xml"]:e===".pptx"?["ppt/slides/*.xml"]:e===".odt"?["content.xml"]:[];o.length&&(n=gI(t,o))}if(!n)return{error:r?"unreadable document":`needs unzip${e===".doc"||e===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}return{text:n}}var jI=4e3,ZI=400,DI="claude",qI=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".swift",".c",".h",".cc",".cpp",".hpp",".cs",".php",".scala",".sh",".bash",".zsh",".sql",".lua",".dart",".vue",".svelte"]),LI=new Set([".md",".mdx",".markdown",".rst",".adoc"]);function UI(t,e){let r=ga(t).toLowerCase();return LI.has(r)?"markdown":qI.has(r)?"code":/^#{1,6}\s+\S/m.test(e)&&!/^#!/.test(e)?"markdown":"prose"}var FI=/^(?![\s})\]]|$)/,Lv=/^(\/\*\*?|\*\/?|\/\/|#(?!include|define|!)|"""|\'\'\'|--|@\w+)/;function HI(t,e){let r=[],n=[],o="",s=0,i=!1,a=!1,c=(u,l)=>{u>s&&t.slice(s,u).some(d=>d.trim())&&r.push({start:s,end:u,heading:o,hard:i}),s=u,i=l};for(let u=0;u<t.length;u++){let l=t[u];if(e==="markdown"){/^\s*(```|~~~)/.test(l)&&(a=!a);let d=!a&&/^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(l);if(d){c(u,!0);let p=d[1].length;n.length=p-1,n[p-1]=d[2],o=n.filter(Boolean).join(" > ");continue}!a&&!l.trim()&&u+1<t.length&&t[u+1].trim()&&c(u+1,!1)}else e==="code"?u>0&&!t[u-1].trim()&&l.trim()&&FI.test(l)&&c(u,!1):!l.trim()&&u+1<t.length&&t[u+1].trim()&&c(u+1,!1)}if(c(t.length,!1),e!=="markdown")for(let u of r){let l=t.slice(u.start,u.end).map(m=>m.trim()).filter(Boolean),d=l.map(m=>m.replace(Lv,"").trim()).find(Boolean),p=e==="code"&&(l.find(m=>!Lv.test(m))||d)||l[0]||"";u.heading=p.slice(0,80)}return r}var VI=t=>t>=55296&&t<=56319,BI=t=>t>=56320&&t<=57343;function JI(t,e={}){let r=Math.max(50,e.maxChunkTokens??ZI),n=e.model??DI,o=UI(t.name,t.text),s=[],i=[],a=Math.floor(r*2.4);t.text.replace(/\r\n?/g,`
79
+ `),!n&&r&&(n=cs("osascript",["-l","JavaScript","-e",gI,t])),!n)return{error:r?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}else{if(r&&e!==".pptx"&&(n=cs("textutil",["-convert","txt","-stdout",t])),!n){let o=e===".docx"?["word/document.xml"]:e===".pptx"?["ppt/slides/*.xml"]:e===".odt"?["content.xml"]:[];o.length&&(n=_I(t,o))}if(!n)return{error:r?"unreadable document":`needs unzip${e===".doc"||e===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}return{text:n}}var DI=4e3,qI=400,LI="claude",UI=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".swift",".c",".h",".cc",".cpp",".hpp",".cs",".php",".scala",".sh",".bash",".zsh",".sql",".lua",".dart",".vue",".svelte"]),FI=new Set([".md",".mdx",".markdown",".rst",".adoc"]);function HI(t,e){let r=ya(t).toLowerCase();return FI.has(r)?"markdown":UI.has(r)?"code":/^#{1,6}\s+\S/m.test(e)&&!/^#!/.test(e)?"markdown":"prose"}var VI=/^(?![\s})\]]|$)/,Uv=/^(\/\*\*?|\*\/?|\/\/|#(?!include|define|!)|"""|\'\'\'|--|@\w+)/;function BI(t,e){let r=[],n=[],o="",s=0,i=!1,a=!1,c=(u,l)=>{u>s&&t.slice(s,u).some(d=>d.trim())&&r.push({start:s,end:u,heading:o,hard:i}),s=u,i=l};for(let u=0;u<t.length;u++){let l=t[u];if(e==="markdown"){/^\s*(```|~~~)/.test(l)&&(a=!a);let d=!a&&/^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(l);if(d){c(u,!0);let p=d[1].length;n.length=p-1,n[p-1]=d[2],o=n.filter(Boolean).join(" > ");continue}!a&&!l.trim()&&u+1<t.length&&t[u+1].trim()&&c(u+1,!1)}else e==="code"?u>0&&!t[u-1].trim()&&l.trim()&&VI.test(l)&&c(u,!1):!l.trim()&&u+1<t.length&&t[u+1].trim()&&c(u+1,!1)}if(c(t.length,!1),e!=="markdown")for(let u of r){let l=t.slice(u.start,u.end).map(m=>m.trim()).filter(Boolean),d=l.map(m=>m.replace(Uv,"").trim()).find(Boolean),p=e==="code"&&(l.find(m=>!Uv.test(m))||d)||l[0]||"";u.heading=p.slice(0,80)}return r}var JI=t=>t>=55296&&t<=56319,WI=t=>t>=56320&&t<=57343;function KI(t,e={}){let r=Math.max(50,e.maxChunkTokens??qI),n=e.model??LI,o=HI(t.name,t.text),s=[],i=[],a=Math.floor(r*2.4);t.text.replace(/\r\n?/g,`
80
80
  `).split(`
81
- `).forEach((p,m)=>{for(;p.length>a;){let f=p.lastIndexOf(" ",a),h=f>a/2?f+1:a;VI(p.charCodeAt(h-1))&&BI(p.charCodeAt(h))&&h--,s.push(p.slice(0,h)),i.push(m+1),p=p.slice(h)}s.push(p),i.push(m+1)});let c=[0];for(let p of s)c.push(c[c.length-1]+sn(p+`
82
- `,n));let u=(p,m)=>c[m]-c[p],l=[];for(let p of HI(s,o)){if(u(p.start,p.end)<=r){l.push(p);continue}let m=p.start;for(let f=p.start+1;f<=p.end;f++)if(f===p.end||u(m,f+1)>r){let h=m===p.start;l.push({start:m,end:f,heading:h?p.heading:`${p.heading} (cont.)`,hard:h&&p.hard}),m=f}}let d=[];for(let p of l){let m=d[d.length-1];m&&!p.hard&&m.heading===p.heading&&u(m.start,p.end)<=r||m&&!p.hard&&o!=="markdown"&&u(m.start,p.end)<=r?m.end=p.end:d.push({...p})}return d.map((p,m)=>{let f=p.start,h=p.end;for(;f<h&&!s[f].trim();)f++;for(;h>f&&!s[h-1].trim();)h--;let y=s.slice(f,h).join(`
83
- `);return{id:`${t.name}#${m+1}`,source:t.name,startLine:i[f]??f+1,endLine:i[h-1]??h,heading:p.heading,text:y,tokens:sn(y,n),score:0}})}var WI=new Set("a an and are as at be but by can do does for from has have how i if in into is it its of on or our so that the their them then there these they this to was we were what when where which who why will with you your about should would could not no yes all any my me get set use using used".split(" "));function ma(t){let e=[],r=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u);for(let n of r)n.length<2||WI.has(n)||(n.length>4&&n.endsWith("ies")?n=n.slice(0,-3)+"y":n.length>3&&n.endsWith("s")&&!n.endsWith("ss")&&(n=n.slice(0,-1)),e.push(n));return e}function KI(t,e){let r=[...new Set(ma(e))];if(r.length===0||t.length===0)return;let n=t.map(i=>{let a=[...ma(i.text),...ma(i.heading),...ma(i.heading)],c=new Map;for(let u of a)c.set(u,(c.get(u)??0)+1);return{len:a.length,tf:c}}),o=n.reduce((i,a)=>i+a.len,0)/n.length||1,s=n.length;for(let i of r){let a=n.filter(u=>u.tf.has(i)).length;if(a===0)continue;let c=Math.log(1+(s-a+.5)/(a+.5));n.forEach((u,l)=>{let d=u.tf.get(i)??0;d&&(t[l].score+=c*(d*2.2/(d+1.2*(1-.75+.75*u.len/o))))})}}async function Vv(t,e={}){let r=t.map(s=>JI(s,e)),n=e.query?.trim()||void 0,o;if(n&&(KI(r.flat(),n),e.semantic)){let{semanticRerank:s}=await Promise.resolve().then(()=>(qv(),Dv));o=(await s(r.flat(),n,{model:typeof e.semantic=="string"?e.semantic:void 0})).note}return{...GI(t,r,n,e),semanticNote:o}}function GI(t,e,r,n){let o=Math.max(1,n.budget??jI),s=e.flat(),i=[],a=[],c=[],u=0,l=(m,f)=>{if(!i.includes(m)){if(u+m.tokens>o){c.some(h=>h.id===m.id)||c.push({id:m.id,tokens:m.tokens,requested:f});return}i.push(m),u+=m.tokens}},d="outline";if(n.ids?.length){d="ids";let m=new Map(s.map(f=>[f.id,f]));for(let f of n.ids){let h=m.get(f);h?l(h,!0):a.push(f)}}if(r){d==="outline"&&(d="query");for(let m of[...s].filter(f=>f.score>0).sort((f,h)=>h.score-f.score))l(m,!1)}let p=new Map(s.map((m,f)=>[m,f]));return i.sort((m,f)=>p.get(m)-p.get(f)),{mode:d,query:r,budget:o,totalTokens:s.reduce((m,f)=>m+f.tokens,0),packedTokens:u,selected:i,chunks:s,missingIds:a,unfit:c,sources:t.map((m,f)=>({name:m.name,tokens:e[f].reduce((h,y)=>h+y.tokens,0),chunks:e[f].length,selected:e[f].filter(h=>i.includes(h)).length}))}}function If(t,e){let r=t.slice(0,e).map(n=>` ${n.id} L${n.startLine}-${n.endLine} ~${H(n.tokens)} ${n.heading}`);return t.length>e&&r.push(` \u2026 ${t.length-e} more`),r}function Bv(t,{outlineLimit:e=60}={}){let r=[],n=t.totalTokens>0?Math.round(t.packedTokens/t.totalTokens*100):0,o=t.sources.length===1?t.sources[0].name:`${t.sources.length} files`;if(t.mode==="outline")return r.push(`OUTLINE of ${o}: ~${H(t.totalTokens)} tokens in ${t.chunks.length} chunks. Nothing packed: pass a query, or chunk ids from this list.`),r.push(...If(t.chunks,e)),r.join(`
84
- `);r.push(`PACKED ~${H(t.packedTokens)} of ~${H(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${H(t.budget)}.`),t.missingIds.length&&r.push(`Unknown ids: ${t.missingIds.join(", ")}.`),t.semanticNote&&r.push(`(${t.semanticNote})`);let s=(t.unfit??[]).filter(a=>a.requested);if(t.selected.length>0&&s.length>0&&r.push(`Did not fit the budget of ${H(t.budget)}: ${s.map(a=>`${a.id} (~${H(a.tokens)})`).join(", ")}. Ask for it alone or with a larger budget (--max-tokens; MCP max_tokens).`),t.selected.length===0&&(t.unfit??[]).length>0){let a=t.unfit[0],c=t.chunks.find(u=>u.id===a.id);return r.push(`Nothing fit the budget of ${H(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${H(a.tokens)} tokens. Raise the budget to at least ${a.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`),r.push(...If(t.chunks,e)),r.join(`
85
- `)}if(t.selected.length===0)return r.push("No chunk matched. Choose from the outline by id, or rephrase with words the document would use."),r.push(...If(t.chunks,e)),r.join(`
81
+ `).forEach((p,m)=>{for(;p.length>a;){let f=p.lastIndexOf(" ",a),h=f>a/2?f+1:a;JI(p.charCodeAt(h-1))&&WI(p.charCodeAt(h))&&h--,s.push(p.slice(0,h)),i.push(m+1),p=p.slice(h)}s.push(p),i.push(m+1)});let c=[0];for(let p of s)c.push(c[c.length-1]+sn(p+`
82
+ `,n));let u=(p,m)=>c[m]-c[p],l=[];for(let p of BI(s,o)){if(u(p.start,p.end)<=r){l.push(p);continue}let m=p.start;for(let f=p.start+1;f<=p.end;f++)if(f===p.end||u(m,f+1)>r){let h=m===p.start;l.push({start:m,end:f,heading:h?p.heading:`${p.heading} (cont.)`,hard:h&&p.hard}),m=f}}let d=[];for(let p of l){let m=d[d.length-1];m&&!p.hard&&m.heading===p.heading&&u(m.start,p.end)<=r||m&&!p.hard&&o!=="markdown"&&u(m.start,p.end)<=r?m.end=p.end:d.push({...p})}return d.map((p,m)=>{let f=p.start,h=p.end;for(;f<h&&!s[f].trim();)f++;for(;h>f&&!s[h-1].trim();)h--;let y=s.slice(f,h).join(`
83
+ `);return{id:`${t.name}#${m+1}`,source:t.name,startLine:i[f]??f+1,endLine:i[h-1]??h,heading:p.heading,text:y,tokens:sn(y,n),score:0}})}var GI=new Set("a an and are as at be but by can do does for from has have how i if in into is it its of on or our so that the their them then there these they this to was we were what when where which who why will with you your about should would could not no yes all any my me get set use using used".split(" "));function ha(t){let e=[],r=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u);for(let n of r)n.length<2||GI.has(n)||(n.length>4&&n.endsWith("ies")?n=n.slice(0,-3)+"y":n.length>3&&n.endsWith("s")&&!n.endsWith("ss")&&(n=n.slice(0,-1)),e.push(n));return e}function XI(t,e){let r=[...new Set(ha(e))];if(r.length===0||t.length===0)return;let n=t.map(i=>{let a=[...ha(i.text),...ha(i.heading),...ha(i.heading)],c=new Map;for(let u of a)c.set(u,(c.get(u)??0)+1);return{len:a.length,tf:c}}),o=n.reduce((i,a)=>i+a.len,0)/n.length||1,s=n.length;for(let i of r){let a=n.filter(u=>u.tf.has(i)).length;if(a===0)continue;let c=Math.log(1+(s-a+.5)/(a+.5));n.forEach((u,l)=>{let d=u.tf.get(i)??0;d&&(t[l].score+=c*(d*2.2/(d+1.2*(1-.75+.75*u.len/o))))})}}async function Bv(t,e={}){let r=t.map(s=>KI(s,e)),n=e.query?.trim()||void 0,o;if(n&&(XI(r.flat(),n),e.semantic)){let{semanticRerank:s}=await Promise.resolve().then(()=>(Lv(),qv));o=(await s(r.flat(),n,{model:typeof e.semantic=="string"?e.semantic:void 0})).note}return{...YI(t,r,n,e),semanticNote:o}}function YI(t,e,r,n){let o=Math.max(1,n.budget??DI),s=e.flat(),i=[],a=[],c=[],u=0,l=(m,f)=>{if(!i.includes(m)){if(u+m.tokens>o){c.some(h=>h.id===m.id)||c.push({id:m.id,tokens:m.tokens,requested:f});return}i.push(m),u+=m.tokens}},d="outline";if(n.ids?.length){d="ids";let m=new Map(s.map(f=>[f.id,f]));for(let f of n.ids){let h=m.get(f);h?l(h,!0):a.push(f)}}if(r){d==="outline"&&(d="query");for(let m of[...s].filter(f=>f.score>0).sort((f,h)=>h.score-f.score))l(m,!1)}let p=new Map(s.map((m,f)=>[m,f]));return i.sort((m,f)=>p.get(m)-p.get(f)),{mode:d,query:r,budget:o,totalTokens:s.reduce((m,f)=>m+f.tokens,0),packedTokens:u,selected:i,chunks:s,missingIds:a,unfit:c,sources:t.map((m,f)=>({name:m.name,tokens:e[f].reduce((h,y)=>h+y.tokens,0),chunks:e[f].length,selected:e[f].filter(h=>i.includes(h)).length}))}}function Of(t,e){let r=t.slice(0,e).map(n=>` ${n.id} L${n.startLine}-${n.endLine} ~${H(n.tokens)} ${n.heading}`);return t.length>e&&r.push(` \u2026 ${t.length-e} more`),r}function Jv(t,{outlineLimit:e=60}={}){let r=[],n=t.totalTokens>0?Math.round(t.packedTokens/t.totalTokens*100):0,o=t.sources.length===1?t.sources[0].name:`${t.sources.length} files`;if(t.mode==="outline")return r.push(`OUTLINE of ${o}: ~${H(t.totalTokens)} tokens in ${t.chunks.length} chunks. Nothing packed: pass a query, or chunk ids from this list.`),r.push(...Of(t.chunks,e)),r.join(`
84
+ `);r.push(`PACKED ~${H(t.packedTokens)} of ~${H(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${H(t.budget)}.`),t.missingIds.length&&r.push(`Unknown ids: ${t.missingIds.join(", ")}.`),t.semanticNote&&r.push(`(${t.semanticNote})`);let s=(t.unfit??[]).filter(a=>a.requested);if(t.selected.length>0&&s.length>0&&r.push(`Did not fit the budget of ${H(t.budget)}: ${s.map(a=>`${a.id} (~${H(a.tokens)})`).join(", ")}. Ask for it alone or with a larger budget (--max-tokens; MCP max_tokens).`),t.selected.length===0&&(t.unfit??[]).length>0){let a=t.unfit[0],c=t.chunks.find(u=>u.id===a.id);return r.push(`Nothing fit the budget of ${H(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${H(a.tokens)} tokens. Raise the budget to at least ${a.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`),r.push(...Of(t.chunks,e)),r.join(`
85
+ `)}if(t.selected.length===0)return r.push("No chunk matched. Choose from the outline by id, or rephrase with words the document would use."),r.push(...Of(t.chunks,e)),r.join(`
86
86
  `);for(let a of t.selected)r.push("",`\u2500\u2500 ${a.id} \xB7 L${a.startLine}-${a.endLine}${a.heading?` \xB7 ${a.heading}`:""} \xB7 ~${H(a.tokens)}`,a.text);let i=t.chunks.length-t.selected.length;if(i>0){let a=t.chunks.filter(c=>c.score>0&&!t.selected.includes(c)).sort((c,u)=>u.score-c.score).slice(0,5);r.push("",`Not included: ${i} chunk(s). `+(a.length?`Next best: ${a.map(c=>`${c.id} (${c.heading||`L${c.startLine}`})`).join("; ")}.`:"Ask for the outline to see them."))}return r.join(`
87
- `)}var XI=new Set(["node_modules",".git","dist","build",".next","target","__pycache__",".venv","venv","vendor"]),ha={files:500,fileBytes:5*1024*1024,totalBytes:50*1024*1024};function YI(t){try{let e=Uv("git",["-C",t,"ls-files","-z","--cached","--others","--exclude-standard"],{encoding:"utf8",maxBuffer:67108864,timeout:3e4});return e.status!==0||typeof e.stdout!="string"?void 0:e.stdout.split("\0").filter(r=>r&&Fv(Kn(t,r))).sort()}catch{return}}function QI(t){let e=Uv("git",["-C",t,"ls-files","-z","--others","--ignored","--exclude-standard","--directory"],{encoding:"utf8",maxBuffer:67108864,timeout:3e4});return e.status===0&&typeof e.stdout=="string"&&e.stdout.length>0}function Jv(t,e){let r=Hv(t,e);return r===""||r!==".."&&!r.startsWith(".."+MI)&&!AI(r)}var eO=new Set([".npmrc",".pypirc",".netrc","_netrc",".git-credentials",".pgpass",".htpasswd"]),tO=new Set([".pem",".key",".p12",".pfx",".keystore",".jks"]);function rO(t){let e=Af(t),r=e.toLowerCase();if(r===".env"||r.startsWith(".env."))return"an .env file";if(eO.has(r))return`a credentials file (${e})`;if(/^id_(rsa|dsa|ecdsa|ed25519)(_sk)?$/.test(r)||/^id_(rsa|dsa|ecdsa|ed25519)/.test(r)&&!r.endsWith(".pub"))return"a private SSH key";if(tO.has(ga(r)))return`a key or certificate store (${ga(r)})`;let n=t.split(/[\\/]+/);if(r==="credentials"&&n[n.length-2]===".aws")return"AWS credentials"}function nO(){let t=CI(),e=[...[".ssh",".aws",".gnupg",".kube",".docker",".azure",Kn(".config","gcloud"),Kn("Library","Keychains"),".password-store"].map(n=>Kn(t,n)),"/etc/shadow","/etc/gshadow","/etc/sudoers","/etc/master.passwd","/etc/ssh"],r=e.map(n=>{try{return Cf(n)}catch{return n}});return[...new Set([...e,...r])]}function oO(t,e){return e.find(r=>Jv(r,t))}function Of(t){let e=t?.code;return e==="ENOENT"?"not found":e==="EACCES"||e==="EPERM"?"permission denied":e==="ENOTDIR"?"not a directory":e==="EISDIR"?"is a directory":e==="ELOOP"?"too many symlinks":e?`unreadable (${e})`:`unreadable (${t?.message??t})`}function Wv(t,e=process.cwd()){let r=typeof e=="string"?{cwd:e}:e,n=r.cwd??process.cwd(),o=r.includeSecrets===!0,s=r.secretsHint??"",i=o?[]:nO(),a=[],c=[],u=0,l=new Set,d="",p=0,m=!1,f=y=>{try{return Cf(y)}catch{return NI(y)}},h=(y,_)=>{if(a.length>=ha.files){(_||c.length<20)&&c.push(`${y}: over ${ha.files} files`);return}let v;try{v=_?OI(y):PI(y)}catch(R){c.push(`${y}: ${Of(R)}`);return}if(v.isSymbolicLink()){let R;try{R=Cf(y)}catch{return}Jv(d,R)||c.push(`${y}: symlink pointing outside the folder (not followed)`);return}if(i.length>0){let R=oO(f(y),i);if(R){_&&c.push(`${y}: refused, ${R} holds credentials${s}`);return}}if(v.isDirectory()){let R=Af(y);if(!_&&XI.has(R))return;if(!_&&R.startsWith(".")){p++;return}let ie=_?YI(y):void 0;if(_&&(m=ie!==void 0),ie){ie.length===0&&QI(y)&&c.push(`${y}: ignored by git (.gitignore); pack reads folders as git does, so ignored files stay out. Name a file to pack it anyway`);for(let Te of ie)h(Kn(y,Te),!1);return}let ae;try{ae=RI(y).sort()}catch(Te){c.push(`${y}: ${Of(Te)}`);return}for(let Te of ae)h(Kn(y,Te),!1);return}if(!v.isFile()){_&&c.push(`${y}: not a regular file`);return}if(!o){let R=rO(y);if(R){c.push(`${y}: ${R}, likely holding secrets; not packed${s}`);return}}if(!_&&Af(y).startsWith(".")&&!m){p++;return}let g=f(y);if(l.has(g))return;if(v.size>ha.fileBytes||u+v.size>ha.totalBytes){c.push(`${y}: too large (${Math.round(v.size/1024)} KB)`);return}let x=Hv(n,y),$=x&&!x.startsWith("..")?x:y;if(Ov.has(ga(y).toLowerCase())){let R=Av(y);"error"in R?c.push(`${y}: ${R.error}`):(u+=v.size,l.add(g),a.push({name:$,text:R.text}));return}let D;try{D=II(y)}catch(R){c.push(`${y}: ${Of(R)}`);return}if(D.subarray(0,8e3).includes(0)){_&&c.push(`${y}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);return}u+=v.size,l.add(g),a.push({name:$,text:D.toString("utf8")})};for(let y of t){if(!Fv(y)){c.push(`${y}: not found`);continue}d=f(y),p=0,m=!1,h(y,!0),p>0&&c.push(`${y}: ${p} hidden file(s) or folder(s) not read (name one to pack it)`)}return{sources:a,skipped:c}}var GO=`Context hygiene rules (always on):
87
+ `)}var QI=new Set(["node_modules",".git","dist","build",".next","target","__pycache__",".venv","venv","vendor"]),ga={files:500,fileBytes:5*1024*1024,totalBytes:50*1024*1024};function eO(t){try{let e=Fv("git",["-C",t,"ls-files","-z","--cached","--others","--exclude-standard"],{encoding:"utf8",maxBuffer:67108864,timeout:3e4});return e.status!==0||typeof e.stdout!="string"?void 0:e.stdout.split("\0").filter(r=>r&&Hv(Kn(t,r))).sort()}catch{return}}function tO(t){let e=Fv("git",["-C",t,"ls-files","-z","--others","--ignored","--exclude-standard","--directory"],{encoding:"utf8",maxBuffer:67108864,timeout:3e4});return e.status===0&&typeof e.stdout=="string"&&e.stdout.length>0}function Wv(t,e){let r=Vv(t,e);return r===""||r!==".."&&!r.startsWith(".."+ZI)&&!MI(r)}var rO=new Set([".npmrc",".pypirc",".netrc","_netrc",".git-credentials",".pgpass",".htpasswd"]),nO=new Set([".pem",".key",".p12",".pfx",".keystore",".jks"]);function oO(t){let e=Nf(t),r=e.toLowerCase();if(r===".env"||r.startsWith(".env."))return"an .env file";if(rO.has(r))return`a credentials file (${e})`;if(/^id_(rsa|dsa|ecdsa|ed25519)(_sk)?$/.test(r)||/^id_(rsa|dsa|ecdsa|ed25519)/.test(r)&&!r.endsWith(".pub"))return"a private SSH key";if(nO.has(ya(r)))return`a key or certificate store (${ya(r)})`;let n=t.split(/[\\/]+/);if(r==="credentials"&&n[n.length-2]===".aws")return"AWS credentials"}function sO(){let t=NI(),e=[...[".ssh",".aws",".gnupg",".kube",".docker",".azure",Kn(".config","gcloud"),Kn("Library","Keychains"),".password-store"].map(n=>Kn(t,n)),"/etc/shadow","/etc/gshadow","/etc/sudoers","/etc/master.passwd","/etc/ssh"],r=e.map(n=>{try{return Af(n)}catch{return n}});return[...new Set([...e,...r])]}function iO(t,e){return e.find(r=>Wv(r,t))}function Cf(t){let e=t?.code;return e==="ENOENT"?"not found":e==="EACCES"||e==="EPERM"?"permission denied":e==="ENOTDIR"?"not a directory":e==="EISDIR"?"is a directory":e==="ELOOP"?"too many symlinks":e?`unreadable (${e})`:`unreadable (${t?.message??t})`}function Kv(t,e=process.cwd()){let r=typeof e=="string"?{cwd:e}:e,n=r.cwd??process.cwd(),o=r.includeSecrets===!0,s=r.secretsHint??"",i=o?[]:sO(),a=[],c=[],u=0,l=new Set,d="",p=0,m=!1,f=y=>{try{return Af(y)}catch{return jI(y)}},h=(y,_)=>{if(a.length>=ga.files){(_||c.length<20)&&c.push(`${y}: over ${ga.files} files`);return}let v;try{v=_?AI(y):II(y)}catch(R){c.push(`${y}: ${Cf(R)}`);return}if(v.isSymbolicLink()){let R;try{R=Af(y)}catch{return}Wv(d,R)||c.push(`${y}: symlink pointing outside the folder (not followed)`);return}if(i.length>0){let R=iO(f(y),i);if(R){_&&c.push(`${y}: refused, ${R} holds credentials${s}`);return}}if(v.isDirectory()){let R=Nf(y);if(!_&&QI.has(R))return;if(!_&&R.startsWith(".")){p++;return}let ae=_?eO(y):void 0;if(_&&(m=ae!==void 0),ae){ae.length===0&&tO(y)&&c.push(`${y}: ignored by git (.gitignore); pack reads folders as git does, so ignored files stay out. Name a file to pack it anyway`);for(let Te of ae)h(Kn(y,Te),!1);return}let ce;try{ce=OI(y).sort()}catch(Te){c.push(`${y}: ${Cf(Te)}`);return}for(let Te of ce)h(Kn(y,Te),!1);return}if(!v.isFile()){_&&c.push(`${y}: not a regular file`);return}if(!o){let R=oO(y);if(R){c.push(`${y}: ${R}, likely holding secrets; not packed${s}`);return}}if(!_&&Nf(y).startsWith(".")&&!m){p++;return}let g=f(y);if(l.has(g))return;if(v.size>ga.fileBytes||u+v.size>ga.totalBytes){c.push(`${y}: too large (${Math.round(v.size/1024)} KB)`);return}let x=Vv(n,y),$=x&&!x.startsWith("..")?x:y;if(Cv.has(ya(y).toLowerCase())){let R=Nv(y);"error"in R?c.push(`${y}: ${R.error}`):(u+=v.size,l.add(g),a.push({name:$,text:R.text}));return}let D;try{D=CI(y)}catch(R){c.push(`${y}: ${Cf(R)}`);return}if(D.subarray(0,8e3).includes(0)){_&&c.push(`${y}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);return}u+=v.size,l.add(g),a.push({name:$,text:D.toString("utf8")})};for(let y of t){if(!Hv(y)){c.push(`${y}: not found`);continue}d=f(y),p=0,m=!1,h(y,!0),p>0&&c.push(`${y}: ${p} hidden file(s) or folder(s) not read (name one to pack it)`)}return{sources:a,skipped:c}}var Gv=`Context hygiene rules (always on):
88
88
  1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; act on its top finding. In a chat app pass a \`sketch\` (turns + big blocks). Do not estimate token counts yourself.
89
89
  2. Summarize any paste or tool result over ~2k tokens into the points you need; keep it verbatim only to edit or quote it exactly.
90
90
  3. Refer to earlier content by name; never re-quote it or inline base64.
91
91
  4. To answer from a big file or folder you won't edit, call pack_context with the question; don't read it whole.
92
- 5. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.`,XO=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"];function R0({fileAccess:t=!0}={}){let e=new na({name:"context-doctor",version:"0.35.0"},{instructions:GO});return e.tool("profile_context","Profile an LLM conversation or prompt: token breakdown, largest blocks, and findings about wasted context (duplicates, oversized pastes or tool results, base64 blobs, long history). Pass ONE input: `conversation` (full OpenAI/Anthropic JSON or raw text) or `sketch` (chat apps such as Claude Desktop or ChatGPT, where you cannot export the conversation: the turn count plus the few blocks that matter, ~120 tokens). Call it whenever the user asks about token usage, context size, cost, speed or limits, and once on your own when the conversation first passes ~30 turns or 3+ large pastes. Act on the top finding.",{conversation:te.string().optional().describe("Conversation JSON (OpenAI or Anthropic format, or bare message array) or raw prompt text. Omit in chat apps and pass `sketch`."),sketch:te.object({turns:te.number().int().nonnegative().max(1e5).describe("User+assistant exchanges so far"),model:te.string().optional().describe("Model this chat runs as, e.g. claude-sonnet-5, gpt-5"),blocks:te.array(te.object({turn:te.number().int().positive().max(1e5).describe("1-based turn the block sits in"),kind:te.enum(["paste","code","tool_result","image","base64","text"]),label:te.string().describe("Short name you can refer to later, e.g. 'the nginx config'"),approx_tokens:te.number().positive().max(1e7).optional(),approx_lines:te.number().positive().max(1e6).optional(),approx_words:te.number().positive().max(5e6).optional(),approx_chars:te.number().positive().max(4e7).optional(),repeated:te.number().int().positive().max(1e3).optional().describe("Times this same content appears (2+ = duplicate)"),stale:te.boolean().optional().describe("Already acted on; nothing in it is still needed")})).max(500).describe("Only the blocks over ~500 tokens, repeated, or images. Plain turns need not be listed.")}).optional().describe("Coarse description of the conversation for chat apps. One size hint per block: lines for code, words for prose, chars (or tokens) for logs and tool output, which vary most per line."),model:te.string().optional().describe("Target model name for context-window math, e.g. claude-sonnet-5 or gpt-4o")},{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:r,sketch:n,model:o})=>{if(n)return{content:[{type:"text",text:(r?"Note: both `conversation` and `sketch` were passed; profiled the sketch only. Pass one.\n\n":"")+Pv({...n,model:n.model??o})}]};if(!r)return{isError:!0,content:[{type:"text",text:"Pass either `conversation` (full JSON or text) or `sketch` (turns + large/repeated blocks). In a chat app, use `sketch`."}]};let s=vv(uv(r),o);return{content:[{type:"text",text:Sv(s)}]}}),e.tool("optimize_context","Rewrite a conversation to reclaim tokens with deterministic strategies (dedupe, trim stale tool results, strip base64; prune-history is optional and lossy). Returns the slimmed JSON and a savings summary; no LLM calls. Results over 100k chars are not echoed back (summary and a CLI command instead). Use after profile_context finds waste the user wants fixed. Add prune-history only with the user's consent, then write the replacement summary as the result instructs.",{conversation:te.string().describe("Conversation JSON (OpenAI or Anthropic format, or bare message array)"),strategies:te.array(te.enum(XO)).optional().describe("Default: dedupe, trim-tool-results, strip-base64. Add trim-tool-calls for big inline file writes, prune-history for lossy compaction of old turns."),keep_recent:te.number().int().nonnegative().optional().describe("Messages at the tail to leave untouched (default 6; 0 = none; prune-history keeps at least 2)"),max_tool_result_tokens:te.number().int().positive().optional().describe("Token budget for trimmed tool results (default 300)")},{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:r,strategies:n,keep_recent:o,max_tool_result_tokens:s})=>{let i=$v(r,{strategies:n,keepRecent:o,maxToolResultTokens:s}),a=i.tokensBefore-i.tokensAfter;a>0&&da({ev:"optimize",src:"mcp",saved:a,model:i.conversation?.model});let c=`Saved ~${H(a)} tokens (${H(i.tokensBefore)} \u2192 ${H(i.tokensAfter)}) via ${i.applied.length} change(s):
92
+ 5. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.`;var YO=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"];function O0({fileAccess:t=!0}={}){let e=new na({name:"context-doctor",version:"0.36.0"},{instructions:Gv});return e.tool("profile_context","Profile an LLM conversation or prompt: token breakdown, largest blocks, and findings about wasted context (duplicates, oversized pastes or tool results, base64 blobs, long history). Pass ONE input: `conversation` (full OpenAI/Anthropic JSON or raw text) or `sketch` (chat apps such as Claude Desktop or ChatGPT, where you cannot export the conversation: the turn count plus the few blocks that matter, ~120 tokens). Call it whenever the user asks about token usage, context size, cost, speed or limits, and once on your own when the conversation first passes ~30 turns or 3+ large pastes. Act on the top finding.",{conversation:te.string().optional().describe("Conversation JSON (OpenAI or Anthropic format, or bare message array) or raw prompt text. Omit in chat apps and pass `sketch`."),sketch:te.object({turns:te.number().int().nonnegative().max(1e5).describe("User+assistant exchanges so far"),model:te.string().optional().describe("Model this chat runs as, e.g. claude-sonnet-5, gpt-5"),blocks:te.array(te.object({turn:te.number().int().positive().max(1e5).describe("1-based turn the block sits in"),kind:te.enum(["paste","code","tool_result","image","base64","text"]),label:te.string().describe("Short name you can refer to later, e.g. 'the nginx config'"),approx_tokens:te.number().positive().max(1e7).optional(),approx_lines:te.number().positive().max(1e6).optional(),approx_words:te.number().positive().max(5e6).optional(),approx_chars:te.number().positive().max(4e7).optional(),repeated:te.number().int().positive().max(1e3).optional().describe("Times this same content appears (2+ = duplicate)"),stale:te.boolean().optional().describe("Already acted on; nothing in it is still needed")})).max(500).describe("Only the blocks over ~500 tokens, repeated, or images. Plain turns need not be listed.")}).optional().describe("Coarse description of the conversation for chat apps. One size hint per block: lines for code, words for prose, chars (or tokens) for logs and tool output, which vary most per line."),model:te.string().optional().describe("Target model name for context-window math, e.g. claude-sonnet-5 or gpt-4o")},{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:r,sketch:n,model:o})=>{if(n)return{content:[{type:"text",text:(r?"Note: both `conversation` and `sketch` were passed; profiled the sketch only. Pass one.\n\n":"")+Rv({...n,model:n.model??o})}]};if(!r)return{isError:!0,content:[{type:"text",text:"Pass either `conversation` (full JSON or text) or `sketch` (turns + large/repeated blocks). In a chat app, use `sketch`."}]};let s=xv(lv(r),o);return{content:[{type:"text",text:Ev(s)}]}}),e.tool("optimize_context","Rewrite a conversation to reclaim tokens with deterministic strategies (dedupe, trim stale tool results, strip base64; prune-history is optional and lossy). Returns the slimmed JSON and a savings summary; no LLM calls. Results over 100k chars are not echoed back (summary and a CLI command instead). Use after profile_context finds waste the user wants fixed. Add prune-history only with the user's consent, then write the replacement summary as the result instructs.",{conversation:te.string().describe("Conversation JSON (OpenAI or Anthropic format, or bare message array)"),strategies:te.array(te.enum(YO)).optional().describe("Default: dedupe, trim-tool-results, strip-base64. Add trim-tool-calls for big inline file writes, prune-history for lossy compaction of old turns."),keep_recent:te.number().int().nonnegative().optional().describe("Messages at the tail to leave untouched (default 6; 0 = none; prune-history keeps at least 2)"),max_tool_result_tokens:te.number().int().positive().optional().describe("Token budget for trimmed tool results (default 300)")},{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:r,strategies:n,keep_recent:o,max_tool_result_tokens:s})=>{let i=kv(r,{strategies:n,keepRecent:o,maxToolResultTokens:s}),a=i.tokensBefore-i.tokensAfter;a>0&&fa({ev:"optimize",src:"mcp",saved:a,model:i.conversation?.model});let c=`Saved ~${H(a)} tokens (${H(i.tokensBefore)} \u2192 ${H(i.tokensAfter)}) via ${i.applied.length} change(s):
93
93
  `+i.applied.map(p=>`- [${p.strategy}] message #${p.messageIndex}: ${p.note} (~${H(p.tokensSaved)})`).join(`
94
94
  `),u=1e5,l=JSON.stringify(i.conversation),d=[{type:"text",text:c},l.length<=u?{type:"text",text:l}:{type:"text",text:`[optimized conversation is ${l.length} chars \u2014 too large to echo into this context. Tell the user the savings above and that \`npx context-doctor optimize <file> --out slim.json\` produces the file directly.]`}];return i.prunedDigest&&d.push({type:"text",text:`ACTION REQUIRED (you, the assistant calling this tool): the pruned turns are digested below. Write a dense factual summary of them (\u2264150 tokens: decisions, current state, open items, key identifiers) and replace the '[context-doctor: ... pruned]' stub message in the conversation above with your summary before presenting the result.
95
95
 
96
96
  PRUNED TURNS DIGEST:
97
- `+i.prunedDigest}),{content:d}}),e.tool("pack_context","Read only the parts of large files a question needs: chunks files or folders along their structure, ranks the chunks against `query` and returns the best that fit `max_tokens`, each with an id and line range. No query: an outline; pick with `ids`. Use instead of reading a big doc, log or folder whole when not editing it. Text, code, PDF, Word, PowerPoint, ODT.",{paths:te.array(te.string()).max(50).optional().describe("Files or folders, absolute paths; over HTTP pass `text`"),text:te.string().optional().describe("Raw text to pack instead of files"),query:te.string().optional().describe("The question; omit for an outline"),max_tokens:te.number().int().positive().max(2e5).optional().describe("Budget, default 4000"),ids:te.array(te.string()).max(200).optional().describe("Chunk ids from an outline or result, e.g. docs/guide.md#4"),model:te.string().optional().describe("Model the budget is counted for (default Claude)"),semantic:te.boolean().optional().describe("Also rank by meaning (local Ollama embeddings)")},{title:"Pack context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({paths:r,text:n,query:o,max_tokens:s,ids:i,model:a,semantic:c})=>{let u=f=>({content:[{type:"text",text:f}],isError:!0});if(r?.length&&!t)return u("This server runs over HTTP and does not read files. Pass the document as `text`.");let{sources:l,skipped:d}=r?.length?Wv(r):{sources:[],skipped:[]};if(n&&l.push({name:"text",text:n}),l.length===0)return u(d.length?`Nothing readable: ${d.join("; ")}`:"Pass `paths` (files or folders) or `text`.");let p=await Vv(l,{query:o,budget:s,ids:i,model:a,semantic:c}),m=d.length?`
98
- Skipped: ${d.slice(0,10).join("; ")}${d.length>10?` (+${d.length-10} more)`:""}`:"";return{content:[{type:"text",text:Bv(p)+m}]}}),e.prompt("context_checkup","Profile this conversation's context and apply the top fix. One click, no typing.",async()=>({messages:[{role:"user",content:{type:"text",text:"Run profile_context on our conversation so far: pass a `sketch` (turn count, the model you are running as, and every block over ~500 tokens, repeated, or an image; one size hint each). Report the total, the top three findings, and the estimated recoverable tokens in under 120 words. Then, if the top finding is recoverable, apply it: summarize the offending content into the points still needed and tell me what you dropped. Do not re-quote the content you are summarizing."}}]})),e.tool("context_best_practices","Curated checklist of context-management practices, optionally for one provider. Call it when the user asks how to keep context lean or how to structure prompts for caching.",{provider:te.enum(["general","anthropic","openai"]).optional().describe("Provider to specialize tips for (default: general)")},{title:"Context best practices",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({provider:r})=>({content:[{type:"text",text:[...I0.general,...r&&r!=="general"?I0[r]:[]].map((o,s)=>`${s+1}. ${o}`).join(`
99
- `)}]})),e}var I0={general:["Put stable content first (system prompt, tool definitions, reference docs) and volatile content last \u2014 prompt caches match byte-identical prefixes only.","Truncate or summarize tool results before they enter history; keep only what the model actually needs downstream.","Never inline base64/binary data in text content \u2014 use file/image APIs.","Summarize and drop conversation history past ~30-40 turns; models lose the middle of long contexts well before the hard limit.","Deduplicate: if the same document/result appears twice, replace later copies with a reference.","Measure before optimizing \u2014 profile the conversation to find the actual heavy hitters."],anthropic:["Use prompt caching with cache_control breakpoints after your stable prefix: cached reads cost 2.5-10% of input depending on the model, and cache writes 1.25x input (5-minute cache) or 2x (1-hour cache).","Current Claude generations have a 1M-token window (Haiku 200k), but quality degrades under heavy fill; aim to stay under ~70%.","For agents: prefer compact tool-result summaries in history and re-fetch details on demand."],openai:["Prefix caching is automatic for prompts >1024 tokens \u2014 but only on byte-identical prefixes, so keep the front of your prompt stable.","Use max_completion_tokens headroom math: input + output must fit the window together."]};function YO(t,e,r){t.headers[e]=r;let n=t.rawHeaders;for(let o=0;o<n.length;o+=2)if(n[o].toLowerCase()===e){n[o+1]=r;return}n.push(e,r)}var Jf=process.argv.slice(2);if(Jf.includes("--http")){let t=s=>{let i=Jf.indexOf(s);return i>=0?Jf[i+1]:void 0},e=Number(t("--port"))>0?Number(t("--port")):8808,r=t("--host")??"127.0.0.1",{createServer:n}=await import("node:http"),{StreamableHTTPServerTransport:o}=await Promise.resolve().then(()=>(P0(),z0));n(async(s,i)=>{try{if(s.url==="/health"){i.setHeader("content-type","application/json"),i.end(JSON.stringify({ok:!0,service:"context-doctor-mcp"}));return}if(!(s.url??"").startsWith("/mcp")){i.statusCode=404,i.end(JSON.stringify({error:"MCP endpoint is /mcp"}));return}if(s.method!=="POST"){i.statusCode=405,i.setHeader("allow","POST"),i.end(JSON.stringify({error:"Stateless server: POST /mcp only"}));return}let a=String(s.headers.accept??""),c=a.includes("text/event-stream");(!c||!a.includes("application/json"))&&YO(s,"accept","application/json, text/event-stream");let u=R0({fileAccess:!1}),l=new o({sessionIdGenerator:void 0,enableJsonResponse:!c});i.on("close",()=>{l.close(),u.close()}),await u.connect(l),await l.handleRequest(s,i)}catch(a){i.headersSent||(i.statusCode=500),i.end(JSON.stringify({error:a.message}))}}).listen(e,r,()=>{console.error(`context-doctor MCP (streamable HTTP) on http://${r}:${e}/mcp`),console.error("ChatGPT developer-mode connectors need a URL their servers can reach \u2014 expose this via your host or a tunnel.")})}else{let t=new sa;await R0().connect(t)}
97
+ `+i.prunedDigest}),{content:d}}),e.tool("pack_context","Read only the parts of large files a question needs: chunks files or folders along their structure, ranks the chunks against `query` and returns the best that fit `max_tokens`, each with an id and line range. No query: an outline; pick with `ids`. Use instead of reading a big doc, log or folder whole when not editing it. Text, code, PDF, Word, PowerPoint, ODT.",{paths:te.array(te.string()).max(50).optional().describe("Files or folders, absolute paths; over HTTP pass `text`"),text:te.string().optional().describe("Raw text to pack instead of files"),query:te.string().optional().describe("The question; omit for an outline"),max_tokens:te.number().int().positive().max(2e5).optional().describe("Budget, default 4000"),ids:te.array(te.string()).max(200).optional().describe("Chunk ids from an outline or result, e.g. docs/guide.md#4"),model:te.string().optional().describe("Model the budget is counted for (default Claude)"),semantic:te.boolean().optional().describe("Also rank by meaning (local Ollama embeddings)")},{title:"Pack context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({paths:r,text:n,query:o,max_tokens:s,ids:i,model:a,semantic:c})=>{let u=f=>({content:[{type:"text",text:f}],isError:!0});if(r?.length&&!t)return u("This server runs over HTTP and does not read files. Pass the document as `text`.");let{sources:l,skipped:d}=r?.length?Kv(r):{sources:[],skipped:[]};if(n&&l.push({name:"text",text:n}),l.length===0)return u(d.length?`Nothing readable: ${d.join("; ")}`:"Pass `paths` (files or folders) or `text`.");let p=await Bv(l,{query:o,budget:s,ids:i,model:a,semantic:c}),m=d.length?`
98
+ Skipped: ${d.slice(0,10).join("; ")}${d.length>10?` (+${d.length-10} more)`:""}`:"";return{content:[{type:"text",text:Jv(p)+m}]}}),e.prompt("context_checkup","Profile this conversation's context and apply the top fix. One click, no typing.",async()=>({messages:[{role:"user",content:{type:"text",text:"Run profile_context on our conversation so far: pass a `sketch` (turn count, the model you are running as, and every block over ~500 tokens, repeated, or an image; one size hint each). Report the total, the top three findings, and the estimated recoverable tokens in under 120 words. Then, if the top finding is recoverable, apply it: summarize the offending content into the points still needed and tell me what you dropped. Do not re-quote the content you are summarizing."}}]})),e.tool("context_best_practices","Curated checklist of context-management practices, optionally for one provider. Call it when the user asks how to keep context lean or how to structure prompts for caching.",{provider:te.enum(["general","anthropic","openai"]).optional().describe("Provider to specialize tips for (default: general)")},{title:"Context best practices",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({provider:r})=>({content:[{type:"text",text:[...C0.general,...r&&r!=="general"?C0[r]:[]].map((o,s)=>`${s+1}. ${o}`).join(`
99
+ `)}]})),e}var C0={general:["Put stable content first (system prompt, tool definitions, reference docs) and volatile content last \u2014 prompt caches match byte-identical prefixes only.","Truncate or summarize tool results before they enter history; keep only what the model actually needs downstream.","Never inline base64/binary data in text content \u2014 use file/image APIs.","Summarize and drop conversation history past ~30-40 turns; models lose the middle of long contexts well before the hard limit.","Deduplicate: if the same document/result appears twice, replace later copies with a reference.","Measure before optimizing \u2014 profile the conversation to find the actual heavy hitters."],anthropic:["Use prompt caching with cache_control breakpoints after your stable prefix: cached reads cost 2.5-10% of input depending on the model, and cache writes 1.25x input (5-minute cache) or 2x (1-hour cache).","Current Claude generations have a 1M-token window (Haiku 200k), but quality degrades under heavy fill; aim to stay under ~70%.","For agents: prefer compact tool-result summaries in history and re-fetch details on demand."],openai:["Prefix caching is automatic for prompts >1024 tokens \u2014 but only on byte-identical prefixes, so keep the front of your prompt stable.","Use max_completion_tokens headroom math: input + output must fit the window together."]};function QO(t,e,r){t.headers[e]=r;let n=t.rawHeaders;for(let o=0;o<n.length;o+=2)if(n[o].toLowerCase()===e){n[o+1]=r;return}n.push(e,r)}var Wf=process.argv.slice(2);if(Wf.includes("--http")){let t=s=>{let i=Wf.indexOf(s);return i>=0?Wf[i+1]:void 0},e=Number(t("--port"))>0?Number(t("--port")):8808,r=t("--host")??"127.0.0.1",{createServer:n}=await import("node:http"),{StreamableHTTPServerTransport:o}=await Promise.resolve().then(()=>(I0(),R0));n(async(s,i)=>{try{if(s.url==="/health"){i.setHeader("content-type","application/json"),i.end(JSON.stringify({ok:!0,service:"context-doctor-mcp"}));return}if(!(s.url??"").startsWith("/mcp")){i.statusCode=404,i.end(JSON.stringify({error:"MCP endpoint is /mcp"}));return}if(s.method!=="POST"){i.statusCode=405,i.setHeader("allow","POST"),i.end(JSON.stringify({error:"Stateless server: POST /mcp only"}));return}let a=String(s.headers.accept??""),c=a.includes("text/event-stream");(!c||!a.includes("application/json"))&&QO(s,"accept","application/json, text/event-stream");let u=O0({fileAccess:!1}),l=new o({sessionIdGenerator:void 0,enableJsonResponse:!c});i.on("close",()=>{l.close(),u.close()}),await u.connect(l),await l.handleRequest(s,i)}catch(a){i.headersSent||(i.statusCode=500),i.end(JSON.stringify({error:a.message}))}}).listen(e,r,()=>{console.error(`context-doctor MCP (streamable HTTP) on http://${r}:${e}/mcp`),console.error("ChatGPT developer-mode connectors need a URL their servers can reach \u2014 expose this via your host or a tunnel.")})}else{let t=new sa;await O0().connect(t)}