context-doctor 0.34.0 → 0.35.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/README.md +4 -1
- package/dist/autoclear.d.ts +5 -2
- package/dist/autoclear.js +57 -19
- package/dist/cachemisses.d.ts +88 -0
- package/dist/cachemisses.js +325 -0
- package/dist/cacheplan.d.ts +1 -1
- package/dist/cacheplan.js +47 -3
- package/dist/cli.js +63 -16
- package/dist/compactquality.js +9 -1
- package/dist/config.d.ts +11 -0
- package/dist/config.js +117 -4
- package/dist/dashboard.js +15 -1
- package/dist/doctor.d.ts +18 -0
- package/dist/doctor.js +71 -1
- package/dist/hook.d.ts +18 -0
- package/dist/hook.js +35 -4
- package/dist/impact.js +32 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +15 -0
- package/dist/install.js +105 -26
- package/dist/mcp.js +52 -49
- package/dist/modelswitch.d.ts +76 -0
- package/dist/modelswitch.js +184 -0
- package/dist/optimize.js +40 -6
- package/dist/pack.d.ts +32 -3
- package/dist/pack.js +176 -24
- package/dist/parse.d.ts +3 -1
- package/dist/parse.js +123 -3
- package/dist/pricing.js +8 -0
- package/dist/profile.js +60 -17
- package/dist/proxy.d.ts +9 -1
- package/dist/proxy.js +45 -9
- package/dist/report.js +8 -2
- package/dist/savings.d.ts +1 -1
- package/dist/savings.js +6 -1
- package/dist/session.js +19 -3
- package/dist/sketch.d.ts +2 -0
- package/dist/sketch.js +10 -1
- package/dist/tokens.js +20 -9
- package/dist/wrap.js +27 -5
- package/package.json +1 -1
package/dist/mcp.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cdRequire } from 'module'; const require = __cdRequire(import.meta.url);
|
|
3
|
-
var S0=Object.create;var ga=Object.defineProperty;var z0=Object.getOwnPropertyDescriptor;var E0=Object.getOwnPropertyNames;var T0=Object.getPrototypeOf,P0=Object.prototype.hasOwnProperty;var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Kn=(t,e)=>{for(var r in e)ga(t,r,{get:e[r],enumerable:!0})},R0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of E0(e))!P0.call(t,o)&&o!==r&&ga(t,o,{get:()=>e[o],enumerable:!(n=z0(e,o))||n.enumerable});return t};var ya=(t,e,r)=>(r=t!=null?S0(T0(t)):{},R0(e||!t||!t.__esModule?ga(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 Ye(t){return t&&Object.assign(ps,t),ps}var qx,Lx,jt,ps,dn=J(()=>{qx=Object.freeze({status:"aborted"});Lx=Symbol("zod_brand"),jt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ps={}});var K={};Kn(K,{BIGINT_FORMAT_RANGES:()=>Gf,Class:()=>$a,NUMBER_FORMAT_RANGES:()=>Ra,aborted:()=>Or,allowsEval:()=>Ea,assert:()=>Bx,assertEqual:()=>Ux,assertIs:()=>Hx,assertNever:()=>Vx,assertNotEqual:()=>Fx,assignProp:()=>za,cached:()=>eo,captureStackTrace:()=>hs,cleanEnum:()=>sb,cleanRegex:()=>ro,clone:()=>Qe,createTransparentProxy:()=>Yx,defineLazy:()=>ce,esc:()=>Ir,escapeRegex:()=>Xt,extend:()=>tb,finalizeIssue:()=>dt,floatSafeRemainder:()=>Sa,getElementAtPath:()=>Jx,getEnumValues:()=>Qn,getLengthableOrigin:()=>no,getParsedType:()=>Xx,getSizableOrigin:()=>Xf,isObject:()=>fn,isPlainObject:()=>pn,issue:()=>Ia,joinValues:()=>ms,jsonStringifyReplacer:()=>ka,merge:()=>rb,normalizeParams:()=>M,nullish:()=>to,numKeys:()=>Gx,omit:()=>eb,optionalKeys:()=>Pa,partial:()=>nb,pick:()=>Qx,prefixIssues:()=>wt,primitiveTypes:()=>Wf,promiseAllObject:()=>Kx,propertyKeyTypes:()=>Ta,randomString:()=>Wx,required:()=>ob,stringifyPrimitive:()=>gs,unwrapMessage:()=>Yn});function Ux(t){return t}function Fx(t){return t}function Hx(t){}function Vx(t){throw new Error}function Bx(t){}function Qn(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 ms(t,e="|"){return t.map(r=>gs(r)).join(e)}function ka(t,e){return typeof e=="bigint"?e.toString():e}function eo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function to(t){return t==null}function ro(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Sa(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 ce(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 za(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Jx(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Kx(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 Wx(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Ir(t){return JSON.stringify(t)}function fn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pn(t){if(fn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(fn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Gx(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Xt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qe(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function M(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 Yx(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 gs(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Pa(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function Qx(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 Qe(t,{...t._zod.def,shape:r,checks:[]})}function eb(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 Qe(t,{...t._zod.def,shape:r,checks:[]})}function tb(t,e){if(!pn(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 za(this,"shape",n),n},checks:[]};return Qe(t,r)}function rb(t,e){return Qe(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return za(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function nb(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 Qe(e,{...e._zod.def,shape:o,checks:[]})}function ob(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 Qe(e,{...e._zod.def,shape:o,checks:[]})}function Or(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function wt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Yn(t){return typeof t=="string"?t:t?.message}function dt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Yn(t.inst?._zod.def?.error?.(t))??Yn(e?.error?.(t))??Yn(r.customError?.(t))??Yn(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Xf(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function no(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ia(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function sb(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var hs,Ea,Xx,Ta,Wf,Ra,Gf,$a,$t=J(()=>{hs=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Ea=eo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});Xx=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}`)}},Ta=new Set(["string","number","symbol"]),Wf=new Set(["string","number","bigint","boolean","symbol","undefined"]);Ra={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]},Gf={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};$a=class{constructor(...e){}}});function Oa(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 Ca(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 Yf,ys,oo,Aa=J(()=>{dn();$t();Yf=(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,ka,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ys=w("$ZodError",Yf),oo=w("$ZodError",Yf,{Parent:Error})});var Na,Ma,ja,Za,Da,Cr,qa,Ar,La=J(()=>{dn();Aa();$t();Na=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 jt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>dt(c,s,Ye())));throw hs(a,o?.callee),a}return i.value},Ma=Na(oo),ja=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=>dt(c,s,Ye())));throw hs(a,o?.callee),a}return i.value},Za=ja(oo),Da=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 jt;return s.issues.length?{success:!1,error:new(t??ys)(s.issues.map(i=>dt(i,o,Ye())))}:{success:!0,data:s.value}},Cr=Da(oo),qa=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=>dt(i,o,Ye())))}:{success:!0,data:s.value}},Ar=qa(oo)});function cp(){return new RegExp(ab,"u")}function _p(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 vp(t){return new RegExp(`^${_p(t)}$`)}function xp(t){let e=_p({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(`^${gp}T(?:${n})$`)}var Qf,ep,tp,rp,np,op,sp,ip,Ua,ap,ab,up,lp,dp,fp,pp,Fa,mp,hp,gp,yp,bp,wp,$p,kp,Sp,zp,Ep,vs=J(()=>{Qf=/^[cC][^\s-]{8,}$/,ep=/^[0-9a-z]+$/,tp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,rp=/^[0-9a-vA-V]{20}$/,np=/^[A-Za-z0-9]{27}$/,op=/^[a-zA-Z0-9_-]{21}$/,sp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ip=/^([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})$/,Ua=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)$/,ap=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ab="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";up=/^(?:(?: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])$/,lp=/^(([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})$/,dp=/^((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])$/,fp=/^(([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])$/,pp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fa=/^[A-Za-z0-9_-]*$/,mp=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,hp=/^\+(?:[0-9]){6,14}[0-9]$/,gp="(?:(?:\\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])))",yp=new RegExp(`^${gp}$`);bp=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},wp=/^\d+$/,$p=/^-?\d+(?:\.\d+)?/i,kp=/true|false/i,Sp=/null/i,zp=/^[^A-Z]*$/,Ep=/^[^a-z]*$/});var ze,Tp,Ha,Va,Pp,Rp,Ip,Op,Cp,so,Ap,Np,Mp,jp,Zp,Dp,qp,xs=J(()=>{dn();vs();$t();ze=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Tp={number:"number",bigint:"bigint",object:"date"},Ha=w("$ZodCheckLessThan",(t,e)=>{ze.init(t,e);let r=Tp[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})}}),Va=w("$ZodCheckGreaterThan",(t,e)=>{ze.init(t,e);let r=Tp[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})}}),Pp=w("$ZodCheckMultipleOf",(t,e)=>{ze.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):Sa(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})}}),Rp=w("$ZodCheckNumberFormat",(t,e)=>{ze.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Ra[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=wp)}),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})}}),Ip=w("$ZodCheckMaxLength",(t,e)=>{var r;ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!to(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=no(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Op=w("$ZodCheckMinLength",(t,e)=>{var r;ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!to(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=no(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Cp=w("$ZodCheckLengthEquals",(t,e)=>{var r;ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!to(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=no(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})}}),so=w("$ZodCheckStringFormat",(t,e)=>{var r,n;ze.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=()=>{})}),Ap=w("$ZodCheckRegex",(t,e)=>{so.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})}}),Np=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=zp),so.init(t,e)}),Mp=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Ep),so.init(t,e)}),jp=w("$ZodCheckIncludes",(t,e)=>{ze.init(t,e);let r=Xt(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})}}),Zp=w("$ZodCheckStartsWith",(t,e)=>{ze.init(t,e);let r=new RegExp(`^${Xt(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})}}),Dp=w("$ZodCheckEndsWith",(t,e)=>{ze.init(t,e);let r=new RegExp(`.*${Xt(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})}}),qp=w("$ZodCheckOverwrite",(t,e)=>{ze.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var bs,Ba=J(()=>{bs=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 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(`
|
|
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
|
|
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(`
|
|
6
6
|
if (${g}.issues.length) {
|
|
7
|
-
if (input[${
|
|
8
|
-
if (${
|
|
9
|
-
newResult[${
|
|
7
|
+
if (input[${x}] === undefined) {
|
|
8
|
+
if (${x} in input) {
|
|
9
|
+
newResult[${x}] = undefined;
|
|
10
10
|
}
|
|
11
11
|
} else {
|
|
12
12
|
payload.issues = payload.issues.concat(
|
|
13
13
|
${g}.issues.map((iss) => ({
|
|
14
14
|
...iss,
|
|
15
|
-
path: iss.path ? [${
|
|
15
|
+
path: iss.path ? [${x}, ...iss.path] : [${x}],
|
|
16
16
|
}))
|
|
17
17
|
);
|
|
18
18
|
}
|
|
19
19
|
} else if (${g}.value === undefined) {
|
|
20
|
-
if (${
|
|
20
|
+
if (${x} in input) newResult[${x}] = undefined;
|
|
21
21
|
} else {
|
|
22
|
-
newResult[${
|
|
22
|
+
newResult[${x}] = ${g}.value;
|
|
23
23
|
}
|
|
24
|
-
`)}else{let g=h[v];
|
|
24
|
+
`)}else{let g=h[v];p.write(`const ${g} = ${f(v)};`),p.write(`
|
|
25
25
|
if (${g}.issues.length) payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
|
|
26
26
|
...iss,
|
|
27
|
-
path: iss.path ? [${
|
|
28
|
-
})));`),m.write(`newResult[${Ir(v)}] = ${g}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let _=m.compile();return(v,g)=>_(d,v,g)},o,s=fn,i=!ps.jitless,c=i&&Ea.value,u=e.catchall,l;t._zod.parse=(d,m)=>{l??(l=r.value);let p=d.value;if(!s(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d;let f=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),d=o(d,m);else{d.value={};let g=l.shape;for(let b of l.keys){let S=g[b],re=S._zod.run({value:p[b],issues:[]},m),L=S._zod.optin==="optional"&&S._zod.optout==="optional";re instanceof Promise?f.push(re.then(be=>L?Hp(be,d,b,p):ws(be,d,b))):L?Hp(re,d,b,p):ws(re,d,b)}}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(p)){if(y.has(g))continue;if(v==="never"){h.push(g);continue}let b=_.run({value:p[g],issues:[]},m);b instanceof Promise?f.push(b.then(S=>ws(S,d,g))):ws(b,d,g)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Ss=w("$ZodUnion",(t,e)=>{se.init(t,e),ce(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ce(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ce(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ce(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=>ro(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=>Vp(i,r,t,n)):Vp(s,r,t,n)}}),xc=w("$ZodDiscriminatedUnion",(t,e)=>{Ss.init(t,e);let r=t._zod.parse;ce(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=eo(()=>{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(!fn(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)}}),bc=w("$ZodIntersection",(t,e)=>{se.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])=>Bp(r,c,u)):Bp(r,s,i)}});wc=w("$ZodRecord",(t,e)=>{se.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!pn(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(...wt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...wt(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=>dt(u,n,Ye())),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(...wt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...wt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),$c=w("$ZodEnum",(t,e)=>{se.init(t,e);let r=Qn(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Ta.has(typeof n)).map(n=>typeof n=="string"?Xt(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}}),kc=w("$ZodLiteral",(t,e)=>{se.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Xt(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}}),Sc=w("$ZodTransform",(t,e)=>{se.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 jt;return r.value=o,r}}),zc=w("$ZodOptional",(t,e)=>{se.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ce(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ce(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ro(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)}),Ec=w("$ZodNullable",(t,e)=>{se.init(t,e),ce(t._zod,"optin",()=>e.innerType._zod.optin),ce(t._zod,"optout",()=>e.innerType._zod.optout),ce(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ro(r.source)}|null)$`):void 0}),ce(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)}),Tc=w("$ZodDefault",(t,e)=>{se.init(t,e),t._zod.optin="optional",ce(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=>Jp(s,e)):Jp(o,e)}});Pc=w("$ZodPrefault",(t,e)=>{se.init(t,e),t._zod.optin="optional",ce(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))}),Rc=w("$ZodNonOptional",(t,e)=>{se.init(t,e),ce(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=>Kp(s,t)):Kp(o,t)}});Ic=w("$ZodCatch",(t,e)=>{se.init(t,e),t._zod.optin="optional",ce(t._zod,"optout",()=>e.innerType._zod.optout),ce(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=>dt(i,n,Ye()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>dt(s,n,Ye()))},input:r.value}),r.issues=[]),r)}}),Oc=w("$ZodPipe",(t,e)=>{se.init(t,e),ce(t._zod,"values",()=>e.in._zod.values),ce(t._zod,"optin",()=>e.in._zod.optin),ce(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=>Wp(s,e,n)):Wp(o,e,n)}});Cc=w("$ZodReadonly",(t,e)=>{se.init(t,e),ce(t._zod,"propValues",()=>e.innerType._zod.propValues),ce(t._zod,"values",()=>e.innerType._zod.values),ce(t._zod,"optin",()=>e.innerType._zod.optin),ce(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(Gp):Gp(o)}});Ac=w("$ZodCustom",(t,e)=>{ze.init(t,e),se.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=>Xp(s,r,n,t));Xp(o,r,n,t)}})});function om(){return{localeError:db()}}var lb,db,sm=J(()=>{$t();lb=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},db=()=>{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 ${lb(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${gs(n.values[0])}`:`Invalid option: expected one of ${ms(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":""}: ${ms(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 zs=J(()=>{});function im(){return new ao}var fb,pb,ao,Yt,Mc=J(()=>{fb=Symbol("ZodOutput"),pb=Symbol("ZodInput"),ao=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)}};Yt=im()});function jc(t,e){return new t({type:"string",...M(e)})}function Zc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...M(e)})}function Es(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...M(e)})}function Dc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...M(e)})}function qc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(e)})}function Lc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(e)})}function Uc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(e)})}function Fc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...M(e)})}function Hc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...M(e)})}function Vc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(e)})}function Bc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...M(e)})}function Jc(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(e)})}function Kc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...M(e)})}function Wc(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...M(e)})}function Gc(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(e)})}function Xc(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(e)})}function Yc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(e)})}function Qc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(e)})}function eu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(e)})}function tu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...M(e)})}function ru(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...M(e)})}function nu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...M(e)})}function ou(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...M(e)})}function am(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(e)})}function cm(t,e){return new t({type:"string",format:"date",check:"string_format",...M(e)})}function um(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...M(e)})}function lm(t,e){return new t({type:"string",format:"duration",check:"string_format",...M(e)})}function su(t,e){return new t({type:"number",checks:[],...M(e)})}function iu(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...M(e)})}function au(t,e){return new t({type:"boolean",...M(e)})}function cu(t,e){return new t({type:"null",...M(e)})}function uu(t){return new t({type:"unknown"})}function lu(t,e){return new t({type:"never",...M(e)})}function Ts(t,e){return new Ha({check:"less_than",...M(e),value:t,inclusive:!1})}function co(t,e){return new Ha({check:"less_than",...M(e),value:t,inclusive:!0})}function Ps(t,e){return new Va({check:"greater_than",...M(e),value:t,inclusive:!1})}function uo(t,e){return new Va({check:"greater_than",...M(e),value:t,inclusive:!0})}function Rs(t,e){return new Pp({check:"multiple_of",...M(e),value:t})}function Is(t,e){return new Ip({check:"max_length",...M(e),maximum:t})}function mn(t,e){return new Op({check:"min_length",...M(e),minimum:t})}function Os(t,e){return new Cp({check:"length_equals",...M(e),length:t})}function du(t,e){return new Ap({check:"string_format",format:"regex",...M(e),pattern:t})}function fu(t){return new Np({check:"string_format",format:"lowercase",...M(t)})}function pu(t){return new Mp({check:"string_format",format:"uppercase",...M(t)})}function mu(t,e){return new jp({check:"string_format",format:"includes",...M(e),includes:t})}function hu(t,e){return new Zp({check:"string_format",format:"starts_with",...M(e),prefix:t})}function gu(t,e){return new Dp({check:"string_format",format:"ends_with",...M(e),suffix:t})}function Nr(t){return new qp({check:"overwrite",tx:t})}function yu(t){return Nr(e=>e.normalize(t))}function _u(){return Nr(t=>t.trim())}function vu(){return Nr(t=>t.toLowerCase())}function xu(){return Nr(t=>t.toUpperCase())}function dm(t,e,r){return new t({type:"array",element:e,...M(r)})}function bu(t,e,r){let n=M(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function wu(t,e,r){return new t({type:"custom",check:"custom",fn:e,...M(r)})}var fm=J(()=>{xs();$t()});var pm=J(()=>{});function $u(t,e){if(t instanceof ao){let n=new Cs(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 Cs(e);return r.process(t),r.emit(t,e)}function we(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 we(o.element,r);case"object":{for(let s in o.shape)if(we(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(we(s,r))return!0;return!1}case"intersection":return we(o.left,r)||we(o.right,r);case"tuple":{for(let s of o.items)if(we(s,r))return!0;return!!(o.rest&&we(o.rest,r))}case"record":return we(o.keyType,r)||we(o.valueType,r);case"map":return we(o.keyType,r)||we(o.valueType,r);case"set":return we(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return we(o.innerType,r);case"lazy":return we(o.getter(),r);case"default":return we(o.innerType,r);case"prefault":return we(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return we(o.in,r)||we(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Cs,mm=J(()=>{Mc();$t();Cs=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Yt,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},m=e._zod.parent;if(m)a.ref=m,this.process(m,d),this.seen.get(m).isParent=!0;else{let p=a.schema;switch(o.type){case"string":{let f=p;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 b=[...v];b.length===1?f.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{let f=p,{minimum:h,maximum:y,format:_,multipleOf:v,exclusiveMaximum:g,exclusiveMinimum:b}=e._zod.bag;typeof _=="string"&&_.includes("int")?f.type="integer":f.type="number",typeof b=="number"&&(f.exclusiveMinimum=b),typeof h=="number"&&(f.minimum=h,typeof b=="number"&&(b>=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=p;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":{p.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":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=p,{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=p;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=p;f.anyOf=o.options.map((h,y)=>this.process(h,{...d,path:[...d.path,"anyOf",y]}));break}case"intersection":{let f=p,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=p;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=p;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=p,h=Qn(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=p,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=p,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);p.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=p;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,p.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(p._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")}p.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=p,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,p.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"&&we(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 p=`#/${d}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:p+f}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:m,defId:p}=s(l);d.def={...d.schema},p&&(d.defId=p);let f=d.schema;for(let h in f)delete f[h];f.$ref=m};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>
|
|
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>
|
|
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 p=n.external.registry.get(l[0])?.id;if(e!==l[0]&&p){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 m=this.seen.get(l),p=m.def??m.schema,f={...p};if(m.ref===null)return;let h=m.ref;if(m.ref=null,h){a(h,d);let y=this.seen.get(h).schema;y.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(y)):(Object.assign(p,y),Object.assign(p,f))}m.isParent||this.override({zodSchema:l,jsonSchema:p,path:m.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 hm=J(()=>{});var Me=J(()=>{dn();La();Aa();nm();xs();Ja();$t();vs();zs();Mc();Ba();pm();fm();mm();hm()});var Su=J(()=>{Me()});var lo={};Kn(lo,{ZodISODate:()=>vm,ZodISODateTime:()=>_m,ZodISODuration:()=>bm,ZodISOTime:()=>xm,date:()=>Eu,datetime:()=>zu,duration:()=>Pu,time:()=>Tu});function zu(t){return am(_m,t)}function Eu(t){return cm(vm,t)}function Tu(t){return um(xm,t)}function Pu(t){return lm(bm,t)}var _m,vm,xm,bm,Ru=J(()=>{Me();Iu();_m=w("ZodISODateTime",(t,e)=>{Yp.init(t,e),me.init(t,e)});vm=w("ZodISODate",(t,e)=>{Qp.init(t,e),me.init(t,e)});xm=w("ZodISOTime",(t,e)=>{em.init(t,e),me.init(t,e)});bm=w("ZodISODuration",(t,e)=>{tm.init(t,e),me.init(t,e)})});var wm,fA,fo,Ou=J(()=>{Me();Me();wm=(t,e)=>{ys.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Ca(t,r)},flatten:{value:r=>Oa(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},fA=w("ZodError",wm),fo=w("ZodError",wm,{Parent:Error})});var $m,km,Sm,zm,Cu=J(()=>{Me();Ou();$m=Na(fo),km=ja(fo),Sm=Da(fo),zm=qa(fo)});function x(t){return jc(sw,t)}function oe(t){return su(Im,t)}function Tm(t){return iu($w,t)}function ke(t){return au(kw,t)}function Om(t){return cu(Sw,t)}function he(){return uu(zw)}function Tw(t){return lu(Ew,t)}function W(t,e){return dm(Pw,t,e)}function P(t,e){let r={type:"object",get shape(){return K.assignProp(this,"shape",{...t}),this.shape},...K.normalizeParams(e)};return new Cm(r)}function je(t,e){return new Cm({type:"object",get shape(){return K.assignProp(this,"shape",{...t}),this.shape},catchall:he(),...K.normalizeParams(e)})}function de(t,e){return new Am({type:"union",options:t,...K.normalizeParams(e)})}function Mu(t,e,r){return new Rw({type:"union",options:e,discriminator:t,...K.normalizeParams(r)})}function js(t,e){return new Iw({type:"intersection",left:t,right:e})}function le(t,e,r){return new Ow({type:"record",keyType:t,valueType:e,...K.normalizeParams(r)})}function He(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Au({type:"enum",entries:r,...K.normalizeParams(e)})}function O(t,e){return new Cw({type:"literal",values:Array.isArray(t)?t:[t],...K.normalizeParams(e)})}function Nm(t){return new Aw({type:"transform",transform:t})}function ge(t){return new Mm({type:"optional",innerType:t})}function Pm(t){return new Nw({type:"nullable",innerType:t})}function jw(t,e){return new Mw({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Dw(t,e){return new Zw({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function qw(t,e){return new jm({type:"nonoptional",innerType:t,...K.normalizeParams(e)})}function Uw(t,e){return new Lw({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Nu(t,e){return new Fw({type:"pipe",in:t,out:e})}function Vw(t){return new Hw({type:"readonly",innerType:t})}function Bw(t){let e=new ze({check:"custom"});return e._zod.check=t,e}function Dm(t,e){return bu(Zm,t??(()=>!0),e)}function Jw(t,e={}){return wu(Zm,t,e)}function Kw(t){let e=Bw(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(K.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(K.issue(o))}},t(r.value,r)));return e}function ju(t,e){return Nu(Nm(t),e)}var _e,Rm,sw,me,iw,Em,Ms,aw,cw,uw,lw,dw,fw,pw,mw,hw,gw,yw,_w,vw,xw,bw,ww,Im,$w,kw,Sw,zw,Ew,Pw,Cm,Am,Rw,Iw,Ow,Au,Cw,Aw,Mm,Nw,Mw,Zw,jm,Lw,Fw,Hw,Zm,Iu=J(()=>{Me();Me();Su();Ru();Cu();_e=w("ZodType",(t,e)=>(se.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)=>Qe(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>$m(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Sm(t,r,n),t.parseAsync=async(r,n)=>km(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(Jw(r,n)),t.superRefine=r=>t.check(Kw(r)),t.overwrite=r=>t.check(Nr(r)),t.optional=()=>ge(t),t.nullable=()=>Pm(t),t.nullish=()=>ge(Pm(t)),t.nonoptional=r=>qw(t,r),t.array=()=>W(t),t.or=r=>de([t,r]),t.and=r=>js(t,r),t.transform=r=>Nu(t,Nm(r)),t.default=r=>jw(t,r),t.prefault=r=>Dw(t,r),t.catch=r=>Uw(t,r),t.pipe=r=>Nu(t,r),t.readonly=()=>Vw(t),t.describe=r=>{let n=t.clone();return Yt.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Yt.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Yt.get(t);let n=t.clone();return Yt.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Rm=w("_ZodString",(t,e)=>{io.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(du(...n)),t.includes=(...n)=>t.check(mu(...n)),t.startsWith=(...n)=>t.check(hu(...n)),t.endsWith=(...n)=>t.check(gu(...n)),t.min=(...n)=>t.check(mn(...n)),t.max=(...n)=>t.check(Is(...n)),t.length=(...n)=>t.check(Os(...n)),t.nonempty=(...n)=>t.check(mn(1,...n)),t.lowercase=n=>t.check(fu(n)),t.uppercase=n=>t.check(pu(n)),t.trim=()=>t.check(_u()),t.normalize=(...n)=>t.check(yu(...n)),t.toLowerCase=()=>t.check(vu()),t.toUpperCase=()=>t.check(xu())}),sw=w("ZodString",(t,e)=>{io.init(t,e),Rm.init(t,e),t.email=r=>t.check(Zc(iw,r)),t.url=r=>t.check(Fc(aw,r)),t.jwt=r=>t.check(ou(ww,r)),t.emoji=r=>t.check(Hc(cw,r)),t.guid=r=>t.check(Es(Em,r)),t.uuid=r=>t.check(Dc(Ms,r)),t.uuidv4=r=>t.check(qc(Ms,r)),t.uuidv6=r=>t.check(Lc(Ms,r)),t.uuidv7=r=>t.check(Uc(Ms,r)),t.nanoid=r=>t.check(Vc(uw,r)),t.guid=r=>t.check(Es(Em,r)),t.cuid=r=>t.check(Bc(lw,r)),t.cuid2=r=>t.check(Jc(dw,r)),t.ulid=r=>t.check(Kc(fw,r)),t.base64=r=>t.check(tu(vw,r)),t.base64url=r=>t.check(ru(xw,r)),t.xid=r=>t.check(Wc(pw,r)),t.ksuid=r=>t.check(Gc(mw,r)),t.ipv4=r=>t.check(Xc(hw,r)),t.ipv6=r=>t.check(Yc(gw,r)),t.cidrv4=r=>t.check(Qc(yw,r)),t.cidrv6=r=>t.check(eu(_w,r)),t.e164=r=>t.check(nu(bw,r)),t.datetime=r=>t.check(zu(r)),t.date=r=>t.check(Eu(r)),t.time=r=>t.check(Tu(r)),t.duration=r=>t.check(Pu(r))});me=w("ZodStringFormat",(t,e)=>{ue.init(t,e),Rm.init(t,e)}),iw=w("ZodEmail",(t,e)=>{Xa.init(t,e),me.init(t,e)}),Em=w("ZodGUID",(t,e)=>{Wa.init(t,e),me.init(t,e)}),Ms=w("ZodUUID",(t,e)=>{Ga.init(t,e),me.init(t,e)}),aw=w("ZodURL",(t,e)=>{Ya.init(t,e),me.init(t,e)}),cw=w("ZodEmoji",(t,e)=>{Qa.init(t,e),me.init(t,e)}),uw=w("ZodNanoID",(t,e)=>{ec.init(t,e),me.init(t,e)}),lw=w("ZodCUID",(t,e)=>{tc.init(t,e),me.init(t,e)}),dw=w("ZodCUID2",(t,e)=>{rc.init(t,e),me.init(t,e)}),fw=w("ZodULID",(t,e)=>{nc.init(t,e),me.init(t,e)}),pw=w("ZodXID",(t,e)=>{oc.init(t,e),me.init(t,e)}),mw=w("ZodKSUID",(t,e)=>{sc.init(t,e),me.init(t,e)}),hw=w("ZodIPv4",(t,e)=>{ic.init(t,e),me.init(t,e)}),gw=w("ZodIPv6",(t,e)=>{ac.init(t,e),me.init(t,e)}),yw=w("ZodCIDRv4",(t,e)=>{cc.init(t,e),me.init(t,e)}),_w=w("ZodCIDRv6",(t,e)=>{uc.init(t,e),me.init(t,e)}),vw=w("ZodBase64",(t,e)=>{lc.init(t,e),me.init(t,e)}),xw=w("ZodBase64URL",(t,e)=>{dc.init(t,e),me.init(t,e)}),bw=w("ZodE164",(t,e)=>{fc.init(t,e),me.init(t,e)}),ww=w("ZodJWT",(t,e)=>{pc.init(t,e),me.init(t,e)}),Im=w("ZodNumber",(t,e)=>{$s.init(t,e),_e.init(t,e),t.gt=(n,o)=>t.check(Ps(n,o)),t.gte=(n,o)=>t.check(uo(n,o)),t.min=(n,o)=>t.check(uo(n,o)),t.lt=(n,o)=>t.check(Ts(n,o)),t.lte=(n,o)=>t.check(co(n,o)),t.max=(n,o)=>t.check(co(n,o)),t.int=n=>t.check(Tm(n)),t.safe=n=>t.check(Tm(n)),t.positive=n=>t.check(Ps(0,n)),t.nonnegative=n=>t.check(uo(0,n)),t.negative=n=>t.check(Ts(0,n)),t.nonpositive=n=>t.check(co(0,n)),t.multipleOf=(n,o)=>t.check(Rs(n,o)),t.step=(n,o)=>t.check(Rs(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});$w=w("ZodNumberFormat",(t,e)=>{mc.init(t,e),Im.init(t,e)});kw=w("ZodBoolean",(t,e)=>{hc.init(t,e),_e.init(t,e)});Sw=w("ZodNull",(t,e)=>{gc.init(t,e),_e.init(t,e)});zw=w("ZodUnknown",(t,e)=>{yc.init(t,e),_e.init(t,e)});Ew=w("ZodNever",(t,e)=>{_c.init(t,e),_e.init(t,e)});Pw=w("ZodArray",(t,e)=>{vc.init(t,e),_e.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(mn(r,n)),t.nonempty=r=>t.check(mn(1,r)),t.max=(r,n)=>t.check(Is(r,n)),t.length=(r,n)=>t.check(Os(r,n)),t.unwrap=()=>t.element});Cm=w("ZodObject",(t,e)=>{ks.init(t,e),_e.init(t,e),K.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>He(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:he()}),t.loose=()=>t.clone({...t._zod.def,catchall:he()}),t.strict=()=>t.clone({...t._zod.def,catchall:Tw()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>K.extend(t,r),t.merge=r=>K.merge(t,r),t.pick=r=>K.pick(t,r),t.omit=r=>K.omit(t,r),t.partial=(...r)=>K.partial(Mm,t,r[0]),t.required=(...r)=>K.required(jm,t,r[0])});Am=w("ZodUnion",(t,e)=>{Ss.init(t,e),_e.init(t,e),t.options=e.options});Rw=w("ZodDiscriminatedUnion",(t,e)=>{Am.init(t,e),xc.init(t,e)});Iw=w("ZodIntersection",(t,e)=>{bc.init(t,e),_e.init(t,e)});Ow=w("ZodRecord",(t,e)=>{wc.init(t,e),_e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Au=w("ZodEnum",(t,e)=>{$c.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 Au({...e,checks:[],...K.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 Au({...e,checks:[],...K.normalizeParams(o),entries:s})}});Cw=w("ZodLiteral",(t,e)=>{kc.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]}})});Aw=w("ZodTransform",(t,e)=>{Sc.init(t,e),_e.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(K.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(K.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Mm=w("ZodOptional",(t,e)=>{zc.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Nw=w("ZodNullable",(t,e)=>{Ec.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Mw=w("ZodDefault",(t,e)=>{Tc.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});Zw=w("ZodPrefault",(t,e)=>{Pc.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType});jm=w("ZodNonOptional",(t,e)=>{Rc.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Lw=w("ZodCatch",(t,e)=>{Ic.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Fw=w("ZodPipe",(t,e)=>{Oc.init(t,e),_e.init(t,e),t.in=e.in,t.out=e.out});Hw=w("ZodReadonly",(t,e)=>{Cc.init(t,e),_e.init(t,e)});Zm=w("ZodCustom",(t,e)=>{Ac.init(t,e),_e.init(t,e)})});var qm=J(()=>{});var Lm=J(()=>{});var Um=J(()=>{Me();Iu();Su();Ou();Cu();qm();Me();sm();zs();Ru();Lm();Ye(om())});var Fm=J(()=>{Um()});var Hm=J(()=>{Fm()});function sh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function ih(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Du,Vm,_n,tr,Ds,$e,Bm,Jm,TA,Xw,Yw,qu,et,po,Km,Ee,nt,ot,Te,qs,Wm,Zt,Gm,Xm,Lu,Dt,A,Uu,vn,mo,PA,Ls,Qw,Us,e$,ho,yn,Ym,t$,r$,n$,o$,s$,i$,Fs,Fu,a$,c$,Hu,Hs,u$,l$,Vs,d$,go,yo,f$,_o,xn,p$,vo,Bs,Js,Ks,RA,Ws,Gs,Xs,Qm,eh,th,Vu,rh,xo,bn,nh,m$,Ys,h$,Qs,g$,Bu,y$,ei,_$,v$,x$,b$,w$,$$,k$,S$,z$,E$,ti,T$,P$,ri,Ju,Ku,Wu,R$,I$,O$,Gu,C$,A$,N$,M$,j$,oh,ni,Z$,oi,IA,D$,wn,q$,OA,bo,L$,Xu,U$,F$,H$,V$,B$,J$,K$,Zs,W$,G$,X$,wo,Yu,Y$,Q$,ek,tk,rk,nk,ok,sk,ik,ak,ck,uk,lk,dk,fk,pk,mk,hk,$n,gk,yk,_k,si,vk,xk,bk,Qu,wk,CA,AA,NA,MA,jA,ZA,I,Zu,Zr=J(()=>{Hm();Du="2025-11-25",Vm="2025-03-26",_n=[Du,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],tr="io.modelcontextprotocol/related-task",Ds="2.0",$e=Dm(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Bm=de([x(),oe().int()]),Jm=x(),TA=je({ttl:oe().optional(),pollInterval:oe().optional()}),Xw=P({ttl:oe().optional()}),Yw=P({taskId:x()}),qu=je({progressToken:Bm.optional(),[tr]:Yw.optional()}),et=P({_meta:qu.optional()}),po=et.extend({task:Xw.optional()}),Km=t=>po.safeParse(t).success,Ee=P({method:x(),params:et.loose().optional()}),nt=P({_meta:qu.optional()}),ot=P({method:x(),params:nt.loose().optional()}),Te=je({_meta:qu.optional()}),qs=de([x(),oe().int()]),Wm=P({jsonrpc:O(Ds),id:qs,...Ee.shape}).strict(),Zt=t=>Wm.safeParse(t).success,Gm=P({jsonrpc:O(Ds),...ot.shape}).strict(),Xm=t=>Gm.safeParse(t).success,Lu=P({jsonrpc:O(Ds),id:qs,result:Te}).strict(),Dt=t=>Lu.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"})(A||(A={}));Uu=P({jsonrpc:O(Ds),id:qs.optional(),error:P({code:oe().int(),message:x(),data:he().optional()})}).strict(),vn=t=>Uu.safeParse(t).success,mo=de([Wm,Gm,Lu,Uu]),PA=de([Lu,Uu]),Ls=Te.strict(),Qw=nt.extend({requestId:qs.optional(),reason:x().optional()}),Us=ot.extend({method:O("notifications/cancelled"),params:Qw}),e$=P({src:x(),mimeType:x().optional(),sizes:W(x()).optional(),theme:He(["light","dark"]).optional()}),ho=P({icons:W(e$).optional()}),yn=P({name:x(),title:x().optional()}),Ym=yn.extend({...yn.shape,...ho.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),t$=js(P({applyDefaults:ke().optional()}),le(x(),he())),r$=ju(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,js(P({form:t$.optional(),url:$e.optional()}),le(x(),he()).optional())),n$=je({list:$e.optional(),cancel:$e.optional(),requests:je({sampling:je({createMessage:$e.optional()}).optional(),elicitation:je({create:$e.optional()}).optional()}).optional()}),o$=je({list:$e.optional(),cancel:$e.optional(),requests:je({tools:je({call:$e.optional()}).optional()}).optional()}),s$=P({experimental:le(x(),$e).optional(),sampling:P({context:$e.optional(),tools:$e.optional()}).optional(),elicitation:r$.optional(),roots:P({listChanged:ke().optional()}).optional(),tasks:n$.optional(),extensions:le(x(),$e).optional()}),i$=et.extend({protocolVersion:x(),capabilities:s$,clientInfo:Ym}),Fs=Ee.extend({method:O("initialize"),params:i$}),Fu=t=>Fs.safeParse(t).success,a$=P({experimental:le(x(),$e).optional(),logging:$e.optional(),completions:$e.optional(),prompts:P({listChanged:ke().optional()}).optional(),resources:P({subscribe:ke().optional(),listChanged:ke().optional()}).optional(),tools:P({listChanged:ke().optional()}).optional(),tasks:o$.optional(),extensions:le(x(),$e).optional()}),c$=Te.extend({protocolVersion:x(),capabilities:a$,serverInfo:Ym,instructions:x().optional()}),Hu=ot.extend({method:O("notifications/initialized"),params:nt.optional()}),Hs=Ee.extend({method:O("ping"),params:et.optional()}),u$=P({progress:oe(),total:ge(oe()),message:ge(x())}),l$=P({...nt.shape,...u$.shape,progressToken:Bm}),Vs=ot.extend({method:O("notifications/progress"),params:l$}),d$=et.extend({cursor:Jm.optional()}),go=Ee.extend({params:d$.optional()}),yo=Te.extend({nextCursor:Jm.optional()}),f$=He(["working","input_required","completed","failed","cancelled"]),_o=P({taskId:x(),status:f$,ttl:de([oe(),Om()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:ge(oe()),statusMessage:ge(x())}),xn=Te.extend({task:_o}),p$=nt.merge(_o),vo=ot.extend({method:O("notifications/tasks/status"),params:p$}),Bs=Ee.extend({method:O("tasks/get"),params:et.extend({taskId:x()})}),Js=Te.merge(_o),Ks=Ee.extend({method:O("tasks/result"),params:et.extend({taskId:x()})}),RA=Te.loose(),Ws=go.extend({method:O("tasks/list")}),Gs=yo.extend({tasks:W(_o)}),Xs=Ee.extend({method:O("tasks/cancel"),params:et.extend({taskId:x()})}),Qm=Te.merge(_o),eh=P({uri:x(),mimeType:ge(x()),_meta:le(x(),he()).optional()}),th=eh.extend({text:x()}),Vu=x().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),rh=eh.extend({blob:Vu}),xo=He(["user","assistant"]),bn=P({audience:W(xo).optional(),priority:oe().min(0).max(1).optional(),lastModified:lo.datetime({offset:!0}).optional()}),nh=P({...yn.shape,...ho.shape,uri:x(),description:ge(x()),mimeType:ge(x()),size:ge(oe()),annotations:bn.optional(),_meta:ge(je({}))}),m$=P({...yn.shape,...ho.shape,uriTemplate:x(),description:ge(x()),mimeType:ge(x()),annotations:bn.optional(),_meta:ge(je({}))}),Ys=go.extend({method:O("resources/list")}),h$=yo.extend({resources:W(nh)}),Qs=go.extend({method:O("resources/templates/list")}),g$=yo.extend({resourceTemplates:W(m$)}),Bu=et.extend({uri:x()}),y$=Bu,ei=Ee.extend({method:O("resources/read"),params:y$}),_$=Te.extend({contents:W(de([th,rh]))}),v$=ot.extend({method:O("notifications/resources/list_changed"),params:nt.optional()}),x$=Bu,b$=Ee.extend({method:O("resources/subscribe"),params:x$}),w$=Bu,$$=Ee.extend({method:O("resources/unsubscribe"),params:w$}),k$=nt.extend({uri:x()}),S$=ot.extend({method:O("notifications/resources/updated"),params:k$}),z$=P({name:x(),description:ge(x()),required:ge(ke())}),E$=P({...yn.shape,...ho.shape,description:ge(x()),arguments:ge(W(z$)),_meta:ge(je({}))}),ti=go.extend({method:O("prompts/list")}),T$=yo.extend({prompts:W(E$)}),P$=et.extend({name:x(),arguments:le(x(),x()).optional()}),ri=Ee.extend({method:O("prompts/get"),params:P$}),Ju=P({type:O("text"),text:x(),annotations:bn.optional(),_meta:le(x(),he()).optional()}),Ku=P({type:O("image"),data:Vu,mimeType:x(),annotations:bn.optional(),_meta:le(x(),he()).optional()}),Wu=P({type:O("audio"),data:Vu,mimeType:x(),annotations:bn.optional(),_meta:le(x(),he()).optional()}),R$=P({type:O("tool_use"),name:x(),id:x(),input:le(x(),he()),_meta:le(x(),he()).optional()}),I$=P({type:O("resource"),resource:de([th,rh]),annotations:bn.optional(),_meta:le(x(),he()).optional()}),O$=nh.extend({type:O("resource_link")}),Gu=de([Ju,Ku,Wu,O$,I$]),C$=P({role:xo,content:Gu}),A$=Te.extend({description:x().optional(),messages:W(C$)}),N$=ot.extend({method:O("notifications/prompts/list_changed"),params:nt.optional()}),M$=P({title:x().optional(),readOnlyHint:ke().optional(),destructiveHint:ke().optional(),idempotentHint:ke().optional(),openWorldHint:ke().optional()}),j$=P({taskSupport:He(["required","optional","forbidden"]).optional()}),oh=P({...yn.shape,...ho.shape,description:x().optional(),inputSchema:P({type:O("object"),properties:le(x(),$e).optional(),required:W(x()).optional()}).catchall(he()),outputSchema:P({type:O("object"),properties:le(x(),$e).optional(),required:W(x()).optional()}).catchall(he()).optional(),annotations:M$.optional(),execution:j$.optional(),_meta:le(x(),he()).optional()}),ni=go.extend({method:O("tools/list")}),Z$=yo.extend({tools:W(oh)}),oi=Te.extend({content:W(Gu).default([]),structuredContent:le(x(),he()).optional(),isError:ke().optional()}),IA=oi.or(Te.extend({toolResult:he()})),D$=po.extend({name:x(),arguments:le(x(),he()).optional()}),wn=Ee.extend({method:O("tools/call"),params:D$}),q$=ot.extend({method:O("notifications/tools/list_changed"),params:nt.optional()}),OA=P({autoRefresh:ke().default(!0),debounceMs:oe().int().nonnegative().default(300)}),bo=He(["debug","info","notice","warning","error","critical","alert","emergency"]),L$=et.extend({level:bo}),Xu=Ee.extend({method:O("logging/setLevel"),params:L$}),U$=nt.extend({level:bo,logger:x().optional(),data:he()}),F$=ot.extend({method:O("notifications/message"),params:U$}),H$=P({name:x().optional()}),V$=P({hints:W(H$).optional(),costPriority:oe().min(0).max(1).optional(),speedPriority:oe().min(0).max(1).optional(),intelligencePriority:oe().min(0).max(1).optional()}),B$=P({mode:He(["auto","required","none"]).optional()}),J$=P({type:O("tool_result"),toolUseId:x().describe("The unique identifier for the corresponding tool call."),content:W(Gu).default([]),structuredContent:P({}).loose().optional(),isError:ke().optional(),_meta:le(x(),he()).optional()}),K$=Mu("type",[Ju,Ku,Wu]),Zs=Mu("type",[Ju,Ku,Wu,R$,J$]),W$=P({role:xo,content:de([Zs,W(Zs)]),_meta:le(x(),he()).optional()}),G$=po.extend({messages:W(W$),modelPreferences:V$.optional(),systemPrompt:x().optional(),includeContext:He(["none","thisServer","allServers"]).optional(),temperature:oe().optional(),maxTokens:oe().int(),stopSequences:W(x()).optional(),metadata:$e.optional(),tools:W(oh).optional(),toolChoice:B$.optional()}),X$=Ee.extend({method:O("sampling/createMessage"),params:G$}),wo=Te.extend({model:x(),stopReason:ge(He(["endTurn","stopSequence","maxTokens"]).or(x())),role:xo,content:K$}),Yu=Te.extend({model:x(),stopReason:ge(He(["endTurn","stopSequence","maxTokens","toolUse"]).or(x())),role:xo,content:de([Zs,W(Zs)])}),Y$=P({type:O("boolean"),title:x().optional(),description:x().optional(),default:ke().optional()}),Q$=P({type:O("string"),title:x().optional(),description:x().optional(),minLength:oe().optional(),maxLength:oe().optional(),format:He(["email","uri","date","date-time"]).optional(),default:x().optional()}),ek=P({type:He(["number","integer"]),title:x().optional(),description:x().optional(),minimum:oe().optional(),maximum:oe().optional(),default:oe().optional()}),tk=P({type:O("string"),title:x().optional(),description:x().optional(),enum:W(x()),default:x().optional()}),rk=P({type:O("string"),title:x().optional(),description:x().optional(),oneOf:W(P({const:x(),title:x()})),default:x().optional()}),nk=P({type:O("string"),title:x().optional(),description:x().optional(),enum:W(x()),enumNames:W(x()).optional(),default:x().optional()}),ok=de([tk,rk]),sk=P({type:O("array"),title:x().optional(),description:x().optional(),minItems:oe().optional(),maxItems:oe().optional(),items:P({type:O("string"),enum:W(x())}),default:W(x()).optional()}),ik=P({type:O("array"),title:x().optional(),description:x().optional(),minItems:oe().optional(),maxItems:oe().optional(),items:P({anyOf:W(P({const:x(),title:x()}))}),default:W(x()).optional()}),ak=de([sk,ik]),ck=de([nk,ok,ak]),uk=de([ck,Y$,Q$,ek]),lk=po.extend({mode:O("form").optional(),message:x(),requestedSchema:P({type:O("object"),properties:le(x(),uk),required:W(x()).optional()})}),dk=po.extend({mode:O("url"),message:x(),elicitationId:x(),url:x().url()}),fk=de([lk,dk]),pk=Ee.extend({method:O("elicitation/create"),params:fk}),mk=nt.extend({elicitationId:x()}),hk=ot.extend({method:O("notifications/elicitation/complete"),params:mk}),$n=Te.extend({action:He(["accept","decline","cancel"]),content:ju(t=>t===null?void 0:t,le(x(),de([x(),oe(),ke(),W(x())])).optional())}),gk=P({type:O("ref/resource"),uri:x()}),yk=P({type:O("ref/prompt"),name:x()}),_k=et.extend({ref:de([yk,gk]),argument:P({name:x(),value:x()}),context:P({arguments:le(x(),x()).optional()}).optional()}),si=Ee.extend({method:O("completion/complete"),params:_k});vk=Te.extend({completion:je({values:W(x()).max(100),total:ge(oe().int()),hasMore:ge(ke())})}),xk=P({uri:x().startsWith("file://"),name:x().optional(),_meta:le(x(),he()).optional()}),bk=Ee.extend({method:O("roots/list"),params:et.optional()}),Qu=Te.extend({roots:W(xk)}),wk=ot.extend({method:O("notifications/roots/list_changed"),params:nt.optional()}),CA=de([Hs,Fs,si,Xu,ri,ti,Ys,Qs,ei,b$,$$,wn,ni,Bs,Ks,Ws,Xs]),AA=de([Us,Vs,Hu,wk,vo]),NA=de([Ls,wo,Yu,$n,Qu,Js,Gs,xn]),MA=de([Hs,X$,pk,bk,Bs,Ks,Ws,Xs]),jA=de([Us,Vs,F$,S$,v$,q$,N$,vo,hk]),ZA=de([Ls,c$,vk,A$,T$,h$,g$,_$,oi,Z$,Js,Gs,xn]),I=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===A.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Zu(o.elicitations,r)}return new t(e,r,n)}},Zu=class extends I{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(A.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var zo=E(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.regexpCode=ne.getEsmExportName=ne.getProperty=ne.safeStringify=ne.stringify=ne.strConcat=ne.addCodeArg=ne.str=ne._=ne.nil=ne._Code=ne.Name=ne.IDENTIFIER=ne._CodeOrName=void 0;var ko=class{};ne._CodeOrName=ko;ne.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Dr=class extends ko{constructor(e){if(super(),!ne.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}}};ne.Name=Dr;var st=class extends ko{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 Dr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ne._Code=st;ne.nil=new st("");function Lh(t,...e){let r=[t[0]],n=0;for(;n<e.length;)ul(r,e[n]),r.push(t[++n]);return new st(r)}ne._=Lh;var cl=new st("+");function Uh(t,...e){let r=[So(t[0])],n=0;for(;n<e.length;)r.push(cl),ul(r,e[n]),r.push(cl,So(t[++n]));return Ck(r),new st(r)}ne.str=Uh;function ul(t,e){e instanceof st?t.push(...e._items):e instanceof Dr?t.push(e):t.push(Mk(e))}ne.addCodeArg=ul;function Ck(t){let e=1;for(;e<t.length-1;){if(t[e]===cl){let r=Ak(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Ak(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Dr||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 Dr))return`"${t}${e.slice(1)}`}function Nk(t,e){return e.emptyStr()?t:t.emptyStr()?e:Uh`${t}${e}`}ne.strConcat=Nk;function Mk(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:So(Array.isArray(t)?t.join(","):t)}function jk(t){return new st(So(t))}ne.stringify=jk;function So(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ne.safeStringify=So;function Zk(t){return typeof t=="string"&&ne.IDENTIFIER.test(t)?new st(`.${t}`):Lh`[${t}]`}ne.getProperty=Zk;function Dk(t){if(typeof t=="string"&&ne.IDENTIFIER.test(t))return new st(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ne.getEsmExportName=Dk;function qk(t){return new st(t.toString())}ne.regexpCode=qk});var fl=E(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.ValueScope=Be.ValueScopeName=Be.Scope=Be.varKinds=Be.UsedValueState=void 0;var Ve=zo(),ll=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},di;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(di||(Be.UsedValueState=di={}));Be.varKinds={const:new Ve.Name("const"),let:new Ve.Name("let"),var:new Ve.Name("var")};var fi=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ve.Name?e:this.name(e)}name(e){return new Ve.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}}};Be.Scope=fi;var pi=class extends Ve.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ve._)`.${new Ve.Name(r)}[${n}]`}};Be.ValueScopeName=pi;var Lk=(0,Ve._)`\n`,dl=class extends fi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Lk:Ve.nil}}get(){return this._scope}name(e){return new pi(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,Ve._)`${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=Ve.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,di.Started);let l=r(u);if(l){let d=this.opts.es5?Be.varKinds.var:Be.varKinds.const;s=(0,Ve._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ve._)`${s}${l}${this.opts._n}`;else throw new ll(u);c.set(u,di.Completed)})}return s}};Be.ValueScope=dl});var F=E(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.or=H.and=H.not=H.CodeGen=H.operators=H.varKinds=H.ValueScopeName=H.ValueScope=H.Scope=H.Name=H.regexpCode=H.stringify=H.getProperty=H.nil=H.strConcat=H.str=H._=void 0;var X=zo(),mt=fl(),nr=zo();Object.defineProperty(H,"_",{enumerable:!0,get:function(){return nr._}});Object.defineProperty(H,"str",{enumerable:!0,get:function(){return nr.str}});Object.defineProperty(H,"strConcat",{enumerable:!0,get:function(){return nr.strConcat}});Object.defineProperty(H,"nil",{enumerable:!0,get:function(){return nr.nil}});Object.defineProperty(H,"getProperty",{enumerable:!0,get:function(){return nr.getProperty}});Object.defineProperty(H,"stringify",{enumerable:!0,get:function(){return nr.stringify}});Object.defineProperty(H,"regexpCode",{enumerable:!0,get:function(){return nr.regexpCode}});Object.defineProperty(H,"Name",{enumerable:!0,get:function(){return nr.Name}});var yi=fl();Object.defineProperty(H,"Scope",{enumerable:!0,get:function(){return yi.Scope}});Object.defineProperty(H,"ValueScope",{enumerable:!0,get:function(){return yi.ValueScope}});Object.defineProperty(H,"ValueScopeName",{enumerable:!0,get:function(){return yi.ValueScopeName}});Object.defineProperty(H,"varKinds",{enumerable:!0,get:function(){return yi.varKinds}});H.operators={GT:new X._Code(">"),GTE:new X._Code(">="),LT:new X._Code("<"),LTE:new X._Code("<="),EQ:new X._Code("==="),NEQ:new X._Code("!=="),NOT:new X._Code("!"),OR:new X._Code("||"),AND:new X._Code("&&"),ADD:new X._Code("+")};var qt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},pl=class extends qt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?mt.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=Sn(this.rhs,e,r)),this}get names(){return this.rhs instanceof X._CodeOrName?this.rhs.names:{}}},mi=class extends qt{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 X.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Sn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof X.Name?{}:{...this.lhs.names};return gi(e,this.rhs)}},ml=class extends mi{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},hl=class extends qt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},gl=class extends qt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},yl=class extends qt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},_l=class extends qt{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=Sn(this.code,e,r),this}get names(){return this.code instanceof X._CodeOrName?this.code.names:{}}},Eo=class extends qt{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)||(Uk(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ur(e,r.names),{})}},Lt=class extends Eo{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},vl=class extends Eo{},kn=class extends Lt{};kn.kind="else";var qr=class t extends Lt{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 kn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Fh(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=Sn(this.condition,e,r),this}get names(){let e=super.names;return gi(e,this.condition),this.else&&Ur(e,this.else.names),e}};qr.kind="if";var Lr=class extends Lt{};Lr.kind="for";var xl=class extends Lr{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=Sn(this.iteration,e,r),this}get names(){return Ur(super.names,this.iteration.names)}},bl=class extends Lr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?mt.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=gi(super.names,this.from);return gi(e,this.to)}},hi=class extends Lr{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=Sn(this.iterable,e,r),this}get names(){return Ur(super.names,this.iterable.names)}},To=class extends Lt{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)}};To.kind="func";var Po=class extends Eo{render(e){return"return "+super.render(e)}};Po.kind="return";var wl=class extends Lt{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&&Ur(e,this.catch.names),this.finally&&Ur(e,this.finally.names),e}},Ro=class extends Lt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ro.kind="catch";var Io=class extends Lt{render(e){return"finally"+super.render(e)}};Io.kind="finally";var $l=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
31
|
-
`:""},this._extScope=e,this._scope=new mt.Scope({parent:e}),this._nodes=[new vl]}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 pl(e,s,n)),s}const(e,r,n){return this._def(mt.varKinds.const,e,r,n)}let(e,r,n){return this._def(mt.varKinds.let,e,r,n)}var(e,r,n){return this._def(mt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new mi(e,r,n))}add(e,r){return this._leafNode(new ml(e,H.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==X.nil&&this._leafNode(new _l(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,X.addCodeArg)(r,o));return r.push("}"),new X._Code(r)}if(e,r,n){if(this._blockNode(new qr(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 qr(e))}else(){return this._elseNode(new kn)}endIf(){return this._endBlockNode(qr,kn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new xl(e),r)}forRange(e,r,n,o,s=this.opts.es5?mt.varKinds.var:mt.varKinds.let){let i=this._scope.toName(e);return this._for(new bl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=mt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof X.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,X._)`${i}.length`,a=>{this.var(s,(0,X._)`${i}[${a}]`),n(s)})}return this._for(new hi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?mt.varKinds.var:mt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,X._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new hi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Lr)}label(e){return this._leafNode(new hl(e))}break(e){return this._leafNode(new gl(e))}return(e){let r=new Po;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Po)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new wl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Ro(s),r(s)}return n&&(this._currNode=o.finally=new Io,this.code(n)),this._endBlockNode(Ro,Io)}throw(e){return this._leafNode(new yl(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=X.nil,n,o){return this._blockNode(new To(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(To)}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 qr))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}};H.CodeGen=$l;function Ur(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function gi(t,e){return e instanceof X._CodeOrName?Ur(t,e.names):t}function Sn(t,e,r){if(t instanceof X.Name)return n(t);if(!o(t))return t;return new X._Code(t._items.reduce((s,i)=>(i instanceof X.Name&&(i=n(i)),i instanceof X._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 X._Code&&s._items.some(i=>i instanceof X.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Uk(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Fh(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,X._)`!${kl(t)}`}H.not=Fh;var Fk=Hh(H.operators.AND);function Hk(...t){return t.reduce(Fk)}H.and=Hk;var Vk=Hh(H.operators.OR);function Bk(...t){return t.reduce(Vk)}H.or=Bk;function Hh(t){return(e,r)=>e===X.nil?r:r===X.nil?e:(0,X._)`${kl(e)} ${t} ${kl(r)}`}function kl(t){return t instanceof X.Name?t:(0,X._)`(${t})`}});var Q=E(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.checkStrictMode=V.getErrorPath=V.Type=V.useFunc=V.setEvaluated=V.evaluatedPropsToName=V.mergeEvaluated=V.eachItem=V.unescapeJsonPointer=V.escapeJsonPointer=V.escapeFragment=V.unescapeFragment=V.schemaRefOrVal=V.schemaHasRulesButRef=V.schemaHasRules=V.checkUnknownRules=V.alwaysValidSchema=V.toHash=void 0;var ae=F(),Jk=zo();function Kk(t){let e={};for(let r of t)e[r]=!0;return e}V.toHash=Kk;function Wk(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Jh(t,e),!Kh(e,t.self.RULES.all))}V.alwaysValidSchema=Wk;function Jh(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]||Xh(t,`unknown keyword: "${s}"`)}V.checkUnknownRules=Jh;function Kh(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}V.schemaHasRules=Kh;function Gk(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}V.schemaHasRulesButRef=Gk;function Xk({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ae._)`${r}`}return(0,ae._)`${t}${e}${(0,ae.getProperty)(n)}`}V.schemaRefOrVal=Xk;function Yk(t){return Wh(decodeURIComponent(t))}V.unescapeFragment=Yk;function Qk(t){return encodeURIComponent(zl(t))}V.escapeFragment=Qk;function zl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}V.escapeJsonPointer=zl;function Wh(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}V.unescapeJsonPointer=Wh;function eS(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}V.eachItem=eS;function Vh({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof ae.Name?(s instanceof ae.Name?t(o,s,i):e(o,s,i),i):s instanceof ae.Name?(e(o,i,s),s):r(s,i);return a===ae.Name&&!(c instanceof ae.Name)?n(o,c):c}}V.mergeEvaluated={props:Vh({mergeNames:(t,e,r)=>t.if((0,ae._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ae._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ae._)`${r} || {}`).code((0,ae._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ae._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ae._)`${r} || {}`),El(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Gh}),items:Vh({mergeNames:(t,e,r)=>t.if((0,ae._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ae._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ae._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ae._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Gh(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ae._)`{}`);return e!==void 0&&El(t,r,e),r}V.evaluatedPropsToName=Gh;function El(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ae._)`${e}${(0,ae.getProperty)(n)}`,!0))}V.setEvaluated=El;var Bh={};function tS(t,e){return t.scopeValue("func",{ref:e,code:Bh[e.code]||(Bh[e.code]=new Jk._Code(e.code))})}V.useFunc=tS;var Sl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Sl||(V.Type=Sl={}));function rS(t,e,r){if(t instanceof ae.Name){let n=e===Sl.Num;return r?n?(0,ae._)`"[" + ${t} + "]"`:(0,ae._)`"['" + ${t} + "']"`:n?(0,ae._)`"/" + ${t}`:(0,ae._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ae.getProperty)(t).toString():"/"+zl(t)}V.getErrorPath=rS;function Xh(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}V.checkStrictMode=Xh});var Ut=E(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});var Oe=F(),nS={data:new Oe.Name("data"),valCxt:new Oe.Name("valCxt"),instancePath:new Oe.Name("instancePath"),parentData:new Oe.Name("parentData"),parentDataProperty:new Oe.Name("parentDataProperty"),rootData:new Oe.Name("rootData"),dynamicAnchors:new Oe.Name("dynamicAnchors"),vErrors:new Oe.Name("vErrors"),errors:new Oe.Name("errors"),this:new Oe.Name("this"),self:new Oe.Name("self"),scope:new Oe.Name("scope"),json:new Oe.Name("json"),jsonPos:new Oe.Name("jsonPos"),jsonLen:new Oe.Name("jsonLen"),jsonPart:new Oe.Name("jsonPart")};Tl.default=nS});var Oo=E(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.extendErrors=Ce.resetErrorsCount=Ce.reportExtraError=Ce.reportError=Ce.keyword$DataError=Ce.keywordError=void 0;var ee=F(),_i=Q(),De=Ut();Ce.keywordError={message:({keyword:t})=>(0,ee.str)`must pass "${t}" keyword validation`};Ce.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ee.str)`"${t}" keyword must be ${e} ($data)`:(0,ee.str)`"${t}" keyword is invalid ($data)`};function oS(t,e=Ce.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=eg(t,e,r);n??(i||a)?Yh(s,c):Qh(o,(0,ee._)`[${c}]`)}Ce.reportError=oS;function sS(t,e=Ce.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=eg(t,e,r);Yh(o,a),s||i||Qh(n,De.default.vErrors)}Ce.reportExtraError=sS;function iS(t,e){t.assign(De.default.errors,e),t.if((0,ee._)`${De.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ee._)`${De.default.vErrors}.length`,e),()=>t.assign(De.default.vErrors,null)))}Ce.resetErrorsCount=iS;function aS({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,De.default.errors,a=>{t.const(i,(0,ee._)`${De.default.vErrors}[${a}]`),t.if((0,ee._)`${i}.instancePath === undefined`,()=>t.assign((0,ee._)`${i}.instancePath`,(0,ee.strConcat)(De.default.instancePath,s.errorPath))),t.assign((0,ee._)`${i}.schemaPath`,(0,ee.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ee._)`${i}.schema`,r),t.assign((0,ee._)`${i}.data`,n))})}Ce.extendErrors=aS;function Yh(t,e){let r=t.const("err",e);t.if((0,ee._)`${De.default.vErrors} === null`,()=>t.assign(De.default.vErrors,(0,ee._)`[${r}]`),(0,ee._)`${De.default.vErrors}.push(${r})`),t.code((0,ee._)`${De.default.errors}++`)}function Qh(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ee._)`new ${t.ValidationError}(${e})`):(r.assign((0,ee._)`${n}.errors`,e),r.return(!1))}var Fr={keyword:new ee.Name("keyword"),schemaPath:new ee.Name("schemaPath"),params:new ee.Name("params"),propertyName:new ee.Name("propertyName"),message:new ee.Name("message"),schema:new ee.Name("schema"),parentSchema:new ee.Name("parentSchema")};function eg(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ee._)`{}`:cS(t,e,r)}function cS(t,e,r={}){let{gen:n,it:o}=t,s=[uS(o,r),lS(t,r)];return dS(t,e,s),n.object(...s)}function uS({errorPath:t},{instancePath:e}){let r=e?(0,ee.str)`${t}${(0,_i.getErrorPath)(e,_i.Type.Str)}`:t;return[De.default.instancePath,(0,ee.strConcat)(De.default.instancePath,r)]}function lS({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ee.str)`${e}/${t}`;return r&&(o=(0,ee.str)`${o}${(0,_i.getErrorPath)(r,_i.Type.Str)}`),[Fr.schemaPath,o]}function dS(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([Fr.keyword,o],[Fr.params,typeof e=="function"?e(t):e||(0,ee._)`{}`]),c.messages&&n.push([Fr.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Fr.schema,i],[Fr.parentSchema,(0,ee._)`${l}${d}`],[De.default.data,s]),u&&n.push([Fr.propertyName,u])}});var rg=E(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.boolOrEmptySchema=zn.topBoolOrEmptySchema=void 0;var fS=Oo(),pS=F(),mS=Ut(),hS={message:"boolean schema is false"};function gS(t){let{gen:e,schema:r,validateName:n}=t;r===!1?tg(t,!1):typeof r=="object"&&r.$async===!0?e.return(mS.default.data):(e.assign((0,pS._)`${n}.errors`,null),e.return(!0))}zn.topBoolOrEmptySchema=gS;function yS(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),tg(t)):r.var(e,!0)}zn.boolOrEmptySchema=yS;function tg(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,fS.reportError)(o,hS,void 0,e)}});var Pl=E(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.getRules=En.isJSONType=void 0;var _S=["string","number","integer","boolean","null","object","array"],vS=new Set(_S);function xS(t){return typeof t=="string"&&vS.has(t)}En.isJSONType=xS;function bS(){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:{}}}En.getRules=bS});var Rl=E(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.shouldUseRule=or.shouldUseGroup=or.schemaHasRulesForType=void 0;function wS({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&ng(t,n)}or.schemaHasRulesForType=wS;function ng(t,e){return e.rules.some(r=>og(t,r))}or.shouldUseGroup=ng;function og(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))}or.shouldUseRule=og});var Co=E(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.reportTypeError=Ae.checkDataTypes=Ae.checkDataType=Ae.coerceAndCheckDataType=Ae.getJSONTypes=Ae.getSchemaTypes=Ae.DataType=void 0;var $S=Pl(),kS=Rl(),SS=Oo(),q=F(),sg=Q(),Tn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Tn||(Ae.DataType=Tn={}));function zS(t){let e=ig(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}Ae.getSchemaTypes=zS;function ig(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every($S.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ae.getJSONTypes=ig;function ES(t,e){let{gen:r,data:n,opts:o}=t,s=TS(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,kS.schemaHasRulesForType)(t,e[0]));if(i){let a=Ol(e,n,o.strictNumbers,Tn.Wrong);r.if(a,()=>{s.length?PS(t,e,s):Cl(t)})}return i}Ae.coerceAndCheckDataType=ES;var ag=new Set(["string","number","integer","boolean","null"]);function TS(t,e){return e?t.filter(r=>ag.has(r)||e==="array"&&r==="array"):[]}function PS(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,q._)`typeof ${o}`),a=n.let("coerced",(0,q._)`undefined`);s.coerceTypes==="array"&&n.if((0,q._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,q._)`${o}[0]`).assign(i,(0,q._)`typeof ${o}`).if(Ol(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(ag.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Cl(t),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),RS(t,a)});function c(u){switch(u){case"string":n.elseIf((0,q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,q._)`"" + ${o}`).elseIf((0,q._)`${o} === null`).assign(a,(0,q._)`""`);return;case"number":n.elseIf((0,q._)`${i} == "boolean" || ${o} === null
|
|
32
|
-
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,
|
|
33
|
-
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,
|
|
34
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function RS({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,q._)`${e} !== undefined`,()=>t.assign((0,q._)`${e}[${r}]`,n))}function Il(t,e,r,n=Tn.Correct){let o=n===Tn.Correct?q.operators.EQ:q.operators.NEQ,s;switch(t){case"null":return(0,q._)`${e} ${o} null`;case"array":s=(0,q._)`Array.isArray(${e})`;break;case"object":s=(0,q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,q._)`typeof ${e} ${o} ${t}`}return n===Tn.Correct?s:(0,q.not)(s);function i(a=q.nil){return(0,q.and)((0,q._)`typeof ${e} == "number"`,a,r?(0,q._)`isFinite(${e})`:q.nil)}}Ae.checkDataType=Il;function Ol(t,e,r,n){if(t.length===1)return Il(t[0],e,r,n);let o,s=(0,sg.toHash)(t);if(s.array&&s.object){let i=(0,q._)`typeof ${e} != "object"`;o=s.null?i:(0,q._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=q.nil;s.number&&delete s.integer;for(let i in s)o=(0,q.and)(o,Il(i,e,r,n));return o}Ae.checkDataTypes=Ol;var IS={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,q._)`{type: ${t}}`:(0,q._)`{type: ${e}}`};function Cl(t){let e=OS(t);(0,SS.reportError)(e,IS)}Ae.reportTypeError=Cl;function OS(t){let{gen:e,data:r,schema:n}=t,o=(0,sg.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var ug=E(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.assignDefaults=void 0;var Pn=F(),CS=Q();function AS(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)cg(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>cg(t,s,o.default))}vi.assignDefaults=AS;function cg(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Pn._)`${s}${(0,Pn.getProperty)(e)}`;if(o){(0,CS.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Pn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Pn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Pn._)`${a} = ${(0,Pn.stringify)(r)}`)}});var it=E(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.validateUnion=ie.validateArray=ie.usePattern=ie.callValidateCode=ie.schemaProperties=ie.allSchemaProperties=ie.noPropertyInData=ie.propertyInData=ie.isOwnProperty=ie.hasPropFunc=ie.reportMissingProp=ie.checkMissingProp=ie.checkReportMissingProp=void 0;var fe=F(),Al=Q(),sr=Ut(),NS=Q();function MS(t,e){let{gen:r,data:n,it:o}=t;r.if(Ml(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,fe._)`${e}`},!0),t.error()})}ie.checkReportMissingProp=MS;function jS({gen:t,data:e,it:{opts:r}},n,o){return(0,fe.or)(...n.map(s=>(0,fe.and)(Ml(t,e,s,r.ownProperties),(0,fe._)`${o} = ${s}`)))}ie.checkMissingProp=jS;function ZS(t,e){t.setParams({missingProperty:e},!0),t.error()}ie.reportMissingProp=ZS;function lg(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,fe._)`Object.prototype.hasOwnProperty`})}ie.hasPropFunc=lg;function Nl(t,e,r){return(0,fe._)`${lg(t)}.call(${e}, ${r})`}ie.isOwnProperty=Nl;function DS(t,e,r,n){let o=(0,fe._)`${e}${(0,fe.getProperty)(r)} !== undefined`;return n?(0,fe._)`${o} && ${Nl(t,e,r)}`:o}ie.propertyInData=DS;function Ml(t,e,r,n){let o=(0,fe._)`${e}${(0,fe.getProperty)(r)} === undefined`;return n?(0,fe.or)(o,(0,fe.not)(Nl(t,e,r))):o}ie.noPropertyInData=Ml;function dg(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ie.allSchemaProperties=dg;function qS(t,e){return dg(e).filter(r=>!(0,Al.alwaysValidSchema)(t,e[r]))}ie.schemaProperties=qS;function LS({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,fe._)`${t}, ${e}, ${n}${o}`:e,d=[[sr.default.instancePath,(0,fe.strConcat)(sr.default.instancePath,s)],[sr.default.parentData,i.parentData],[sr.default.parentDataProperty,i.parentDataProperty],[sr.default.rootData,sr.default.rootData]];i.opts.dynamicRef&&d.push([sr.default.dynamicAnchors,sr.default.dynamicAnchors]);let m=(0,fe._)`${l}, ${r.object(...d)}`;return c!==fe.nil?(0,fe._)`${a}.call(${c}, ${m})`:(0,fe._)`${a}(${m})`}ie.callValidateCode=LS;var US=(0,fe._)`new RegExp`;function FS({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,fe._)`${o.code==="new RegExp"?US:(0,NS.useFunc)(t,o)}(${r}, ${n})`})}ie.usePattern=FS;function HS(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,fe._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Al.Type.Num},s),e.if((0,fe.not)(s),a)})}}ie.validateArray=HS;function VS(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,Al.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,fe._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,fe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ie.validateUnion=VS});var mg=E(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.validateKeywordUsage=St.validSchemaType=St.funcKeywordCode=St.macroKeywordCode=void 0;var qe=F(),Hr=Ut(),BS=it(),JS=Oo();function KS(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=pg(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:qe.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}St.macroKeywordCode=KS;function WS(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;XS(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=pg(n,o,u),d=n.let("valid");t.block$data(d,m),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function m(){if(e.errors===!1)h(),e.modifying&&fg(t),y(()=>t.error());else{let _=e.async?p():f();e.modifying&&fg(t),y(()=>GS(t,_))}}function p(){let _=n.let("ruleErrs",null);return n.try(()=>h((0,qe._)`await `),v=>n.assign(d,!1).if((0,qe._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,qe._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,qe._)`${l}.errors`;return n.assign(_,null),h(qe.nil),_}function h(_=e.async?(0,qe._)`await `:qe.nil){let v=c.opts.passContext?Hr.default.this:Hr.default.self,g=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,qe._)`${_}${(0,BS.callValidateCode)(t,l,v,g)}`,e.modifying)}function y(_){var v;n.if((0,qe.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}St.funcKeywordCode=WS;function fg(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,qe._)`${n.parentData}[${n.parentDataProperty}]`))}function GS(t,e){let{gen:r}=t;r.if((0,qe._)`Array.isArray(${e})`,()=>{r.assign(Hr.default.vErrors,(0,qe._)`${Hr.default.vErrors} === null ? ${e} : ${Hr.default.vErrors}.concat(${e})`).assign(Hr.default.errors,(0,qe._)`${Hr.default.vErrors}.length`),(0,JS.extendErrors)(t)},()=>t.error())}function XS({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function pg(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,qe.stringify)(r)})}function YS(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")}St.validSchemaType=YS;function QS({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)}}St.validateKeywordUsage=QS});var gg=E(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.extendSubschemaMode=ir.extendSubschemaData=ir.getSubschema=void 0;var zt=F(),hg=Q();function ez(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,zt._)`${t.schemaPath}${(0,zt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,zt._)`${t.schemaPath}${(0,zt.getProperty)(e)}${(0,zt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,hg.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')}ir.getSubschema=ez;function tz(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,m=a.let("data",(0,zt._)`${e.data}${(0,zt.getProperty)(r)}`,!0);c(m),t.errorPath=(0,zt.str)`${u}${(0,hg.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,zt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof zt.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]}}ir.extendSubschemaData=tz;function rz(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}ir.extendSubschemaMode=rz});var jl=E((eZ,yg)=>{"use strict";yg.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 vg=E((tZ,_g)=>{"use strict";var ar=_g.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(){};xi(e,n,o,t,"",t)};ar.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ar.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ar.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ar.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 xi(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 ar.arrayKeywords)for(var m=0;m<d.length;m++)xi(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in ar.propsKeywords){if(d&&typeof d=="object")for(var p in d)xi(t,e,r,d[p],o+"/"+l+"/"+nz(p),s,o,l,n,p)}else(l in ar.keywords||t.allKeys&&!(l in ar.skipKeywords))&&xi(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function nz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ao=E(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.getSchemaRefs=Je.resolveUrl=Je.normalizeId=Je._getFullPath=Je.getFullPath=Je.inlineRef=void 0;var oz=Q(),sz=jl(),iz=vg(),az=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function cz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Zl(t):e?xg(t)<=e:!1}Je.inlineRef=cz;var uz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Zl(t){for(let e in t){if(uz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Zl)||typeof r=="object"&&Zl(r))return!0}return!1}function xg(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!az.has(r)&&(typeof t[r]=="object"&&(0,oz.eachItem)(t[r],n=>e+=xg(n)),e===1/0))return 1/0}return e}function bg(t,e="",r){r!==!1&&(e=Rn(e));let n=t.parse(e);return wg(t,n)}Je.getFullPath=bg;function wg(t,e){return t.serialize(e).split("#")[0]+"#"}Je._getFullPath=wg;var lz=/#\/?$/;function Rn(t){return t?t.replace(lz,""):""}Je.normalizeId=Rn;function dz(t,e,r){return r=Rn(r),t.resolve(e,r)}Je.resolveUrl=dz;var fz=/^[a-z_][-a-z0-9._]*$/i;function pz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Rn(t[r]||e),s={"":o},i=bg(n,o,!1),a={},c=new Set;return iz(t,{allKeys:!0},(d,m,p,f)=>{if(f===void 0)return;let h=i+m,y=s[f];typeof d[r]=="string"&&(y=_.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[m]=y;function _(g){let b=this.opts.uriResolver.resolve;if(g=Rn(y?b(y,g):g),c.has(g))throw l(g);c.add(g);let S=this.refs[g];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?u(d,S.schema,g):g!==Rn(h)&&(g[0]==="#"?(u(d,a[g],g),a[g]=d):this.refs[g]=h),g}function v(g){if(typeof g=="string"){if(!fz.test(g))throw new Error(`invalid anchor "${g}"`);_.call(this,`#${g}`)}}}),a;function u(d,m,p){if(m!==void 0&&!sz(d,m))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Je.getSchemaRefs=pz});var jo=E(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.getData=cr.KeywordCxt=cr.validateFunctionCode=void 0;var Eg=rg(),$g=Co(),ql=Rl(),bi=Co(),mz=ug(),Mo=mg(),Dl=gg(),C=F(),Z=Ut(),hz=Ao(),Ft=Q(),No=Oo();function gz(t){if(Rg(t)&&(Ig(t),Pg(t))){vz(t);return}Tg(t,()=>(0,Eg.topBoolOrEmptySchema)(t))}cr.validateFunctionCode=gz;function Tg({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,C._)`${Z.default.data}, ${Z.default.valCxt}`,n.$async,()=>{t.code((0,C._)`"use strict"; ${kg(r,o)}`),_z(t,o),t.code(s)}):t.func(e,(0,C._)`${Z.default.data}, ${yz(o)}`,n.$async,()=>t.code(kg(r,o)).code(s))}function yz(t){return(0,C._)`{${Z.default.instancePath}="", ${Z.default.parentData}, ${Z.default.parentDataProperty}, ${Z.default.rootData}=${Z.default.data}${t.dynamicRef?(0,C._)`, ${Z.default.dynamicAnchors}={}`:C.nil}}={}`}function _z(t,e){t.if(Z.default.valCxt,()=>{t.var(Z.default.instancePath,(0,C._)`${Z.default.valCxt}.${Z.default.instancePath}`),t.var(Z.default.parentData,(0,C._)`${Z.default.valCxt}.${Z.default.parentData}`),t.var(Z.default.parentDataProperty,(0,C._)`${Z.default.valCxt}.${Z.default.parentDataProperty}`),t.var(Z.default.rootData,(0,C._)`${Z.default.valCxt}.${Z.default.rootData}`),e.dynamicRef&&t.var(Z.default.dynamicAnchors,(0,C._)`${Z.default.valCxt}.${Z.default.dynamicAnchors}`)},()=>{t.var(Z.default.instancePath,(0,C._)`""`),t.var(Z.default.parentData,(0,C._)`undefined`),t.var(Z.default.parentDataProperty,(0,C._)`undefined`),t.var(Z.default.rootData,Z.default.data),e.dynamicRef&&t.var(Z.default.dynamicAnchors,(0,C._)`{}`)})}function vz(t){let{schema:e,opts:r,gen:n}=t;Tg(t,()=>{r.$comment&&e.$comment&&Cg(t),kz(t),n.let(Z.default.vErrors,null),n.let(Z.default.errors,0),r.unevaluated&&xz(t),Og(t),Ez(t)})}function xz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,C._)`${r}.evaluated`),e.if((0,C._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,C._)`${t.evaluated}.props`,(0,C._)`undefined`)),e.if((0,C._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,C._)`${t.evaluated}.items`,(0,C._)`undefined`))}function kg(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,C._)`/*# sourceURL=${r} */`:C.nil}function bz(t,e){if(Rg(t)&&(Ig(t),Pg(t))){wz(t,e);return}(0,Eg.boolOrEmptySchema)(t,e)}function Pg({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 Rg(t){return typeof t.schema!="boolean"}function wz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Cg(t),Sz(t),zz(t);let s=n.const("_errs",Z.default.errors);Og(t,s),n.var(e,(0,C._)`${s} === ${Z.default.errors}`)}function Ig(t){(0,Ft.checkUnknownRules)(t),$z(t)}function Og(t,e){if(t.opts.jtd)return Sg(t,[],!1,e);let r=(0,$g.getSchemaTypes)(t.schema),n=(0,$g.coerceAndCheckDataType)(t,r);Sg(t,r,!n,e)}function $z(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Ft.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function kz(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Ft.checkStrictMode)(t,"default is ignored in the schema root")}function Sz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,hz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function zz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Cg({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,C._)`${Z.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,C.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,C._)`${Z.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Ez(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,C._)`${Z.default.errors} === 0`,()=>e.return(Z.default.data),()=>e.throw((0,C._)`new ${o}(${Z.default.vErrors})`)):(e.assign((0,C._)`${n}.errors`,Z.default.vErrors),s.unevaluated&&Tz(t),e.return((0,C._)`${Z.default.errors} === 0`))}function Tz({gen:t,evaluated:e,props:r,items:n}){r instanceof C.Name&&t.assign((0,C._)`${e}.props`,r),n instanceof C.Name&&t.assign((0,C._)`${e}.items`,n)}function Sg(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,Ft.schemaHasRulesButRef)(s,l))){o.block(()=>Ng(t,"$ref",l.all.$ref.definition));return}c.jtd||Pz(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,ql.shouldUseGroup)(s,m)&&(m.type?(o.if((0,bi.checkDataType)(m.type,i,c.strictNumbers)),zg(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,bi.reportTypeError)(t)),o.endIf()):zg(t,m),a||o.if((0,C._)`${Z.default.errors} === ${n||0}`))}}function zg(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,mz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,ql.shouldUseRule)(n,s)&&Ng(t,s.keyword,s.definition,e.type)})}function Pz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Rz(t,e),t.opts.allowUnionTypes||Iz(t,e),Oz(t,t.dataTypes))}function Rz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Ag(t.dataTypes,r)||Ll(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Az(t,e)}}function Iz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ll(t,"use allowUnionTypes to allow union type keyword")}function Oz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,ql.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Cz(e,i))&&Ll(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Cz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ag(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Az(t,e){let r=[];for(let n of t.dataTypes)Ag(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Ll(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Ft.checkStrictMode)(t,e,t.opts.strictTypes)}var wi=class{constructor(e,r,n){if((0,Mo.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,Ft.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",Mg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Mo.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",Z.default.errors))}result(e,r,n){this.failResult((0,C.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,C.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,C._)`${r} !== undefined && (${(0,C.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?No.reportExtraError:No.reportError)(this,this.def.error,r)}$dataError(){(0,No.reportError)(this,this.def.$dataError||No.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,No.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=C.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=C.nil,r=C.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,C.or)((0,C._)`${o} === undefined`,r)),e!==C.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==C.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,C.or)(i(),a());function i(){if(n.length){if(!(r instanceof C.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,C._)`${(0,bi.checkDataTypes)(c,r,s.opts.strictNumbers,bi.DataType.Wrong)}`}return C.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,C._)`!${c}(${r})`}return C.nil}}subschema(e,r){let n=(0,Dl.getSubschema)(this.it,e);(0,Dl.extendSubschemaData)(n,this.it,e),(0,Dl.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return bz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Ft.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Ft.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,C.Name)),!0}};cr.KeywordCxt=wi;function Ng(t,e,r,n){let o=new wi(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Mo.funcKeywordCode)(o,r):"macro"in r?(0,Mo.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Mo.funcKeywordCode)(o,r)}var Nz=/^\/(?:[^~]|~0|~1)*$/,Mz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Mg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return Z.default.rootData;if(t[0]==="/"){if(!Nz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=Z.default.rootData}else{let u=Mz.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,C._)`${s}${(0,C.getProperty)((0,Ft.unescapeJsonPointer)(u))}`,i=(0,C._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}cr.getData=Mg});var $i=E(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var Ul=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Fl.default=Ul});var Zo=E(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var Hl=Ao(),Vl=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Hl.resolveUrl)(e,r,n),this.missingSchema=(0,Hl.normalizeId)((0,Hl.getFullPath)(e,this.missingRef))}};Bl.default=Vl});var Si=E(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.resolveSchema=at.getCompilingSchema=at.resolveRef=at.compileSchema=at.SchemaEnv=void 0;var ht=F(),jz=$i(),Vr=Ut(),gt=Ao(),jg=Q(),Zz=jo(),In=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,gt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};at.SchemaEnv=In;function Kl(t){let e=Zg.call(this,t);if(e)return e;let r=(0,gt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new ht.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:jz.default,code:(0,ht._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Vr.default.data,parentData:Vr.default.parentData,parentDataProperty:Vr.default.parentDataProperty,dataNames:[Vr.default.data],dataPathArr:[ht.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ht.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ht.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ht._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Zz.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Vr.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${Vr.default.self}`,`${Vr.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:h}=u;p.evaluated={props:f instanceof ht.Name?void 0:f,items:h instanceof ht.Name?void 0:h,dynamicProps:f instanceof ht.Name,dynamicItems:h instanceof ht.Name},p.source&&(p.source.evaluated=(0,ht.stringify)(p.evaluated))}return t.validate=p,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)}}at.compileSchema=Kl;function Dz(t,e,r){var n;r=(0,gt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Uz.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 In({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=qz.call(this,s)}at.resolveRef=Dz;function qz(t){return(0,gt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Kl.call(this,t)}function Zg(t){for(let e of this._compilations)if(Lz(e,t))return e}at.getCompilingSchema=Zg;function Lz(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Uz(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ki.call(this,t,e)}function ki(t,e){let r=this.opts.uriResolver.parse(e),n=(0,gt._getFullPath)(this.opts.uriResolver,r),o=(0,gt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Jl.call(this,r,t);let s=(0,gt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ki.call(this,t,i);return typeof a?.schema!="object"?void 0:Jl.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Kl.call(this,i),s===(0,gt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,gt.resolveUrl)(this.opts.uriResolver,o,u)),new In({schema:a,schemaId:c,root:t,baseId:o})}return Jl.call(this,r,i)}}at.resolveSchema=ki;var Fz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Jl(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,jg.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Fz.has(a)&&u&&(e=(0,gt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,jg.schemaHasRulesButRef)(r,this.RULES)){let a=(0,gt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ki.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new In({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Dg=E((aZ,Hz)=>{Hz.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 ed=E((cZ,Bg)=>{"use strict";var Vz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Gl=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),Bz=RegExp.prototype.test.bind(/^\d*$/u),Br=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Xl=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Lg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Yl=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),Jz=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Ke=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Ke[e]="%"+t[e>>4]+t[e&15]}function Ne(t){return t<2048?Ke[192|t>>6]+Ke[128|t&63]:t<65536?Ke[224|t>>12]+Ke[128|t>>6&63]+Ke[128|t&63]:Ke[240|t>>18]+Ke[128|t>>12&63]+Ke[128|t>>6&63]+Ke[128|t&63]}function Kz(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 Wz=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),Gz=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),Xz=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),Yz=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Qz(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!Xz(t[e])){if(t[e]==="%"&&e+2<t.length&&Br(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function qg(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 eE(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||!Gl(c))return;s+=2;continue}if(!Wz(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:qg(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 qg(i)}function Wl(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&&Gz(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(tE(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),!Qz(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=eE(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function tE(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function rE(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 nE={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},oE=/[@/?#:]/g,sE=/[@/?#]/g;function Ug(t,e){let r=e?sE:oE;return r.lastIndex=0,t.replace(r,n=>nE[n])}function Fg(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(Br(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Xl(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function iE(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(Br(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Xl(i)?e+=i:e+="%"+s,r+=2;continue}}if(Lg(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=Vg(o)?n:Ke[o];else if(o<55296||o>57343)e+=Ne(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Ne(65536+(o-55296<<10)+(s-56320)),r++):e+=Ne(65533)}else e+=Ne(65533)}}return e}function aE(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(Br(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),Lg(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=Ke[i];else if(i<55296||i>57343)r+=Ne(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=Ne(65536+(i-55296<<10)+(a-56320)),o++):r+=Ne(65533)}else r+=Ne(65533)}}return r}function Ql(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(Br(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=Ke[s];else if(s<55296||s>57343)r+=Ne(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Ne(65536+(s-55296<<10)+(i-56320)),n++):r+=Ne(65533)}else r+=Ne(65533)}}return r}function Hg(t){return Ql(t,Jz)}function cE(t){return Ql(t,Yl)}function uE(t){return Ql(t,Yl)}function Vg(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 lE(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(Br(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Xl(i)?e+=i:e+="%"+s,r+=2;continue}}if(Yl(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=Vg(o)?n:Ke[o];else if(o<55296||o>57343)e+=Ne(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Ne(65536+(o-55296<<10)+(s-56320)),r++):e+=Ne(65533)}else e+=Ne(65533)}}return e}function dE(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(Br(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function fE(t){let e=[];if(t.userinfo!==void 0&&(e.push(Hg(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!Gl(r)){let n=Wl(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=Fg(r,!0),n=Wl(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=Ug(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!Bz(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}Bg.exports={nonSimpleDomain:Yz,recomposeAuthority:fE,reescapeHostDelimiters:Ug,normalizePercentEncoding:Fg,normalizePathEncoding:iE,serializePathEncoding:aE,normalizeQueryFragmentEncoding:lE,encodeUserinfo:Hg,encodeQuery:cE,encodeFragment:uE,escapePreservingEscapes:dE,removeDotSegments:rE,isIPv4:Gl,isUUID:Vz,normalizeIPv6:Wl,stringArrayToHexStripped:Kz}});var Xg=E((uZ,Gg)=>{"use strict";var{isUUID:pE}=ed(),mE=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,hE=["http","https","ws","wss","urn","urn:uuid"];function gE(t){return hE.indexOf(t)!==-1}function td(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 Jg(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Kg(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 yE(t){return t.secure=td(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function _E(t){if((t.port===(td(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 vE(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(mE);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=rd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function xE(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=rd(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 bE(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!pE(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function wE(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Wg={scheme:"http",domainHost:!0,parse:Jg,serialize:Kg},$E={scheme:"https",domainHost:Wg.domainHost,parse:Jg,serialize:Kg},zi={scheme:"ws",domainHost:!0,parse:yE,serialize:_E},kE={scheme:"wss",domainHost:zi.domainHost,parse:zi.parse,serialize:zi.serialize},SE={scheme:"urn",parse:vE,serialize:xE,skipNormalize:!0},zE={scheme:"urn:uuid",parse:bE,serialize:wE,skipNormalize:!0},Ei={http:Wg,https:$E,ws:zi,wss:kE,urn:SE,"urn:uuid":zE};Object.setPrototypeOf(Ei,null);function rd(t){return t&&(Ei[t]||Ei[t.toLowerCase()])||void 0}Gg.exports={wsIsSecure:td,SCHEMES:Ei,isValidSchemeName:gE,getSchemeHandler:rd}});var ly=E((lZ,Ri)=>{"use strict";var{normalizeIPv6:ry,removeDotSegments:qo,recomposeAuthority:EE,normalizePercentEncoding:nd,normalizePathEncoding:TE,serializePathEncoding:Yg,normalizeQueryFragmentEncoding:Qg,encodeQuery:PE,encodeFragment:RE,reescapeHostDelimiters:IE,isIPv4:ny,nonSimpleDomain:OE}=ed(),{SCHEMES:oy,getSchemeHandler:od}=Xg(),sy=/^[A-Za-z][A-Za-z0-9+.-]*$/u,iy="URI scheme is malformed.";function ey(t){let e=unescape(String(t));if(!sy.test(e))throw new TypeError(iy);return e}function CE(t,e){return typeof t=="string"?t=LE(t,e):typeof t=="object"&&(t=Pi(Jr(t,e),e)),t}function AE(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}=Ti(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:m,malformedSchemeSpecific:p,malformedHost:f,malformedScheme:h}=Ti(e,n);if(s||d||i||m||a||p||c||f||u||h)throw new Error(o.error||l.error||"URI is malformed.");let y=ay(o,l,n,!0),_=od(r&&r.scheme||y.scheme),v=y.host,g=v!==void 0&&v!==""&&(ny(v)||ry(v).isIPV6);cy(y,r||{},_,g);let b=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(y.error&&!b)throw new Error(y.error);return n.skipEscape=!0,Jr(y,n)}function ay(t,e,r,n){let o={};return n||(t=Pi(Jr(t,r),r),e=Pi(Jr(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=qo(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=qo(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=qo(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=qo(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 NE(t,e,r){let n=ty(t,r),o=ty(e,r);return n!==void 0&&o!==void 0&&n===o}function Jr(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=ey(r.scheme));let s=od(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=nd(r.path):r.path=Yg(r.path,a)),n.reference!=="suffix"&&r.scheme&&(r.scheme=ey(r.scheme),o.push(r.scheme,":"));let c=EE(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=qo(u)),a&&(u=Yg(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return r.query!==void 0&&o.push("?",PE(r.query)),r.fragment!==void 0&&o.push("#",RE(r.fragment)),o.join("")}var ME=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,jE=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,ZE=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function DE(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 Do(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 sd(t){return t[0]==="["&&t[t.length-1]==="]"}function qE(t){let e=t[4];return Do(t[3])||e!==void 0&&!sd(e)&&Do(e)||Do(t[6])||Do(t[7])||Do(t[8])}function cy(t,e,r,n){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!sd(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&OE(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 Ti(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(jE);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let m=t.match(ZE);if(m!==null){let f=m[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 p=t.match(ME);if(p){if(n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0){let y=unescape(n.scheme);sy.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||iy,u=!0)}s=qE(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let f=DE(n,p);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(ny(n.host)===!1){let _=sd(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,g=ry(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=od(r.scheme||n.scheme);if(c||(a=cy(n,r,h,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=l?n.host:nd(n.host,!0);l||(y=nd(y.toLowerCase())),n.host=IE(y,l)}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=TE(n.path)),n.query&&(n.query=Qg(n.query)),n.fragment&&(n.fragment=Qg(n.fragment))),h&&h.parse&&(h.parse(n,r),h===oy.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 Pi(t,e){return Ti(t,e).parsed}function LE(t,e){return uy(t,e).normalized}function uy(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Ti(t,e);return{normalized:n||o||s||i||a?t:Jr(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function ty(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:Jr(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=uy(r,e);return o||s||i||a||c?void 0:n}var id={SCHEMES:oy,normalize:CE,resolve:AE,resolveComponent:ay,equal:NE,serialize:Jr,parse:Pi};Ri.exports=id;Ri.exports.default=id;Ri.exports.fastUri=id});var fy=E(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var dy=ly();dy.code='require("ajv/dist/runtime/uri").default';ad.default=dy});var xy=E(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.CodeGen=Pe.Name=Pe.nil=Pe.stringify=Pe.str=Pe._=Pe.KeywordCxt=void 0;var UE=jo();Object.defineProperty(Pe,"KeywordCxt",{enumerable:!0,get:function(){return UE.KeywordCxt}});var On=F();Object.defineProperty(Pe,"_",{enumerable:!0,get:function(){return On._}});Object.defineProperty(Pe,"str",{enumerable:!0,get:function(){return On.str}});Object.defineProperty(Pe,"stringify",{enumerable:!0,get:function(){return On.stringify}});Object.defineProperty(Pe,"nil",{enumerable:!0,get:function(){return On.nil}});Object.defineProperty(Pe,"Name",{enumerable:!0,get:function(){return On.Name}});Object.defineProperty(Pe,"CodeGen",{enumerable:!0,get:function(){return On.CodeGen}});var FE=$i(),yy=Zo(),HE=Pl(),Lo=Si(),VE=F(),Uo=Ao(),Ii=Co(),ud=Q(),py=Dg(),BE=fy(),_y=(t,e)=>new RegExp(t,e);_y.code="new RegExp";var JE=["removeAdditional","useDefaults","coerceTypes"],KE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),WE={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."},GE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},my=200;function XE(t){var e,r,n,o,s,i,a,c,u,l,d,m,p,f,h,y,_,v,g,b,S,re,L,be,Xe;let ut=t.strict,Bn=(e=t.code)===null||e===void 0?void 0:e.optimize,Jn=Bn===!0||Bn===void 0?1:Bn||0,tn=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:_y,as=(o=t.uriResolver)!==null&&o!==void 0?o:BE.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:ut)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:ut)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:ut)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:ut)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:ut)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Jn,regExp:tn}:{optimize:Jn,regExp:tn},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:my,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:my,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:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(re=t.validateSchema)!==null&&re!==void 0?re:!0,validateFormats:(L=t.validateFormats)!==null&&L!==void 0?L:!0,unicodeRegExp:(be=t.unicodeRegExp)!==null&&be!==void 0?be:!0,int32range:(Xe=t.int32range)!==null&&Xe!==void 0?Xe:!0,uriResolver:as}}var Fo=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,...XE(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new VE.ValueScope({scope:{},prefixes:KE,es5:r,lines:n}),this.logger=nT(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,HE.getRules)(),hy.call(this,WE,e,"NOT SUPPORTED"),hy.call(this,GE,e,"DEPRECATED","warn"),this._metaOpts=tT.call(this),e.formats&&QE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&eT.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),YE.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=py;n==="id"&&(o={...py},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 m=this._addSchema(l,d);return m.validate||i.call(this,m)}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 yy.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,Uo.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=gy.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Lo.SchemaEnv({schema:{},schemaId:n});if(r=Lo.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=gy.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,Uo.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(sT.call(this,n,r),!r)return(0,ud.eachItem)(n,s=>cd.call(this,s)),this;aT.call(this,r);let o={...r,type:(0,Ii.getJSONTypes)(r.type),schemaType:(0,Ii.getJSONTypes)(r.schemaType)};return(0,ud.eachItem)(n,o.type.length===0?s=>cd.call(this,s,o):s=>o.type.forEach(i=>cd.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]=vy(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,Uo.normalizeId)(i||n);let u=Uo.getSchemaRefs.call(this,e,n);return c=new Lo.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):Lo.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{Lo.compileSchema.call(this,e)}finally{this.opts=r}}};Fo.ValidationError=FE.default;Fo.MissingRefError=yy.default;Pe.default=Fo;function hy(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 gy(t){return t=(0,Uo.normalizeId)(t),this.schemas[t]||this.refs[t]}function YE(){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 QE(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function eT(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 tT(){let t={...this.opts};for(let e of JE)delete t[e];return t}var rT={log(){},warn(){},error(){}};function nT(t){if(t===!1)return rT;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 oT=/^[a-z_$][a-z0-9_$:-]*$/i;function sT(t,e){let{RULES:r}=this;if((0,ud.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!oT.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 cd(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,Ii.getJSONTypes)(e.type),schemaType:(0,Ii.getJSONTypes)(e.schemaType)}};e.before?iT.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 iT(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 aT(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=vy(e)),t.validateSchema=this.compile(e,!0))}var cT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function vy(t){return{anyOf:[t,cT]}}});var by=E(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var uT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ld.default=uT});var Sy=E(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.callRef=Kr.getValidate=void 0;var lT=Zo(),wy=it(),We=F(),Cn=Ut(),$y=Si(),Oi=Q(),dT={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=$y.resolveRef.call(c,u,o,r);if(l===void 0)throw new lT.default(n.opts.uriResolver,o,r);if(l instanceof $y.SchemaEnv)return m(l);return p(l);function d(){if(s===u)return Ci(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return Ci(t,(0,We._)`${f}.validate`,u,u.$async)}function m(f){let h=ky(t,f);Ci(t,h,f,f.$async)}function p(f){let h=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,We.stringify)(f)}:{ref:f}),y=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:We.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(_),t.ok(y)}}};function ky(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,We._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Kr.getValidate=ky;function Ci(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Cn.default.this:We.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,We._)`await ${(0,wy.callValidateCode)(t,e,u)}`),p(e),i||o.assign(f,!0)},h=>{o.if((0,We._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),m(h),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,wy.callValidateCode)(t,e,u),()=>p(e),()=>m(e))}function m(f){let h=(0,We._)`${f}.errors`;o.assign(Cn.default.vErrors,(0,We._)`${Cn.default.vErrors} === null ? ${h} : ${Cn.default.vErrors}.concat(${h})`),o.assign(Cn.default.errors,(0,We._)`${Cn.default.vErrors}.length`)}function p(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=Oi.mergeEvaluated.props(o,y.props,s.props));else{let _=o.var("props",(0,We._)`${f}.evaluated.props`);s.props=Oi.mergeEvaluated.props(o,_,s.props,We.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Oi.mergeEvaluated.items(o,y.items,s.items));else{let _=o.var("items",(0,We._)`${f}.evaluated.items`);s.items=Oi.mergeEvaluated.items(o,_,s.items,We.Name)}}}Kr.callRef=Ci;Kr.default=dT});var zy=E(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var fT=by(),pT=Sy(),mT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",fT.default,pT.default];dd.default=mT});var Ey=E(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var Ai=F(),ur=Ai.operators,Ni={maximum:{okStr:"<=",ok:ur.LTE,fail:ur.GT},minimum:{okStr:">=",ok:ur.GTE,fail:ur.LT},exclusiveMaximum:{okStr:"<",ok:ur.LT,fail:ur.GTE},exclusiveMinimum:{okStr:">",ok:ur.GT,fail:ur.LTE}},hT={message:({keyword:t,schemaCode:e})=>(0,Ai.str)`must be ${Ni[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ai._)`{comparison: ${Ni[t].okStr}, limit: ${e}}`},gT={keyword:Object.keys(Ni),type:"number",schemaType:"number",$data:!0,error:hT,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Ai._)`${r} ${Ni[e].fail} ${n} || isNaN(${r})`)}};fd.default=gT});var Ty=E(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var Ho=F(),yT={message:({schemaCode:t})=>(0,Ho.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ho._)`{multipleOf: ${t}}`},_T={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:yT,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ho._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ho._)`${i} !== parseInt(${i})`;t.fail$data((0,Ho._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};pd.default=_T});var Ry=E(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});function Py(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}md.default=Py;Py.code='require("ajv/dist/runtime/ucs2length").default'});var Iy=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var Wr=F(),vT=Q(),xT=Ry(),bT={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Wr.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Wr._)`{limit: ${t}}`},wT={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:bT,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Wr.operators.GT:Wr.operators.LT,i=o.opts.unicode===!1?(0,Wr._)`${r}.length`:(0,Wr._)`${(0,vT.useFunc)(t.gen,xT.default)}(${r})`;t.fail$data((0,Wr._)`${i} ${s} ${n}`)}};hd.default=wT});var Oy=E(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var $T=it(),kT=Q(),An=F(),ST={message:({schemaCode:t})=>(0,An.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,An._)`{pattern: ${t}}`},zT={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ST,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,An._)`new RegExp`:(0,kT.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,An._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,An._)`!${l}`)}else{let c=(0,$T.usePattern)(t,o);t.fail$data((0,An._)`!${c}.test(${r})`)}}};gd.default=zT});var Cy=E(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var Vo=F(),ET={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Vo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Vo._)`{limit: ${t}}`},TT={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ET,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Vo.operators.GT:Vo.operators.LT;t.fail$data((0,Vo._)`Object.keys(${r}).length ${o} ${n}`)}};yd.default=TT});var Ay=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var Bo=it(),Jo=F(),PT=Q(),RT={message:({params:{missingProperty:t}})=>(0,Jo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Jo._)`{missingProperty: ${t}}`},IT={keyword:"required",type:"object",schemaType:"array",$data:!0,error:RT,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 p=t.parentSchema.properties,{definedProperties:f}=t.it;for(let h of r)if(p?.[h]===void 0&&!f.has(h)){let y=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,PT.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Jo.nil,d);else for(let p of r)(0,Bo.checkReportMissingProp)(t,p)}function l(){let p=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>m(p,f)),t.ok(f)}else e.if((0,Bo.checkMissingProp)(t,r,p)),(0,Bo.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,Bo.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function m(p,f){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,Bo.propertyInData)(e,o,p,a.ownProperties)),e.if((0,Jo.not)(f),()=>{t.error(),e.break()})},Jo.nil)}}};_d.default=IT});var Ny=E(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var Ko=F(),OT={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ko.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ko._)`{limit: ${t}}`},CT={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:OT,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ko.operators.GT:Ko.operators.LT;t.fail$data((0,Ko._)`${r}.length ${o} ${n}`)}};vd.default=CT});var Mi=E(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var My=jl();My.code='require("ajv/dist/runtime/equal").default';xd.default=My});var jy=E(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var bd=Co(),Re=F(),AT=Q(),NT=Mi(),MT={message:({params:{i:t,j:e}})=>(0,Re.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Re._)`{i: ${t}, j: ${e}}`},jT={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:MT,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,bd.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Re._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Re._)`${r}.length`),h=e.let("j");t.setParams({i:f,j:h}),e.assign(c,!0),e.if((0,Re._)`${f} > 1`,()=>(d()?m:p)(f,h))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function m(f,h){let y=e.name("item"),_=(0,bd.checkDataTypes)(u,y,a.opts.strictNumbers,bd.DataType.Wrong),v=e.const("indices",(0,Re._)`{}`);e.for((0,Re._)`;${f}--;`,()=>{e.let(y,(0,Re._)`${r}[${f}]`),e.if(_,(0,Re._)`continue`),u.length>1&&e.if((0,Re._)`typeof ${y} == "string"`,(0,Re._)`${y} += "_"`),e.if((0,Re._)`typeof ${v}[${y}] == "number"`,()=>{e.assign(h,(0,Re._)`${v}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Re._)`${v}[${y}] = ${f}`)})}function p(f,h){let y=(0,AT.useFunc)(e,NT.default),_=e.name("outer");e.label(_).for((0,Re._)`;${f}--;`,()=>e.for((0,Re._)`${h} = ${f}; ${h}--;`,()=>e.if((0,Re._)`${y}(${r}[${f}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};wd.default=jT});var Zy=E(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var $d=F(),ZT=Q(),DT=Mi(),qT={message:"must be equal to constant",params:({schemaCode:t})=>(0,$d._)`{allowedValue: ${t}}`},LT={keyword:"const",$data:!0,error:qT,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,$d._)`!${(0,ZT.useFunc)(e,DT.default)}(${r}, ${o})`):t.fail((0,$d._)`${s} !== ${r}`)}};kd.default=LT});var Dy=E(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Wo=F(),UT=Q(),FT=Mi(),HT={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Wo._)`{allowedValues: ${t}}`},VT={keyword:"enum",schemaType:"array",$data:!0,error:HT,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,UT.useFunc)(e,FT.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 p=e.const("vSchema",s);l=(0,Wo.or)(...o.map((f,h)=>m(p,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,p=>e.if((0,Wo._)`${u()}(${r}, ${p})`,()=>e.assign(l,!0).break()))}function m(p,f){let h=o[f];return typeof h=="object"&&h!==null?(0,Wo._)`${u()}(${r}, ${p}[${f}])`:(0,Wo._)`${r} === ${h}`}}};Sd.default=VT});var qy=E(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var BT=Ey(),JT=Ty(),KT=Iy(),WT=Oy(),GT=Cy(),XT=Ay(),YT=Ny(),QT=jy(),eP=Zy(),tP=Dy(),rP=[BT.default,JT.default,KT.default,WT.default,GT.default,XT.default,YT.default,QT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},eP.default,tP.default];zd.default=rP});var Td=E(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.validateAdditionalItems=void 0;var Gr=F(),Ed=Q(),nP={message:({params:{len:t}})=>(0,Gr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Gr._)`{limit: ${t}}`},oP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:nP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Ed.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Ly(t,n)}};function Ly(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Gr._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Gr._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Ed.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Gr._)`${a} <= ${e.length}`);r.if((0,Gr.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Ed.Type.Num},u),i.allErrors||r.if((0,Gr.not)(u),()=>r.break())})}}Go.validateAdditionalItems=Ly;Go.default=oP});var Pd=E(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.validateTuple=void 0;var Uy=F(),ji=Q(),sP=it(),iP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Fy(t,"additionalItems",e);r.items=!0,!(0,ji.alwaysValidSchema)(r,e)&&t.ok((0,sP.validateArray)(t))}};function Fy(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=ji.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Uy._)`${s}.length`);r.forEach((d,m)=>{(0,ji.alwaysValidSchema)(a,d)||(n.if((0,Uy._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function l(d){let{opts:m,errSchemaPath:p}=a,f=r.length,h=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(m.strictTuples&&!h){let y=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,ji.checkStrictMode)(a,y,m.strictTuples)}}}Xo.validateTuple=Fy;Xo.default=iP});var Hy=E(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var aP=Pd(),cP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,aP.validateTuple)(t,"items")};Rd.default=cP});var By=E(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var Vy=F(),uP=Q(),lP=it(),dP=Td(),fP={message:({params:{len:t}})=>(0,Vy.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Vy._)`{limit: ${t}}`},pP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:fP,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,uP.alwaysValidSchema)(n,e)&&(o?(0,dP.validateAdditionalItems)(t,o):t.ok((0,lP.validateArray)(t)))}};Id.default=pP});var Jy=E(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var ct=F(),Zi=Q(),mP={message:({params:{min:t,max:e}})=>e===void 0?(0,ct.str)`must contain at least ${t} valid item(s)`:(0,ct.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ct._)`{minContains: ${t}}`:(0,ct._)`{minContains: ${t}, maxContains: ${e}}`},hP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:mP,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,ct._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Zi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Zi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Zi.alwaysValidSchema)(s,r)){let h=(0,ct._)`${l} >= ${i}`;a!==void 0&&(h=(0,ct._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?p(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,ct._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let h=e.name("_valid"),y=e.let("count",0);p(h,()=>e.if(h,()=>f(y)))}function p(h,y){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:Zi.Type.Num,compositeRule:!0},h),y()})}function f(h){e.code((0,ct._)`${h}++`),a===void 0?e.if((0,ct._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ct._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ct._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};Od.default=hP});var Gy=E(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.validateSchemaDeps=Et.validatePropertyDeps=Et.error=void 0;var Cd=F(),gP=Q(),Yo=it();Et.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Cd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Cd._)`{property: ${t},
|
|
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
|
|
32
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,F._)`+${o}`);return;case"integer":n.elseIf((0,F._)`${i} === "boolean" || ${o} === null
|
|
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},
|
|
35
35
|
missingProperty: ${n},
|
|
36
36
|
depsCount: ${e},
|
|
37
|
-
deps: ${r}}`};var yP={keyword:"dependencies",type:"object",schemaType:"object",error:Et.error,code(t){let[e,r]=_P(t);Ky(t,e),Wy(t,r)}};function _P({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 Ky(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,Yo.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,Yo.checkReportMissingProp)(t,u)}):(r.if((0,Cd._)`${c} && (${(0,Yo.checkMissingProp)(t,a,s)})`),(0,Yo.reportMissingProp)(t,s),r.else())}}Et.validatePropertyDeps=Ky;function Wy(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,gP.alwaysValidSchema)(s,e[a])||(r.if((0,Yo.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))}Et.validateSchemaDeps=Wy;Et.default=yP});var Yy=E(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var Xy=F(),vP=Q(),xP={message:"property name must be valid",params:({params:t})=>(0,Xy._)`{propertyName: ${t.propertyName}}`},bP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:xP,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,vP.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,Xy.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ad.default=bP});var Md=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var Di=it(),yt=F(),wP=Ut(),qi=Q(),$P={message:"must NOT have additional properties",params:({params:t})=>(0,yt._)`{additionalProperty: ${t.additionalProperty}}`},kP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:$P,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,qi.alwaysValidSchema)(i,r))return;let u=(0,Di.allSchemaProperties)(n.properties),l=(0,Di.allSchemaProperties)(n.patternProperties);d(),t.ok((0,yt._)`${s} === ${wP.default.errors}`);function d(){e.forIn("key",o,y=>{!u.length&&!l.length?f(y):e.if(m(y),()=>f(y))})}function m(y){let _;if(u.length>8){let v=(0,qi.schemaRefOrVal)(i,n.properties,"properties");_=(0,Di.isOwnProperty)(e,v,y)}else u.length?_=(0,yt.or)(...u.map(v=>(0,yt._)`${y} === ${v}`)):_=yt.nil;return l.length&&(_=(0,yt.or)(_,...l.map(v=>(0,yt._)`${(0,Di.usePattern)(t,v)}.test(${y})`))),(0,yt.not)(_)}function p(y){e.code((0,yt._)`delete ${o}[${y}]`)}function f(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,qi.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(h(y,_,!1),e.if((0,yt.not)(_),()=>{t.reset(),p(y)})):(h(y,_),a||e.if((0,yt.not)(_),()=>e.break()))}}function h(y,_,v){let g={keyword:"additionalProperties",dataProp:y,dataPropType:qi.Type.Str};v===!1&&Object.assign(g,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(g,_)}}};Nd.default=kP});var t_=E(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});var SP=jo(),Qy=it(),jd=Q(),e_=Md(),zP={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&&e_.default.code(new SP.KeywordCxt(s,e_.default,"additionalProperties"));let i=(0,Qy.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=jd.mergeEvaluated.props(e,(0,jd.toHash)(i),s.props));let a=i.filter(d=>!(0,jd.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,Qy.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)}}};Zd.default=zP});var s_=E(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var r_=it(),Li=F(),n_=Q(),o_=Q(),EP={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,r_.allSchemaProperties)(r),c=a.filter(h=>(0,n_.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 Li.Name)&&(s.props=(0,o_.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let h of a)u&&p(h),s.allErrors?f(h):(e.var(l,!0),f(h),e.if(l))}function p(h){for(let y in u)new RegExp(h).test(y)&&(0,n_.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",n,y=>{e.if((0,Li._)`${(0,r_.usePattern)(t,h)}.test(${y})`,()=>{let _=c.includes(h);_||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:o_.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Li._)`${d}[${y}]`,!0):!_&&!s.allErrors&&e.if((0,Li.not)(l),()=>e.break())})})}}};Dd.default=EP});var i_=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var TP=Q(),PP={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,TP.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"}};qd.default=PP});var a_=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var RP=it(),IP={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:RP.validateUnion,error:{message:"must match a schema in anyOf"}};Ld.default=IP});var c_=E(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var Ui=F(),OP=Q(),CP={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ui._)`{passingSchemas: ${t.passing}}`},AP={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:CP,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 m;(0,OP.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ui._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ui._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,Ui.Name)})})}}};Ud.default=AP});var u_=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var NP=Q(),MP={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,NP.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Fd.default=MP});var f_=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Fi=F(),d_=Q(),jP={message:({params:t})=>(0,Fi.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Fi._)`{failingKeyword: ${t.ifClause}}`},ZP={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,d_.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=l_(n,"then"),s=l_(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,Fi.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 m=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(m,i),d?e.assign(d,(0,Fi._)`${l}`):t.setParams({ifClause:l})}}}};function l_(t,e){let r=t.schema[e];return r!==void 0&&!(0,d_.alwaysValidSchema)(t,r)}Hd.default=ZP});var p_=E(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var DP=Q(),qP={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,DP.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Vd.default=qP});var m_=E(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var LP=Td(),UP=Hy(),FP=Pd(),HP=By(),VP=Jy(),BP=Gy(),JP=Yy(),KP=Md(),WP=t_(),GP=s_(),XP=i_(),YP=a_(),QP=c_(),eR=u_(),tR=f_(),rR=p_();function nR(t=!1){let e=[XP.default,YP.default,QP.default,eR.default,tR.default,rR.default,JP.default,KP.default,BP.default,WP.default,GP.default];return t?e.push(UP.default,HP.default):e.push(LP.default,FP.default),e.push(VP.default),e}Bd.default=nR});var h_=E(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var ve=F(),oR={message:({schemaCode:t})=>(0,ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ve._)`{format: ${t}}`},sR={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:oR,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?m():p();function m(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ve._)`${f}[${i}]`),y=r.let("fType"),_=r.let("format");r.if((0,ve._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,ve._)`${h}.type || "string"`).assign(_,(0,ve._)`${h}.validate`),()=>r.assign(y,(0,ve._)`"string"`).assign(_,h)),t.fail$data((0,ve.or)(v(),g()));function v(){return c.strictSchema===!1?ve.nil:(0,ve._)`${i} && !${_}`}function g(){let b=l.$async?(0,ve._)`(${h}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ve._)`${_}(${n})`,S=(0,ve._)`(typeof ${_} == "function" ? ${b} : ${_}.test(${n}))`;return(0,ve._)`${_} && ${_} !== true && ${y} === ${e} && !${S}`}}function p(){let f=d.formats[s];if(!f){v();return}if(f===!0)return;let[h,y,_]=g(f);h===e&&t.pass(b());function v(){if(c.strictSchema===!1){d.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function g(S){let re=S instanceof RegExp?(0,ve.regexpCode)(S):c.code.formats?(0,ve._)`${c.code.formats}${(0,ve.getProperty)(s)}`:void 0,L=r.scopeValue("formats",{key:s,ref:S,code:re});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,ve._)`${L}.validate`]:["string",S,L]}function b(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ve._)`await ${_}(${n})`}return typeof y=="function"?(0,ve._)`${_}(${n})`:(0,ve._)`${_}.test(${n})`}}}};Jd.default=sR});var g_=E(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var iR=h_(),aR=[iR.default];Kd.default=aR});var y_=E(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.contentVocabulary=Nn.metadataVocabulary=void 0;Nn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Nn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var v_=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var cR=zy(),uR=qy(),lR=m_(),dR=g_(),__=y_(),fR=[cR.default,uR.default,(0,lR.default)(),dR.default,__.metadataVocabulary,__.contentVocabulary];Wd.default=fR});var b_=E(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.DiscrError=void 0;var x_;(function(t){t.Tag="tag",t.Mapping="mapping"})(x_||(Hi.DiscrError=x_={}))});var $_=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var Mn=F(),Gd=b_(),w_=Si(),pR=Zo(),mR=Q(),hR={message:({params:{discrError:t,tagName:e}})=>t===Gd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Mn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},gR={keyword:"discriminator",type:"object",schemaType:"object",error:hR,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,Mn._)`${r}${(0,Mn.getProperty)(a)}`);e.if((0,Mn._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Gd.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let p=m();e.if(!1);for(let f in p)e.elseIf((0,Mn._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:Gd.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(h,Mn.Name),f}function m(){var p;let f={},h=_(o),y=!0;for(let b=0;b<i.length;b++){let S=i[b];if(S?.$ref&&!(0,mR.schemaHasRulesButRef)(S,s.self.RULES)){let L=S.$ref;if(S=w_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,L),S instanceof w_.SchemaEnv&&(S=S.schema),S===void 0)throw new pR.default(s.opts.uriResolver,s.baseId,L)}let re=(p=S?.properties)===null||p===void 0?void 0:p[a];if(typeof re!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||_(S)),v(re,b)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return f;function _({required:b}){return Array.isArray(b)&&b.includes(a)}function v(b,S){if(b.const)g(b.const,S);else if(b.enum)for(let re of b.enum)g(re,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function g(b,S){if(typeof b!="string"||b in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[b]=S}}}};Xd.default=gR});var k_=E((YZ,yR)=>{yR.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 Qd=E((pe,Yd)=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.MissingRefError=pe.ValidationError=pe.CodeGen=pe.Name=pe.nil=pe.stringify=pe.str=pe._=pe.KeywordCxt=pe.Ajv=void 0;var _R=xy(),vR=v_(),xR=$_(),S_=k_(),bR=["/properties"],Vi="http://json-schema.org/draft-07/schema",jn=class extends _R.default{_addVocabularies(){super._addVocabularies(),vR.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(xR.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(S_,bR):S_;this.addMetaSchema(e,Vi,!1),this.refs["http://json-schema.org/schema"]=Vi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Vi)?Vi:void 0)}};pe.Ajv=jn;Yd.exports=pe=jn;Yd.exports.Ajv=jn;Object.defineProperty(pe,"__esModule",{value:!0});pe.default=jn;var wR=jo();Object.defineProperty(pe,"KeywordCxt",{enumerable:!0,get:function(){return wR.KeywordCxt}});var Zn=F();Object.defineProperty(pe,"_",{enumerable:!0,get:function(){return Zn._}});Object.defineProperty(pe,"str",{enumerable:!0,get:function(){return Zn.str}});Object.defineProperty(pe,"stringify",{enumerable:!0,get:function(){return Zn.stringify}});Object.defineProperty(pe,"nil",{enumerable:!0,get:function(){return Zn.nil}});Object.defineProperty(pe,"Name",{enumerable:!0,get:function(){return Zn.Name}});Object.defineProperty(pe,"CodeGen",{enumerable:!0,get:function(){return Zn.CodeGen}});var $R=$i();Object.defineProperty(pe,"ValidationError",{enumerable:!0,get:function(){return $R.default}});var kR=Zo();Object.defineProperty(pe,"MissingRefError",{enumerable:!0,get:function(){return kR.default}})});var C_=E(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.formatNames=Pt.fastFormats=Pt.fullFormats=void 0;function Tt(t,e){return{validate:t,compare:e}}Pt.fullFormats={date:Tt(P_,nf),time:Tt(tf(!0),of),"date-time":Tt(z_(!0),I_),"iso-time":Tt(tf(),R_),"iso-date-time":Tt(z_(),O_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:RR,"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:IR,int32:{type:"number",validate:AR},int64:{type:"number",validate:NR},float:{type:"number",validate:T_},double:{type:"number",validate:T_},password:!0,binary:!0};Pt.fastFormats={...Pt.fullFormats,date:Tt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,nf),time:Tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,of),"date-time":Tt(/^\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,I_),"iso-time":Tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,R_),"iso-date-time":Tt(/^\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,O_),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};Pt.formatNames=Object.keys(Pt.fullFormats);function SR(t){return t%4===0&&(t%100!==0||t%400===0)}var zR=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ER=[0,31,28,31,30,31,30,31,31,30,31,30,31];function P_(t){let e=zR.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&&SR(r)?29:ER[n])}function nf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ef=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function tf(t){return function(r){let n=ef.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,m=o-u*c-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&i<61}}function of(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 R_(t,e){if(!(t&&e))return;let r=ef.exec(t),n=ef.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 rf=/t|\s/i;function z_(t){let e=tf(t);return function(n){let o=n.split(rf);return o.length===2&&P_(o[0])&&e(o[1])}}function I_(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function O_(t,e){if(!(t&&e))return;let[r,n]=t.split(rf),[o,s]=e.split(rf),i=nf(r,o);if(i!==void 0)return i||of(n,s)}var TR=/\/|:/,PR=/^(?:[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 RR(t){return TR.test(t)&&PR.test(t)}var E_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function IR(t){return E_.lastIndex=0,E_.test(t)}var OR=-(2**31),CR=2**31-1;function AR(t){return Number.isInteger(t)&&t<=CR&&t>=OR}function NR(t){return Number.isInteger(t)}function T_(){return!0}var MR=/[^\\]\\Z/;function jR(t){if(MR.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var A_=E(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.formatLimitDefinition=void 0;var ZR=Qd(),_t=F(),lr=_t.operators,Bi={formatMaximum:{okStr:"<=",ok:lr.LTE,fail:lr.GT},formatMinimum:{okStr:">=",ok:lr.GTE,fail:lr.LT},formatExclusiveMaximum:{okStr:"<",ok:lr.LT,fail:lr.GTE},formatExclusiveMinimum:{okStr:">",ok:lr.GT,fail:lr.LTE}},DR={message:({keyword:t,schemaCode:e})=>(0,_t.str)`should be ${Bi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,_t._)`{comparison: ${Bi[t].okStr}, limit: ${e}}`};Dn.formatLimitDefinition={keyword:Object.keys(Bi),type:"string",schemaType:"string",$data:!0,error:DR,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 ZR.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),p=e.const("fmt",(0,_t._)`${m}[${c.schemaCode}]`);t.fail$data((0,_t.or)((0,_t._)`typeof ${p} != "object"`,(0,_t._)`${p} instanceof RegExp`,(0,_t._)`typeof ${p}.compare != "function"`,d(p)))}function l(){let m=c.schema,p=a.formats[m];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let f=e.scopeValue("formats",{key:m,ref:p,code:i.code.formats?(0,_t._)`${i.code.formats}${(0,_t.getProperty)(m)}`:void 0});t.fail$data(d(f))}function d(m){return(0,_t._)`${m}.compare(${r}, ${n}) ${Bi[o].fail} 0`}},dependencies:["format"]};var qR=t=>(t.addKeyword(Dn.formatLimitDefinition),t);Dn.default=qR});var Z_=E((Qo,j_)=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});var qn=C_(),LR=A_(),sf=F(),N_=new sf.Name("fullFormats"),UR=new sf.Name("fastFormats"),af=(t,e={keywords:!0})=>{if(Array.isArray(e))return M_(t,e,qn.fullFormats,N_),t;let[r,n]=e.mode==="fast"?[qn.fastFormats,UR]:[qn.fullFormats,N_],o=e.formats||qn.formatNames;return M_(t,o,r,n),e.keywords&&(0,LR.default)(t),t};af.get=(t,e="full")=>{let n=(e==="fast"?qn.fastFormats:qn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function M_(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,sf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}j_.exports=Qo=af;Object.defineProperty(Qo,"__esModule",{value:!0});Qo.default=af});var Pv={};Kn(Pv,{findEmbeddingModel:()=>Tv,ollamaUrl:()=>xf,semanticRerank:()=>y1});import{createHash as i1}from"node:crypto";import{existsSync as a1,mkdirSync as c1,readFileSync as u1,writeFileSync as l1}from"node:fs";import{homedir as d1}from"node:os";import{join as vf}from"node:path";function xf(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 Ev(t,e,r=6e4){let n=await fetch(xf()+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 Tv(t){let r=((await Ev("/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=>f1.test(n))}function ia(){return vf(process.env.XDG_CACHE_HOME??vf(d1(),".cache"),"context-doctor","embeddings.json")}function p1(){try{return a1(ia())?JSON.parse(u1(ia(),"utf8")):{}}catch{return{}}}function m1(t){try{let e=Object.keys(t);if(e.length>zv)for(let r of e.slice(0,e.length-zv))delete t[r];c1(vf(ia(),".."),{recursive:!0}),l1(ia(),JSON.stringify(t))}catch{}}async function h1(t,e){let r=[];for(let n=0;n<e.length;n+=Sv){let o=await Ev("/api/embed",{model:t,input:e.slice(n,n+Sv),truncate:!0});r.push(...o.embeddings)}return r}function g1(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 y1(t,e,r={}){let n;try{n=await Tv(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${xf()} (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=p1(),s=f=>i1("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 h1(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&&m1(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])),m=t.map((f,h)=>({c:f,s:g1(u,c[h])})).sort((f,h)=>h.s-f.s),p=new Map(m.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+p.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var f1,Sv,zv,Rv=J(()=>{"use strict";f1=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,Sv=64,zv=5e4});var Uv,Fv=J(()=>{Uv="x-hono-already-sent"});var Hv,Vv=J(()=>{Hv=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 Fn,constants as U1}from"node:http2";import{Readable as Bv}from"node:stream";async function dO(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function s0(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 Xv(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:s0(t.getReader(),e)}var Rt,F1,H1,V1,B1,J1,K1,Hn,Qv,e0,W1,G1,$f,kf,t0,Rf,Jv,la,Kv,X1,mr,Ht,Vn,ss,r0,n0,ns,Sf,zf,pr,ua,Bt,Wv,os,da,is,Y1,Q1,eO,tO,rO,nO,oO,If,sO,Gv,iO,Ot,aO,fr,Ef,Un,Vt,fa,It,cO,uO,lO,Tf,pa,Yv,fO,pO,i0,mO,hO,gO,a0,ma,Pf,c0,u0,yO,Of,_O,vO,xO,bO,wO,C2,l0=J(()=>{Fv();Vv();Rt=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},F1=/^\/[!#$&-;=?-\[\]_a-z~]*$/,H1=/\/\.\.?(?:[/?#]|$)/,V1=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,B1=(t,e,r)=>{let n=`${t}://${e}${r}`;if(V1.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Rt("Invalid URL");return!F1.test(r)||H1.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 Rt("Invalid host header");return o.href}},J1=t=>t instanceof Rt?t:new Rt(t.message,{cause:t}),K1=global.Request,Hn=class extends K1{constructor(t,e){if(typeof t=="object"&&mr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[Bt]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[mr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Qv=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)},e0=Symbol("wrapBodyStream"),W1=new Set(["latin1","binary","hex","base64","base64url"]),G1=t=>t===null||W1.has(t),$f=Symbol("bodyBufferedBeforeDisconnect"),kf=Symbol("bodyBufferedLengthBeforeDisconnect"),t0=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Rf=t=>!(t instanceof Fn)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&G1(t.readableEncoding),Jv=t=>{if(t.readableDidRead||!Rf(t))return;let e=t;e[kf]??=t.readableLength},la=(t,e)=>{if(t.readableDidRead&&!e||!Rf(t))return;let r=t;if(r[$f]!==void 0)return r[$f];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[kf]!==void 0&&t.readableLength!==r[kf])n=da();else{let s=e??[],i=t.read();i!==null&&s.push(t0(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=da())}}return r[$f]=n,n},Kv=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},X1=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new Hn(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[e0]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=la(n);if(l!==void 0){Kv(a,l);return}}i||=Bv.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=la(n);i!==void 0?s.body=new ReadableStream({start(a){Kv(a,i)}}):s.body=Bv.toWeb(n)}return new Hn(e,s)},mr=Symbol("getRequestCache"),Ht=Symbol("requestCache"),Vn=Symbol("incomingKey"),ss=Symbol("urlKey"),r0=Symbol("methodKey"),n0=Symbol("headersKey"),ns=Symbol("abortControllerKey"),Sf=Symbol("getAbortController"),zf=Symbol("abortRequest"),pr=Symbol("bodyBuffer"),ua=Symbol("bodyReadPromise"),Bt=Symbol("bodyConsumedDirectly"),Wv=Symbol("bodyLockReader"),os=Symbol("abortReason"),da=()=>new TypeError("Body is unusable"),is=()=>Promise.reject(da()),Y1=new TextDecoder,Q1=t=>{if(t[Bt])return is();t[Bt]=!0},eO=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),tO=t=>(t[n0]||=Qv(t[Vn])).get("content-type")||"",rO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,nO=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}},oO=t=>{if(!rO.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.`)},If=(t,e,r)=>{if(t[Bt])return is();let n=t.method;if(n==="GET"||n==="HEAD")return t[mr]()[e]();let o=oO(n);if(o)return Promise.reject(o);if(t[Ht]&&n!=="TRACE")return t[Ht][e]();let s=Q1(t);if(s)return s;let i=sO(t);if(i){let a=Promise.resolve(r(i,t));return t[pr]=void 0,a}return iO(t).then(a=>{let c=r(a,t);return t[pr]=void 0,c})},sO=t=>{let e=t[Vn];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},Gv=(t,e)=>{if(e.errored)return e.errored;let r=t[os];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},iO=t=>{if(t[pr])return Promise.resolve(t[pr]);if(t[ua])return t[ua];let e=t[Vn];if(e.readableDidRead)return is();let r=la(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[pr]=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!Rf(e)||y&&y.code!=="ECONNRESET"?!1:(c(()=>{let _=la(e,i);_ instanceof Error?s(_):_===void 0?s(h??Gv(t,e)):(t[pr]=_,o(_))}),!0)},l=h=>{i.push(t0(h,e.readableEncoding))},d=()=>{c(()=>{let h=i.length===1?i[0]:Buffer.concat(i);t[pr]=h,o(h)})},m=h=>{u(h)||c(()=>{s(h)})},p=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(Gv(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",m),e.off("close",p),t[ua]=void 0};e.on("data",l),e.on("end",d),e.on("error",m),e.on("close",p),queueMicrotask(()=>{a||(e.readableEnded?d():e.errored?m(e.errored):e.destroyed&&p())})});return t[ua]=n,n},Ot={get method(){return this[r0]},get url(){return this[ss]},get headers(){return this[n0]||=Qv(this[Vn])},[zf](t){this[os]===void 0&&(this[os]=t);let e=this[ns];e&&!e.signal.aborted&&e.abort(t)},[Sf](){return this[ns]||=new AbortController,this[os]!==void 0&&!this[ns].signal.aborted&&this[ns].abort(this[os]),this[ns]},[mr](){let t=this[Sf]();if(this[Ht])return this[Ht];let e=this.method;if(this[Bt]&&!(e==="GET"||e==="HEAD")){this[pr]=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 Hn(this[ss],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[Ht]=n}return this[Ht]=X1(this.method,this[ss],this.headers,this[Vn],t)},get body(){if(!this[Bt])return this[mr]().body;let t=this[mr]();return!this[Wv]&&t.body&&(this[Wv]=t.body.getReader()),t.body},get bodyUsed(){return this[Bt]?!0:this[Ht]?this[Ht].bodyUsed:!1}};Object.defineProperty(Ot,"signal",{get(){return this[Sf]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(Ot,t,{get(){return this[mr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(Ot,t,{value:function(){if(this[Bt]){if(t==="clone")throw da();return is()}return this[mr]()[t]()}})});Object.defineProperty(Ot,"text",{value:function(){return If(this,"text",t=>Y1.decode(t))}});Object.defineProperty(Ot,"arrayBuffer",{value:function(){return If(this,"arrayBuffer",t=>eO(t))}});Object.defineProperty(Ot,"blob",{value:function(){return If(this,"blob",(t,e)=>{let r=tO(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(Ot,"json",{value:function(){return this[Bt]?is():this.text().then(JSON.parse)}});Object.defineProperty(Ot,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[Ht]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Ot,Hn.prototype);aO=(t,e)=>{let r=Object.create(Ot);r[Vn]=t,r[r0]=nO(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof Fn)throw new Rt("Absolute URL for :path is not allowed in HTTP/2");try{r[ss]=new URL(n).href}catch(i){throw new Rt("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof Fn?t.authority:t.headers.host)||e;if(!o)throw new Rt("Missing host header");let s;if(t instanceof Fn){if(s=t.scheme,!(s==="http"||s==="https"))throw new Rt("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[ss]=B1(s,o,n)}catch(i){throw i instanceof Rt?i:new Rt("Invalid URL",{cause:i})}return r},fr="text/plain; charset=UTF-8",Ef=Symbol("responseCache"),Un=Symbol("getResponseCache"),Vt=Symbol("cache"),fa=global.Response,It=class o0{#e;#t;[Un](){let e=this[Vt],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[Vt],this[Ef]||=new fa(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 fa){let o=r[Ef];if(o){this.#t=o,this[Un]();return}this.#t=r instanceof o0?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[Vt]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[Vt];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":fr}))),e[2]):this[Un]().headers}get status(){return this[Vt]?.[0]??this[Un]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(It.prototype,t,{get(){return this[Un]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(It.prototype,t,{value:function(){return this[Un]()[t]()}})});Object.defineProperty(It.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[Ef]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(It,fa);Object.setPrototypeOf(It.prototype,fa.prototype);cO=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,uO=t=>t instanceof URL?t.href:cO.test(t)?t:new URL(t).href,lO=new Set([301,302,303,307,308]);Object.defineProperty(It,"redirect",{value:function(e,r=302){if(!lO.has(r))throw new RangeError("Invalid status code");return new It(null,{status:r,headers:{location:uO(e)}})},writable:!0,configurable:!0});Object.defineProperty(It,"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 It(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});Tf=(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},pa=Symbol("outgoingEnded"),Yv=Symbol("incomingDraining"),fO=500,pO=64*1024*1024,i0=t=>{let e=t;if(t.destroyed||e[Yv])return;if(e[Yv]=!0,t instanceof Fn){try{t.stream?.close?.(U1.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,fO);s.unref?.();let i=a=>{r+=a.length,r>pO&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},mO=(t,e,r,n)=>()=>{e.errored?(Jv(e),t[zf](e.errored.toString())):r.writableFinished||(Jv(e),t[zf]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{i0(e)})})},hO=t=>{if(!(Vt in t))return!1;let e=t[Vt][1];return e===null||typeof e=="string"||e instanceof Uint8Array},gO=()=>new Response(null,{status:400}),a0=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),ma=(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))},Pf=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},c0=async(t,e)=>{let[r,n,o]=t[Vt];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(e.writeHead(r,{"Content-Type":fr,"Content-Length":Buffer.byteLength(n)}),e.end(n)):n instanceof Uint8Array?(e.writeHead(r,{"Content-Type":fr,"Content-Length":n.byteLength}),e.end(n)):n instanceof Blob?(e.writeHead(r,{"Content-Type":fr,"Content-Length":n.size}),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":fr}),Pf(e),await Xv(n,e)?.catch(i=>ma(i,e))),e[pa]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=Tf(o,n===null?void 0:fr);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Tf(i,n===null?void 0:fr)}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())):(Pf(e),await Xv(n,e)?.catch(i=>ma(i,e))),e[pa]?.()},u0=t=>typeof t.then=="function",yO=async(t,e,r={})=>{if(u0(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(a0);if(Vt in t)return c0(t,e);let n=Tf(t.headers,t.body===null?void 0:fr);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 dO(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&&Pf(e),await s0(o,e,a))}else n[Uv]||(e.writeHead(t.status,n),e.end());e[pa]?.()},Of=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==Hn&&(Object.defineProperty(global,"Request",{value:Hn}),Object.defineProperty(global,"Response",{value:It})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",mO(i,n,o,a)))};try{if(i=aO(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[e0]=!0,n instanceof Fn&&(o[pa]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!u0(s)&&hO(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||i0(n)}),c0(s,o);u()}catch(l){if(s)return ma(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:J1(l)),!s)return}else i?s=a0(l):s=gO()}try{return await yO(s,o,e)}catch(l){return ma(l,o)}}},_O=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??""}},vO=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}},xO=()=>Symbol("connection"),bO=Symbol("CONNECTION_SYMBOL_KEY"),wO=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),C2=Hv(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[wO];if(!o||!n.incoming)return new Response(null,{status:500});let s=xO();return n[bO]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,m)=>{a.push([d,m])};i.on("message",c);let u={binaryType:"arraybuffer",close(d,m){i.close(d,m)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,m){i.send(d,{compress:m?.compress})},url:new URL(t.req.url)};try{e?.onOpen?.(new Event("open"),u)}catch(d){(r?.onError??console.error)(d)}let l=(d,m)=>{let p=Array.isArray(d)?d:[d];for(let f of p)try{e?.onMessage?.(new MessageEvent("message",{data:m?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,m)=>{l(d,m)}),i.on("close",(d,m)=>{try{e?.onClose?.(new _O("close",{code:d,reason:m.toString()}),u)}catch(p){(r?.onError??console.error)(p)}}),i.on("error",d=>{try{e?.onError?.(new vO("error",{error:d}),u)}catch(m){(r?.onError??console.error)(m)}})})(),new Response})});var m0=E(Cf=>{"use strict";var d0=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,$O=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,f0=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,kO=/\\([\u000b\u0020-\u00ff])/g,SO=/([\\"])/g,p0=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Cf.format=zO;Cf.parse=EO;function zO(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!p0.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],!f0.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+PO(e[o])}return n}function EO(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?TO(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(!p0.test(n))throw new TypeError("invalid media type");var o=new RO(n.toLowerCase());if(r!==-1){var s,i,a;for(d0.lastIndex=r;i=d0.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(kO,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function TO(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 PO(t){var e=String(t);if(f0.test(e))return e;if(e.length>0&&!$O.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(SO,"\\$1")+'"'}function RO(t){this.parameters=Object.create(null),this.type=t}});function IO(t){if(t)try{return h0.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function g0(t){return t==="application/json"?!0:IO(t)==="application/json"}var h0,y0=J(()=>{h0=ya(m0(),1)});function _0(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var v0=J(()=>{});var ha,x0=J(()=>{y0();v0();Zr();ha=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=_0(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
|
|
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
|
|
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:
|
|
@@ -44,53 +44,56 @@ data:
|
|
|
44
44
|
retry: ${this._retryInterval}
|
|
45
45
|
data:
|
|
46
46
|
|
|
47
|
-
`),e.enqueue(r.encode(i)),this._resumableStreams.add(n)}async handleGetRequest(e){if(!e.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept text/event-stream");let n=this.validateSession(e);if(n)return n;let o=this.validateProtocolVersion(e);if(o)return o;if(this._eventStore){let l=e.headers.get("last-event-id");if(l)return this.replayEvents(l)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(new Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32e3,"Conflict: Only one SSE stream is allowed per session");let s=new TextEncoder,i,a,c=new ReadableStream({start:l=>{i=l},cancel:()=>{a!==void 0&&clearInterval(a),this._streamMapping.get(this._standaloneSseStreamId)?.controller===i&&this._streamMapping.delete(this._standaloneSseStreamId)}}),u={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};return this.sessionId!==void 0&&(u["mcp-session-id"]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:s,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),a=this.startKeepAlive(i,s),new Response(c,{headers:u})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(new Error("Event store not configured")),this.createJsonErrorResponse(400,-32e3,"Event store not configured");try{let r;if(this._eventStore.getStreamIdForEventId){if(r=await this._eventStore.getStreamIdForEventId(e),!r)return this.onerror?.(new Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32e3,"Invalid event ID format");if(this._streamMapping.get(r)!==void 0)return this.onerror?.(new Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32e3,"Conflict: Stream already has an active connection")}let n={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(n["mcp-session-id"]=this.sessionId);let o=new TextEncoder,s,i,a,c=!1,u=new ReadableStream({start:d=>{s=d},cancel:()=>{c=!0,i!==void 0&&clearInterval(i),a!==void 0&&this._streamMapping.get(a)?.controller===s&&this._streamMapping.delete(a)}}),l=new Set;if(a=await this._eventStore.replayEventsAfter(e,{send:async(d,
|
|
47
|
+
`),e.enqueue(r.encode(i)),this._resumableStreams.add(n)}async handleGetRequest(e){if(!e.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept text/event-stream");let n=this.validateSession(e);if(n)return n;let o=this.validateProtocolVersion(e);if(o)return o;if(this._eventStore){let l=e.headers.get("last-event-id");if(l)return this.replayEvents(l)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(new Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32e3,"Conflict: Only one SSE stream is allowed per session");let s=new TextEncoder,i,a,c=new ReadableStream({start:l=>{i=l},cancel:()=>{a!==void 0&&clearInterval(a),this._streamMapping.get(this._standaloneSseStreamId)?.controller===i&&this._streamMapping.delete(this._standaloneSseStreamId)}}),u={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};return this.sessionId!==void 0&&(u["mcp-session-id"]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:s,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),a=this.startKeepAlive(i,s),new Response(c,{headers:u})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(new Error("Event store not configured")),this.createJsonErrorResponse(400,-32e3,"Event store not configured");try{let r;if(this._eventStore.getStreamIdForEventId){if(r=await this._eventStore.getStreamIdForEventId(e),!r)return this.onerror?.(new Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32e3,"Invalid event ID format");if(this._streamMapping.get(r)!==void 0)return this.onerror?.(new Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32e3,"Conflict: Stream already has an active connection")}let n={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(n["mcp-session-id"]=this.sessionId);let o=new TextEncoder,s,i,a,c=!1,u=new ReadableStream({start:d=>{s=d},cancel:()=>{c=!0,i!==void 0&&clearInterval(i),a!==void 0&&this._streamMapping.get(a)?.controller===s&&this._streamMapping.delete(a)}}),l=new Set;if(a=await this._eventStore.replayEventsAfter(e,{send:async(d,p)=>{if(this.writeSSEEvent(s,o,p,d))l.add(d);else{this.onerror?.(new Error("Failed replay events"));try{s.close()}catch{}}}}),this._closed||c){try{s.close()}catch{}return this.createJsonErrorResponse(404,-32001,"Session not found")}return this._streamMapping.get(a)?.cleanup(),this._streamMapping.set(a,{controller:s,encoder:o,replayedEventIds:l,cleanup:()=>{i!==void 0&&clearInterval(i),this._streamMapping.delete(a);try{s.close()}catch{}}}),this._resumableStreams.add(a),i=this.startKeepAlive(s,o),new Response(u,{headers:n})}catch(r){return this.onerror?.(r),this.createJsonErrorResponse(500,-32e3,"Error replaying events")}}writeSSEEvent(e,r,n,o){try{let s=`event: message
|
|
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(!g0(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=>mo.parse(v)):a=[mo.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(Fu);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(Zt)){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=>Fu(v)),m=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??Vm;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let g of a)Zt(g)&&this._requestToStreamMapping.set(g.id,l);for(let g of a)this.onmessage?.(g,{authInfo:r?.authInfo,requestInfo:s})});let p=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)Zt(v)&&(this._streamMapping.set(l,{controller:f,encoder:p,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,p,l,m);for(let v of a){let g,b;Zt(v)&&this._eventStore&&m>="2025-11-25"&&(g=()=>{this.closeSSEStream(v.id)},b=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:g,closeStandaloneSSEStream:b})}}catch(v){this._streamMapping.get(l)?.cleanup(),this._resumableStreams.delete(l);for(let g of a)Zt(g)&&this._requestToStreamMapping.delete(g.id);throw v}return this._streamMapping.get(l)?.controller===f&&(h=this.startKeepAlive(f,p)),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&&!_n.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${_n.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${_n.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((Dt(e)||vn(e))&&(n=e.id),n===void 0){if(Dt(e)||vn(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(Dt(e)||vn(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 b0={};Kn(b0,{StreamableHTTPServerTransport:()=>Af});var Af,w0=J(()=>{l0();x0();Af=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new ha(e),this._requestListener=Of(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 Of(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 Y={};Kn(Y,{BRAND:()=>rx,DIRTY:()=>hr,EMPTY_PATH:()=>A0,INVALID:()=>N,NEVER:()=>Dx,OK:()=>Ie,ParseStatus:()=>Se,Schema:()=>U,ZodAny:()=>Wt,ZodArray:()=>Mt,ZodBigInt:()=>yr,ZodBoolean:()=>_r,ZodBranded:()=>Gn,ZodCatch:()=>Pr,ZodDate:()=>vr,ZodDefault:()=>Tr,ZodDiscriminatedUnion:()=>ls,ZodEffects:()=>rt,ZodEnum:()=>zr,ZodError:()=>Le,ZodFirstPartyTypeKind:()=>k,ZodFunction:()=>fs,ZodIntersection:()=>$r,ZodIssueCode:()=>$,ZodLazy:()=>kr,ZodLiteral:()=>Sr,ZodMap:()=>cn,ZodNaN:()=>ln,ZodNativeEnum:()=>Er,ZodNever:()=>lt,ZodNull:()=>br,ZodNullable:()=>bt,ZodNumber:()=>gr,ZodObject:()=>Fe,ZodOptional:()=>Ue,ZodParsedType:()=>T,ZodPipeline:()=>Xn,ZodPromise:()=>Gt,ZodReadonly:()=>Rr,ZodRecord:()=>ds,ZodSchema:()=>U,ZodSet:()=>un,ZodString:()=>Kt,ZodSymbol:()=>sn,ZodTransformer:()=>rt,ZodTuple:()=>xt,ZodType:()=>U,ZodUndefined:()=>xr,ZodUnion:()=>wr,ZodUnknown:()=>Nt,ZodVoid:()=>an,addIssueToContext:()=>z,any:()=>dx,array:()=>hx,bigint:()=>ix,boolean:()=>Kf,coerce:()=>Zx,custom:()=>Vf,date:()=>ax,datetimeRegex:()=>Ff,defaultErrorMap:()=>Ct,discriminatedUnion:()=>_x,effect:()=>Rx,enum:()=>Ex,function:()=>kx,getErrorMap:()=>rn,getParsedType:()=>vt,instanceof:()=>ox,intersection:()=>vx,isAborted:()=>cs,isAsync:()=>nn,isDirty:()=>us,isValid:()=>Jt,late:()=>nx,lazy:()=>Sx,literal:()=>zx,makeIssue:()=>Wn,map:()=>wx,nan:()=>sx,nativeEnum:()=>Tx,never:()=>px,null:()=>lx,nullable:()=>Ox,number:()=>Jf,object:()=>ba,objectUtil:()=>_a,oboolean:()=>jx,onumber:()=>Mx,optional:()=>Ix,ostring:()=>Nx,pipeline:()=>Ax,preprocess:()=>Cx,promise:()=>Px,quotelessJson:()=>I0,record:()=>bx,set:()=>$x,setErrorMap:()=>C0,strictObject:()=>gx,string:()=>Bf,symbol:()=>cx,transformer:()=>Rx,tuple:()=>xx,undefined:()=>ux,union:()=>yx,unknown:()=>fx,util:()=>B,void:()=>mx});var B;(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})(B||(B={}));var _a;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(_a||(_a={}));var T=B.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vt=t=>{switch(typeof t){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(t)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":return Array.isArray(t)?T.array:t===null?T.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?T.promise:typeof Map<"u"&&t instanceof Map?T.map:typeof Set<"u"&&t instanceof Set?T.set:typeof Date<"u"&&t instanceof Date?T.date:T.object;default:return T.unknown}};var $=B.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),I0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Le=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,B.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()}};Le.create=t=>new Le(t);var O0=(t,e)=>{let r;switch(t.code){case $.invalid_type:t.received===T.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,B.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${B.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${B.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${B.joinValues(t.options)}, received '${t.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.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}"`:B.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case $.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 $.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 $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=e.defaultError,B.assertNever(t)}return{message:r}},Ct=O0;var Zf=Ct;function C0(t){Zf=t}function rn(){return Zf}var Wn=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}},A0=[];function z(t,e){let r=rn(),n=Wn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ct?void 0:Ct].filter(o=>!!o)});t.common.issues.push(n)}var Se=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 N;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 N;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}}},N=Object.freeze({status:"aborted"}),hr=t=>({status:"dirty",value:t}),Ie=t=>({status:"valid",value:t}),cs=t=>t.status==="aborted",us=t=>t.status==="dirty",Jt=t=>t.status==="valid",nn=t=>typeof Promise<"u"&&t instanceof Promise;var R;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(R||(R={}));var tt=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}},Df=(t,e)=>{if(Jt(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 Le(t.common.issues);return this._error=r,this._error}}};function D(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 U=class{get description(){return this._def.description}_getType(e){return vt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:vt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Se,ctx:{common:e.parent.common,data:e.data,parsedType:vt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(nn(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:vt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Df(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Jt(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=>Jt(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:vt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(nn(o)?o:Promise.resolve(o));return Df(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:$.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 rt({schema:this,typeName:k.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 Ue.create(this,this._def)}nullable(){return bt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Mt.create(this)}promise(){return Gt.create(this,this._def)}or(e){return wr.create([this,e],this._def)}and(e){return $r.create(this,e,this._def)}transform(e){return new rt({...D(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Tr({...D(this._def),innerType:this,defaultValue:r,typeName:k.ZodDefault})}brand(){return new Gn({typeName:k.ZodBranded,type:this,...D(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Pr({...D(this._def),innerType:this,catchValue:r,typeName:k.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Xn.create(this,e)}readonly(){return Rr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},N0=/^c[^\s-]{8,}$/i,M0=/^[0-9a-z]+$/,j0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Z0=/^[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,D0=/^[a-z0-9_-]{21}$/i,q0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,L0=/^[-+]?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)?)??$/,U0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,F0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",va,H0=/^(?:(?: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])$/,V0=/^(?:(?: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])$/,B0=/^(([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]))$/,J0=/^(([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])$/,K0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,W0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Lf="((\\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])))",G0=new RegExp(`^${Lf}$`);function Uf(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 X0(t){return new RegExp(`^${Uf(t)}$`)}function Ff(t){let e=`${Lf}T${Uf(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 Y0(t,e){return!!((e==="v4"||!e)&&H0.test(t)||(e==="v6"||!e)&&B0.test(t))}function Q0(t,e){if(!q0.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 ex(t,e){return!!((e==="v4"||!e)&&V0.test(t)||(e==="v6"||!e)&&J0.test(t))}var Kt=class t extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==T.string){let s=this._getOrReturnCtx(e);return z(s,{code:$.invalid_type,expected:T.string,received:s.parsedType}),N}let n=new Se,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),z(o,{code:$.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),z(o,{code:$.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?z(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&z(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")U0.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"email",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")va||(va=new RegExp(F0,"u")),va.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"emoji",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Z0.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"uuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")D0.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"nanoid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")N0.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"cuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")M0.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"cuid2",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")j0.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"ulid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),z(o,{validation:"url",code:$.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),z(o,{validation:"regex",code:$.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),z(o,{code:$.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),z(o,{code:$.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),z(o,{code:$.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Ff(s).test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{code:$.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?G0.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{code:$.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?X0(s).test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{code:$.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?L0.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"duration",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Y0(e.data,s.version)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"ip",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Q0(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"jwt",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?ex(e.data,s.version)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"cidr",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?K0.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"base64",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?W0.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"base64url",code:$.invalid_string,message:s.message}),n.dirty()):B.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:$.invalid_string,...R.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.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,...R.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,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...R.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...R.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...R.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...R.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...R.errToObj(r)})}nonempty(e){return this.min(1,R.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}};Kt.create=t=>new Kt({checks:[],typeName:k.ZodString,coerce:t?.coerce??!1,...D(t)});function tx(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 gr=class t extends U{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)!==T.number){let s=this._getOrReturnCtx(e);return z(s,{code:$.invalid_type,expected:T.number,received:s.parsedType}),N}let n,o=new Se;for(let s of this._def.checks)s.kind==="int"?B.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:$.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),z(n,{code:$.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),z(n,{code:$.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?tx(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),z(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:$.not_finite,message:s.message}),o.dirty()):B.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,R.toString(r))}gt(e,r){return this.setLimit("min",e,!1,R.toString(r))}lte(e,r){return this.setLimit("max",e,!0,R.toString(r))}lt(e,r){return this.setLimit("max",e,!1,R.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:R.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.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"&&B.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)}};gr.create=t=>new gr({checks:[],typeName:k.ZodNumber,coerce:t?.coerce||!1,...D(t)});var yr=class t extends U{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)!==T.bigint)return this._getInvalidInput(e);let n,o=new Se;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),z(n,{code:$.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),z(n,{code:$.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),z(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):B.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return z(r,{code:$.invalid_type,expected:T.bigint,received:r.parsedType}),N}gte(e,r){return this.setLimit("min",e,!0,R.toString(r))}gt(e,r){return this.setLimit("min",e,!1,R.toString(r))}lte(e,r){return this.setLimit("max",e,!0,R.toString(r))}lt(e,r){return this.setLimit("max",e,!1,R.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:R.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:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:R.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}};yr.create=t=>new yr({checks:[],typeName:k.ZodBigInt,coerce:t?.coerce??!1,...D(t)});var _r=class extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==T.boolean){let n=this._getOrReturnCtx(e);return z(n,{code:$.invalid_type,expected:T.boolean,received:n.parsedType}),N}return Ie(e.data)}};_r.create=t=>new _r({typeName:k.ZodBoolean,coerce:t?.coerce||!1,...D(t)});var vr=class t extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==T.date){let s=this._getOrReturnCtx(e);return z(s,{code:$.invalid_type,expected:T.date,received:s.parsedType}),N}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return z(s,{code:$.invalid_date}),N}let n=new Se,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),z(o,{code:$.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),z(o,{code:$.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):B.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:R.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:R.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}};vr.create=t=>new vr({checks:[],coerce:t?.coerce||!1,typeName:k.ZodDate,...D(t)});var sn=class extends U{_parse(e){if(this._getType(e)!==T.symbol){let n=this._getOrReturnCtx(e);return z(n,{code:$.invalid_type,expected:T.symbol,received:n.parsedType}),N}return Ie(e.data)}};sn.create=t=>new sn({typeName:k.ZodSymbol,...D(t)});var xr=class extends U{_parse(e){if(this._getType(e)!==T.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:$.invalid_type,expected:T.undefined,received:n.parsedType}),N}return Ie(e.data)}};xr.create=t=>new xr({typeName:k.ZodUndefined,...D(t)});var br=class extends U{_parse(e){if(this._getType(e)!==T.null){let n=this._getOrReturnCtx(e);return z(n,{code:$.invalid_type,expected:T.null,received:n.parsedType}),N}return Ie(e.data)}};br.create=t=>new br({typeName:k.ZodNull,...D(t)});var Wt=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return Ie(e.data)}};Wt.create=t=>new Wt({typeName:k.ZodAny,...D(t)});var Nt=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ie(e.data)}};Nt.create=t=>new Nt({typeName:k.ZodUnknown,...D(t)});var lt=class extends U{_parse(e){let r=this._getOrReturnCtx(e);return z(r,{code:$.invalid_type,expected:T.never,received:r.parsedType}),N}};lt.create=t=>new lt({typeName:k.ZodNever,...D(t)});var an=class extends U{_parse(e){if(this._getType(e)!==T.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:$.invalid_type,expected:T.void,received:n.parsedType}),N}return Ie(e.data)}};an.create=t=>new an({typeName:k.ZodVoid,...D(t)});var Mt=class t extends U{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==T.array)return z(r,{code:$.invalid_type,expected:T.array,received:r.parsedType}),N;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(z(r,{code:i?$.too_big:$.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&&(z(r,{code:$.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&&(z(r,{code:$.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 tt(r,i,r.path,a)))).then(i=>Se.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new tt(r,i,r.path,a)));return Se.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:R.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:R.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:R.toString(r)}})}nonempty(e){return this.min(1,e)}};Mt.create=(t,e)=>new Mt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...D(e)});function on(t){if(t instanceof Fe){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ue.create(on(n))}return new Fe({...t._def,shape:()=>e})}else return t instanceof Mt?new Mt({...t._def,type:on(t.element)}):t instanceof Ue?Ue.create(on(t.unwrap())):t instanceof bt?bt.create(on(t.unwrap())):t instanceof xt?xt.create(t.items.map(e=>on(e))):t}var Fe=class t extends U{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=B.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==T.object){let u=this._getOrReturnCtx(e);return z(u,{code:$.invalid_type,expected:T.object,received:u.parsedType}),N}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof lt&&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 tt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof lt){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&&(z(o,{code:$.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 tt(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,m=await l.value;u.push({key:d,value:m,alwaysSet:l.alwaysSet})}return u}).then(u=>Se.mergeObjectSync(n,u)):Se.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return R.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:R.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:k.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 B.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 B.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return on(this)}partial(e){let r={};for(let n of B.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 B.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ue;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Hf(B.objectKeys(this.shape))}};Fe.create=(t,e)=>new Fe({shape:()=>t,unknownKeys:"strip",catchall:lt.create(),typeName:k.ZodObject,...D(e)});Fe.strictCreate=(t,e)=>new Fe({shape:()=>t,unknownKeys:"strict",catchall:lt.create(),typeName:k.ZodObject,...D(e)});Fe.lazycreate=(t,e)=>new Fe({shape:t,unknownKeys:"strip",catchall:lt.create(),typeName:k.ZodObject,...D(e)});var wr=class extends U{_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 Le(a.ctx.common.issues));return z(r,{code:$.invalid_union,unionErrors:i}),N}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 Le(c));return z(r,{code:$.invalid_union,unionErrors:a}),N}}get options(){return this._def.options}};wr.create=(t,e)=>new wr({options:t,typeName:k.ZodUnion,...D(e)});var At=t=>t instanceof kr?At(t.schema):t instanceof rt?At(t.innerType()):t instanceof Sr?[t.value]:t instanceof zr?t.options:t instanceof Er?B.objectValues(t.enum):t instanceof Tr?At(t._def.innerType):t instanceof xr?[void 0]:t instanceof br?[null]:t instanceof Ue?[void 0,...At(t.unwrap())]:t instanceof bt?[null,...At(t.unwrap())]:t instanceof Gn||t instanceof Rr?At(t.unwrap()):t instanceof Pr?At(t._def.innerType):[],ls=class t extends U{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==T.object)return z(r,{code:$.invalid_type,expected:T.object,received:r.parsedType}),N;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}):(z(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),N)}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=At(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:k.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...D(n)})}};function xa(t,e){let r=vt(t),n=vt(e);if(t===e)return{valid:!0,data:t};if(r===T.object&&n===T.object){let o=B.objectKeys(e),s=B.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=xa(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===T.array&&n===T.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=xa(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===T.date&&n===T.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var $r=class extends U{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(cs(s)||cs(i))return N;let a=xa(s.value,i.value);return a.valid?((us(s)||us(i))&&r.dirty(),{status:r.value,value:a.data}):(z(n,{code:$.invalid_intersection_types}),N)};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}))}};$r.create=(t,e,r)=>new $r({left:t,right:e,typeName:k.ZodIntersection,...D(r)});var xt=class t extends U{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==T.array)return z(n,{code:$.invalid_type,expected:T.array,received:n.parsedType}),N;if(n.data.length<this._def.items.length)return z(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),N;!this._def.rest&&n.data.length>this._def.items.length&&(z(n,{code:$.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 tt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Se.mergeArray(r,i)):Se.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};xt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xt({items:t,typeName:k.ZodTuple,rest:null,...D(e)})};var ds=class t extends U{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!==T.object)return z(n,{code:$.invalid_type,expected:T.object,received:n.parsedType}),N;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new tt(n,a,n.path,a)),value:i._parse(new tt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Se.mergeObjectAsync(r,o):Se.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof U?new t({keyType:e,valueType:r,typeName:k.ZodRecord,...D(n)}):new t({keyType:Kt.create(),valueType:e,typeName:k.ZodRecord,...D(r)})}},cn=class extends U{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!==T.map)return z(n,{code:$.invalid_type,expected:T.map,received:n.parsedType}),N;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new tt(n,a,n.path,[u,"key"])),value:s._parse(new tt(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 N;(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 N;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};cn.create=(t,e,r)=>new cn({valueType:e,keyType:t,typeName:k.ZodMap,...D(r)});var un=class t extends U{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==T.set)return z(n,{code:$.invalid_type,expected:T.set,received:n.parsedType}),N;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(z(n,{code:$.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&&(z(n,{code:$.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 N;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 tt(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:R.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:R.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};un.create=(t,e)=>new un({valueType:t,minSize:null,maxSize:null,typeName:k.ZodSet,...D(e)});var fs=class t extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==T.function)return z(r,{code:$.invalid_type,expected:T.function,received:r.parsedType}),N;function n(a,c){return Wn({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,rn(),Ct].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function o(a,c){return Wn({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,rn(),Ct].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Gt){let a=this;return Ie(async function(...c){let u=new Le([]),l=await a._def.args.parseAsync(c,s).catch(p=>{throw u.addIssue(n(c,p)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(p=>{throw u.addIssue(o(d,p)),u})})}else{let a=this;return Ie(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Le([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Le([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:xt.create(e).rest(Nt.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||xt.create([]).rest(Nt.create()),returns:r||Nt.create(),typeName:k.ZodFunction,...D(n)})}},kr=class extends U{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})}};kr.create=(t,e)=>new kr({getter:t,typeName:k.ZodLazy,...D(e)});var Sr=class extends U{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return z(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),N}return{status:"valid",value:e.data}}get value(){return this._def.value}};Sr.create=(t,e)=>new Sr({value:t,typeName:k.ZodLiteral,...D(e)});function Hf(t,e){return new zr({values:t,typeName:k.ZodEnum,...D(e)})}var zr=class t extends U{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{expected:B.joinValues(n),received:r.parsedType,code:$.invalid_type}),N}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 z(r,{received:r.data,code:$.invalid_enum_value,options:n}),N}return Ie(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})}};zr.create=Hf;var Er=class extends U{_parse(e){let r=B.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==T.string&&n.parsedType!==T.number){let o=B.objectValues(r);return z(n,{expected:B.joinValues(o),received:n.parsedType,code:$.invalid_type}),N}if(this._cache||(this._cache=new Set(B.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=B.objectValues(r);return z(n,{received:n.data,code:$.invalid_enum_value,options:o}),N}return Ie(e.data)}get enum(){return this._def.values}};Er.create=(t,e)=>new Er({values:t,typeName:k.ZodNativeEnum,...D(e)});var Gt=class extends U{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==T.promise&&r.common.async===!1)return z(r,{code:$.invalid_type,expected:T.promise,received:r.parsedType}),N;let n=r.parsedType===T.promise?r.data:Promise.resolve(r.data);return Ie(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Gt.create=(t,e)=>new Gt({type:t,typeName:k.ZodPromise,...D(e)});var rt=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.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=>{z(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 N;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?N:c.status==="dirty"?hr(c.value):r.value==="dirty"?hr(c.value):c});{if(r.value==="aborted")return N;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?N:a.status==="dirty"?hr(a.value):r.value==="dirty"?hr(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"?N:(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"?N:(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(!Jt(i))return N;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=>Jt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):N);B.assertNever(o)}};rt.create=(t,e,r)=>new rt({schema:t,typeName:k.ZodEffects,effect:e,...D(r)});rt.createWithPreprocess=(t,e,r)=>new rt({schema:e,effect:{type:"preprocess",transform:t},typeName:k.ZodEffects,...D(r)});var Ue=class extends U{_parse(e){return this._getType(e)===T.undefined?Ie(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ue.create=(t,e)=>new Ue({innerType:t,typeName:k.ZodOptional,...D(e)});var bt=class extends U{_parse(e){return this._getType(e)===T.null?Ie(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bt.create=(t,e)=>new bt({innerType:t,typeName:k.ZodNullable,...D(e)});var Tr=class extends U{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===T.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Tr.create=(t,e)=>new Tr({innerType:t,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...D(e)});var Pr=class extends U{_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 nn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Le(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Le(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Pr.create=(t,e)=>new Pr({innerType:t,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...D(e)});var ln=class extends U{_parse(e){if(this._getType(e)!==T.nan){let n=this._getOrReturnCtx(e);return z(n,{code:$.invalid_type,expected:T.nan,received:n.parsedType}),N}return{status:"valid",value:e.data}}};ln.create=t=>new ln({typeName:k.ZodNaN,...D(t)});var rx=Symbol("zod_brand"),Gn=class extends U{_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}},Xn=class t extends U{_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"?N:s.status==="dirty"?(r.dirty(),hr(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"?N: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:k.ZodPipeline})}},Rr=class extends U{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Jt(o)&&(o.value=Object.freeze(o.value)),o);return nn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Rr.create=(t,e)=>new Rr({innerType:t,typeName:k.ZodReadonly,...D(e)});function qf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Vf(t,e={},r){return t?Wt.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=qf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=qf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Wt.create()}var nx={object:Fe.lazycreate},k;(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"})(k||(k={}));var ox=(t,e={message:`Input not instance of ${t.name}`})=>Vf(r=>r instanceof t,e),Bf=Kt.create,Jf=gr.create,sx=ln.create,ix=yr.create,Kf=_r.create,ax=vr.create,cx=sn.create,ux=xr.create,lx=br.create,dx=Wt.create,fx=Nt.create,px=lt.create,mx=an.create,hx=Mt.create,ba=Fe.create,gx=Fe.strictCreate,yx=wr.create,_x=ls.create,vx=$r.create,xx=xt.create,bx=ds.create,wx=cn.create,$x=un.create,kx=fs.create,Sx=kr.create,zx=Sr.create,Ex=zr.create,Tx=Er.create,Px=Gt.create,Rx=rt.create,Ix=Ue.create,Ox=bt.create,Cx=rt.createWithPreprocess,Ax=Xn.create,Nx=()=>Bf().optional(),Mx=()=>Jf().optional(),jx=()=>Kf().optional(),Zx={string:(t=>Kt.create({...t,coerce:!0})),number:(t=>gr.create({...t,coerce:!0})),boolean:(t=>_r.create({...t,coerce:!0})),bigint:(t=>yr.create({...t,coerce:!0})),date:(t=>vr.create({...t,coerce:!0}))};var Dx=N;Me();Me();Me();Me();var Kb=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");se.init(t,e),t.def=e,t.parse=(r,n)=>Ma(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Cr(t,r,n),t.parseAsync=async(r,n)=>Za(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ar(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)=>Qe(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var Wb=w("ZodMiniObject",(t,e)=>{ks.init(t,e),Kb.init(t,e),K.defineLazy(t,"shape",()=>e.shape)});function ku(t,e){let r={type:"object",get shape(){return K.assignProp(this,"shape",{...t}),this.shape},...K.normalizeParams(e)};return new Wb(r)}Me();zs();function kt(t){return!!t._zod}function jr(t){let e=Object.values(t);if(e.length===0)return ku({});let r=e.every(kt),n=e.every(o=>!kt(o));if(r)return ku(t);if(n)return ba(t);throw new Error("Mixed Zod versions detected in object shape.")}function Qt(t,e){return kt(t)?Cr(t,e):t.safeParse(e)}async function As(t,e){return kt(t)?await Ar(t,e):await t.safeParseAsync(e)}function er(t){if(!t)return;let e;if(kt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function hn(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 jr(t)}}if(kt(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 Xb(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Ns(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 ${Xb(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 gm(t){return t.description}function ym(t){if(kt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function gn(t){if(kt(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}Zr();function rr(t){return t==="completed"||t==="failed"||t==="cancelled"}var ch=Symbol("Let zodToJsonSchema decide on which parser to use");var ah={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"},uh=t=>typeof t=="string"?{...ah,name:t}:{...ah,...t};var lh=t=>{let e=uh(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 el(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function G(t,e,r,n,o){t[e]=r,el(t,e,n,o)}var ii=(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 ye(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ii(e,t.currentPath):e.join("/")}}function dh(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==k.ZodAny&&(r.items=j(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&G(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&G(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(G(r,"minItems",t.exactLength.value,t.exactLength.message,e),G(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function fh(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?G(r,"minimum",n.value,n.message,e):G(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),G(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?G(r,"maximum",n.value,n.message,e):G(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),G(r,"maximum",n.value,n.message,e));break;case"multipleOf":G(r,"multipleOf",n.value,n.message,e);break}return r}function ph(){return{type:"boolean"}}function ai(t,e){return j(t.type._def,e)}var mh=(t,e)=>j(t.innerType._def,e);function tl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>tl(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 $k(t,e)}}var $k=(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":G(r,"minimum",n.value,n.message,e);break;case"max":G(r,"maximum",n.value,n.message,e);break}return r};function hh(t,e){return{...j(t.innerType._def,e),default:t.defaultValue()}}function gh(t,e){return e.effectStrategy==="input"?j(t.schema._def,e):ye(e)}function yh(t){return{type:"string",enum:Array.from(t.values)}}var kk=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function _h(t,e){let r=[j(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),j(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(kk(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 vh(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 rl,ft={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:()=>(rl===void 0&&(rl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),rl),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 ci(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":G(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":G(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":pt(r,"email",n.message,e);break;case"format:idn-email":pt(r,"idn-email",n.message,e);break;case"pattern:zod":Ze(r,ft.email,n.message,e);break}break;case"url":pt(r,"uri",n.message,e);break;case"uuid":pt(r,"uuid",n.message,e);break;case"regex":Ze(r,n.regex,n.message,e);break;case"cuid":Ze(r,ft.cuid,n.message,e);break;case"cuid2":Ze(r,ft.cuid2,n.message,e);break;case"startsWith":Ze(r,RegExp(`^${nl(n.value,e)}`),n.message,e);break;case"endsWith":Ze(r,RegExp(`${nl(n.value,e)}$`),n.message,e);break;case"datetime":pt(r,"date-time",n.message,e);break;case"date":pt(r,"date",n.message,e);break;case"time":pt(r,"time",n.message,e);break;case"duration":pt(r,"duration",n.message,e);break;case"length":G(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),G(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ze(r,RegExp(nl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&pt(r,"ipv4",n.message,e),n.version!=="v4"&&pt(r,"ipv6",n.message,e);break}case"base64url":Ze(r,ft.base64url,n.message,e);break;case"jwt":Ze(r,ft.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ze(r,ft.ipv4Cidr,n.message,e),n.version!=="v4"&&Ze(r,ft.ipv6Cidr,n.message,e);break}case"emoji":Ze(r,ft.emoji(),n.message,e);break;case"ulid":{Ze(r,ft.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{pt(r,"binary",n.message,e);break}case"contentEncoding:base64":{G(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ze(r,ft.base64,n.message,e);break}}break}case"nanoid":Ze(r,ft.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function nl(t,e){return e.patternStrategy==="escape"?zk(t):t}var Sk=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function zk(t){let e="";for(let r=0;r<t.length;r++)Sk.has(t[r])||(e+="\\"),e+=t[r];return e}function pt(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}}})):G(t,"format",e,r,n)}function Ze(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:xh(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):G(t,"pattern",xh(e,n),r,n)}function xh(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(!$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
|
|
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 ui(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===k.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ye(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===k.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=ci(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===k.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===k.ZodBranded&&t.keyType._def.type._def.typeName===k.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ai(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function bh(t,e){if(e.mapStrategy==="record")return ui(t,e);let r=j(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ye(e),n=j(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ye(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function wh(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 $h(t){return t.target==="openAi"?void 0:{not:ye({...t,currentPath:[...t.currentPath,"not"]})}}function kh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var $o={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function zh(t,e){if(e.target==="openApi3")return Sh(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in $o&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=$o[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 Sh(t,e)}var Sh=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>j(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 Eh(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:$o[t.innerType._def.typeName],nullable:!0}:{type:[$o[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=j(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=j(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Th(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",el(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?G(r,"minimum",n.value,n.message,e):G(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),G(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?G(r,"maximum",n.value,n.message,e):G(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),G(r,"maximum",n.value,n.message,e));break;case"multipleOf":G(r,"multipleOf",n.value,n.message,e);break}return r}function Ph(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=Tk(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=j(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=Ek(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Ek(t,e){if(t.catchall._def.typeName!=="ZodNever")return j(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 Tk(t){try{return t.isOptional()}catch{return!0}}var Rh=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return j(t.innerType._def,e);let r=j(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ye(e)},r]}:ye(e)};var Ih=(t,e)=>{if(e.pipeStrategy==="input")return j(t.in._def,e);if(e.pipeStrategy==="output")return j(t.out._def,e);let r=j(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=j(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Oh(t,e){return j(t.type._def,e)}function Ch(t,e){let n={type:"array",uniqueItems:!0,items:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&G(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&G(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Ah(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>j(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:j(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>j(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Nh(t){return{not:ye(t)}}function Mh(t){return ye(t)}var jh=(t,e)=>j(t.innerType._def,e);var Zh=(t,e,r)=>{switch(e){case k.ZodString:return ci(t,r);case k.ZodNumber:return Th(t,r);case k.ZodObject:return Ph(t,r);case k.ZodBigInt:return fh(t,r);case k.ZodBoolean:return ph();case k.ZodDate:return tl(t,r);case k.ZodUndefined:return Nh(r);case k.ZodNull:return kh(r);case k.ZodArray:return dh(t,r);case k.ZodUnion:case k.ZodDiscriminatedUnion:return zh(t,r);case k.ZodIntersection:return _h(t,r);case k.ZodTuple:return Ah(t,r);case k.ZodRecord:return ui(t,r);case k.ZodLiteral:return vh(t,r);case k.ZodEnum:return yh(t);case k.ZodNativeEnum:return wh(t);case k.ZodNullable:return Eh(t,r);case k.ZodOptional:return Rh(t,r);case k.ZodMap:return bh(t,r);case k.ZodSet:return Ch(t,r);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return Oh(t,r);case k.ZodNaN:case k.ZodNever:return $h(r);case k.ZodEffects:return gh(t,r);case k.ZodAny:return ye(r);case k.ZodUnknown:return Mh(r);case k.ZodDefault:return hh(t,r);case k.ZodBranded:return ai(t,r);case k.ZodReadonly:return jh(t,r);case k.ZodCatch:return mh(t,r);case k.ZodPipeline:return Ih(t,r);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(n=>{})(e)}};function j(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==ch)return a}if(n&&!r){let a=Pk(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=Zh(t,t.typeName,e),i=typeof s=="function"?j(s(),e):s;if(i&&Rk(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Pk=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ii(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`),ye(e)):e.$refStrategy==="seen"?ye(e):void 0}},Rk=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ol=(t,e)=>{let r=lh(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:j(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ye(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=j(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ye(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 Ik(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function sl(t,e){return kt(t)?$u(t,{target:Ik(e?.target),io:e?.pipeStrategy??"input"}):ol(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function il(t){let r=er(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=gn(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function al(t,e){let r=Qt(t,e);if(!r.success)throw r.error;return r.data}var Ok=6e4,li=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(Us,r=>{this._oncancel(r)}),this.setNotificationHandler(Vs,r=>{this._onprogress(r)}),this.setRequestHandler(Hs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Bs,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(A.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ks,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,m=new I(d.error.code,d.error.message,d.error.data);l(m)}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 I(A.InvalidParams,`Task not found: ${s}`);if(!rr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(rr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[tr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ws,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 I(A.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Xs,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(rr(o.status))throw new I(A.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 I(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof I?o:new I(A.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),I.fromError(A.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),Dt(s)||vn(s)?this._onresponse(s):Zt(s)?this._onrequest(s,i):Xm(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=I.fromError(A.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?.[tr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:A.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=Km(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,m)=>{if(i.signal.aborted)throw new I(A.ConnectionClosed,"Request was cancelled");let p={...m,relatedRequestId:e.id};s&&!p.relatedTask&&(p.relatedTask={taskId:s});let f=p.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(l,d,p)},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:A.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),Dt(e))n(e);else{let i=new I(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(Dt(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),Dt(e))o(e);else{let i=I.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 I?i:new I(A.InternalError,String(i))}}return}let s;try{let i=await this.request(e,xn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new I(A.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},rr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new I(A.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new I(A.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 I?i:new I(A.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 m=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[tr]:c}});let f=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let g=v instanceof I?v:new I(A.RequestTimeout,String(v));l(g)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let g=Qt(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??Ok,y=()=>f(I.fromError(A.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=g=>{let b=this._responseHandlers.get(m);b?b(g):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(_,{type:"request",message:p,timestamp:Date.now()}).catch(g=>{this._cleanupTimeout(m),l(g)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(m),l(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Js,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},Gs,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Qm,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||{},[tr]: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||{},[tr]: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||{},[tr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=il(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=al(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=il(e);this._notificationHandlers.set(n,o=>{let s=al(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"&&Zt(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new I(A.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 I(A.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new I(A.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 I(A.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=vo.parse({method:"notifications/tasks/status",params:a});await this.notification(c),rr(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 I(A.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(rr(a.status))throw new I(A.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=vo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),rr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Dh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function qh(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];Dh(i)&&Dh(s)?r[o]={...i,...s}:r[o]=s}return r}Zr();var D_=ya(Qd(),1),q_=ya(Z_(),1);function FR(){let t=new D_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,q_.default)(t),t}var Ji=class{constructor(e){this._ajv=e??FR()}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)}}};Zr();var Ki=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(m=>m.type==="tool_use").map(m=>m.id)),d=new Set(s.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(l.size!==d.size||![...l].every(m=>d.has(m)))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},wo,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},$n,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 L_(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 U_(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 Wi=class extends li{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(bo.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 Ji,this.setRequestHandler(Fs,n=>this._oninitialize(n)),this.setNotificationHandler(Hu,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Xu,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=bo.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ki(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qh(this._capabilities,e)}setRequestHandler(e,r){let o=er(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=gn(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=Qt(wn,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new I(A.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let f=Qt(xn,m);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new I(A.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let p=Qt(oi,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new I(A.InvalidParams,`Invalid tools/call result: ${f}`)}return p.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){U_(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&L_(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:_n.includes(r)?r:Du,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"},Ls)}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},Yu,r):this.request({method:"sampling/createMessage",params:e},wo,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},$n,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},$n,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new I(A.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof I?i:new I(A.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},Qu,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"})}};Zr();var H_=Symbol.for("mcp.completable");function cf(t){return!!t&&typeof t=="object"&&H_ in t}function V_(t){return t[H_]?.complete}var F_;(function(t){t.Completable="McpCompletable"})(F_||(F_={}));var HR=/^[A-Za-z0-9._-]{1,128}$/;function VR(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"),!HR.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 BR(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 uf(t){let e=VR(t);return BR(t,e.warnings),e.isValid}var Gi=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 Xi=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 Wi(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Gi(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(dr(ni)),this.server.assertCanSetRequestHandler(dr(wn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ni,()=>({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=hn(r.inputSchema);return o?sl(o,{strictUnions:!0,pipeStrategy:"input"}):JR})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=hn(r.outputSchema);o&&(n.outputSchema=sl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(wn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new I(A.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new I(A.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 I(A.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new I(A.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 I&&n.code===A.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=hn(e.inputSchema)??e.inputSchema,i=await As(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ns(a);throw new I(A.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 I(A.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=hn(e.outputSchema),s=await As(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ns(i);throw new I(A.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(m=>setTimeout(m,l));let d=await n.taskStore.getTask(c);if(!d)throw new I(A.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(dr(si)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(si,async e=>{switch(e.params.ref.type){case"ref/prompt":return sh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return ih(e),this.handleResourceCompletion(e,e.params.ref);default:throw new I(A.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new I(A.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new I(A.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return es;let s=er(n.argsSchema)?.[e.params.argument.name];if(!cf(s))return es;let i=V_(s);if(!i)return es;let a=await i(e.params.argument.value,e.params.context);return J_(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 es;throw new I(A.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return es;let s=await o(e.params.argument.value,e.params.context);return J_(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(dr(Ys)),this.server.assertCanSetRequestHandler(dr(Qs)),this.server.assertCanSetRequestHandler(dr(ei)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ys,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(Qs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ei,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new I(A.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 I(A.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(dr(ti)),this.server.assertCanSetRequestHandler(dr(ri)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ti,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?KR(r.argsSchema):void 0}))})),this.server.setRequestHandler(ri,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new I(A.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new I(A.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=hn(n.argsSchema),s=await As(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Ns(c);throw new I(A.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:jr(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=jr(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 Ue?c._def?.innerType:c;return cf(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){uf(e);let l={title:r,description:n,inputSchema:B_(o),outputSchema:B_(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"&&uf(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=jr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=jr(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(lf(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!lf(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 JR={type:"object",properties:{}};function K_(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function W_(t){return"_def"in t||"_zod"in t||K_(t)}function lf(t){return typeof t!="object"||t===null||W_(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(K_)}function B_(t){if(t){if(lf(t))return jr(t);if(!W_(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function KR(t){let e=er(t);return e?Object.entries(e).map(([r,n])=>{let o=gm(n),s=ym(n);return{name:r,description:o,required:!s}}):[]}function dr(t){let r=er(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=gn(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function J_(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var es={completion:{values:[],hasMore:!1}};import X_ from"node:process";Zr();var WR=10*1024*1024,Yi=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??WR}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),
|
|
58
|
-
`}var
|
|
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
|
|
60
|
-
|
|
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(`
|
|
61
63
|
`)+`
|
|
62
|
-
`)}
|
|
63
|
-
`)}catch{}}var mI=2,hI=.5,gI=2;function yI(){return pI(fI(hf()),".context-doctor-calibration.json")}function _I(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 vI(){try{return JSON.parse(dI(yI(),"utf8"))}catch{return{}}}function iv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=vI()[_I(t)];if(!e||e.v!==mI||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<hI||r>gI?{factor:1,samples:0}:{factor:r,samples:e.samples}}function bI(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 wI(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.messages[a.messages.length-1];r.set(c,Math.max(r.get(c)??0,a.estSavings))}let o=[...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 $I(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function av(t){return xI("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function kI(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 SI(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=kI(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var cv=.6;function zI(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 uv=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function EI(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function TI(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;uv.lastIndex=0;for(let n of e.matchAll(uv)){let o=n[2].replace(/\\+$/,"");EI(o)&&r.add(o)}return[...r]}function lv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":void 0),n=iv(r),o=t.messages.map(g=>({msg:g,tokens:Math.round(Yr(g.text,r)*n.factor)+ff})),s=o.reduce((g,b)=>g+b.tokens,0),i={system:0,user:0,assistant:0,tool_calls:0,tool_results:0,other:0};for(let g of o)i[bI(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 b=av(g.msg.text),S=c.get(b);S!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:g.tokens-ff,message:`Message #${g.msg.index} duplicates the content of message #${S} (~${g.tokens} tokens).`,suggestion:"Replace repeated content with a short reference to the first occurrence.",messages:[S,g.msg.index]}):c.set(b,g.msg.index)}{let g=o.filter(L=>L.msg.text.length>=300).sort((L,be)=>be.tokens-L.tokens).slice(0,150),b=g.map(L=>SI(L.msg.text)),S=b.map(L=>L.size),re=new Set(a.filter(L=>L.id==="duplicate_content").flatMap(L=>L.messages));for(let L=0;L<g.length;L++)for(let be=L+1;be<g.length;be++){let Xe=g[L],ut=g[be];if(re.has(Xe.msg.index)&&re.has(ut.msg.index))continue;let Bn=Math.min(S[L],S[be]),Jn=Math.max(S[L],S[be]);if(Jn===0||Bn/Jn<cv)continue;let tn=zI(b[L],b[be]);if(tn>=cv){let as=Math.min(Xe.tokens,ut.tokens),[Mf,jf]=Xe.msg.index<=ut.msg.index?[Xe,ut]:[ut,Xe];a.push({id:"near_duplicate",severity:"warn",estSavings:Math.round(as*tn*.9),message:`Messages #${Mf.msg.index} and #${jf.msg.index} are ~${Math.round(tn*100)}% similar (~${as} tokens repeated with different framing).`,suggestion:"Replace the later copy with a short reference to the first \u2014 repeats survive even when the surrounding words differ.",messages:[Mf.msg.index,jf.msg.index]})}}}let u=new Map;for(let g of o){if(g.msg.kind!=="tool_call"||!g.msg.toolCallText)continue;let b=av(g.msg.toolCallText),S=u.get(b)??[];S.push(g.msg.index),u.set(b,S)}let l=g=>o.find(b=>b.msg.index>g&&b.msg.kind==="tool_result")?.msg;for(let[,g]of u){if(g.length<2)continue;let b=g.slice(1).filter((re,L)=>l(g[L])?.isError===!0).length,S=g.length-1-b;b>0&&a.push({id:"retried_tool_call",severity:b>=3?"warn":"info",estSavings:0,message:`The same tool call was retried ${b} time(s) after it failed (messages #${g.join(", #")}).`,suggestion:b>=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}),S>0&&a.push({id:"repeated_tool_call",severity:"info",estSavings:0,message:`The same tool call (with identical arguments) was repeated ${S} 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 b of o)if(!(b.msg.kind!=="tool_call"||!b.msg.toolCallText))for(let S of TI(b.msg.toolName,b.msg.toolCallText))g.set(S,[...g.get(S)??[],b.msg.index]);for(let[b,S]of g){if(S.length<3)continue;let re=o.filter(be=>be.msg.kind==="tool_result"&&S.some(Xe=>be.msg.index===Xe+1)).reduce((be,Xe)=>be+Xe.tokens,0),L=Math.round(re*(S.length-1)/S.length);a.push({id:"repeated_file_read",severity:L>4e3?"high":"warn",estSavings:L,message:`${b.split("/").pop()} was read ${S.length} times (messages #${S.join(", #")}), keeping ${S.length} copies in context.`,suggestion:"Re-read a file only after it changes; otherwise refer back to the copy already in context.",messages:S})}}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)Ln(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 b=o.slice(0,Math.floor(o.length/2)).reduce((S,re)=>S+re.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(b*.7),message:`Conversation has ${d} turns; the older half holds ~${b} 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:[]}),(Xr(e)==="anthropic"||Xr(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 m=ea(e),p=m?s/m*100:void 0;p!==void 0&&p>70&&a.push({id:"near_window_limit",severity:p>90?"high":"warn",estSavings:0,message:`Context is at ~${p.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:$I(g.msg.text),toolName:g.msg.toolName})).sort((g,b)=>b.tokens-g.tokens).slice(0,5),h={high:0,warn:1,info:2};a.sort((g,b)=>h[g.severity]-h[b.severity]||b.estSavings-g.estSavings);let y=wI(a,s),_=na(e),v;if(_){let g=ts(s,_),b=ts(y,_);v={perCallUsd:g,per1kCallsUsd:g*1e3,savingsPerCallUsd:b,savingsPer1kCallsUsd:b*1e3,ttftSeconds:pf(s),ttftSavedSeconds:pf(y)}}return{totalTokens:s,model:e,contextWindow:m,usagePct:p,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 PI}from"node:crypto";var pv=10,sa={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:pv};function RI(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 II(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 dv(t,e,r){let n=Math.round(e*ra("",r)),o={};for(let[s,i]of Object.entries(t))typeof i=="string"&&i.length>n?o[s]=i.slice(0,n)+`
|
|
64
|
-
[context-doctor: ${i.length-n} more chars trimmed \u2014 this call already ran]`:o[s]=i;return o}function
|
|
65
|
-
`):JSON.stringify(t
|
|
66
|
-
`),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
|
|
67
|
-
\u2026[context-doctor: trimmed ${s} chars of stale tool output]`}function
|
|
68
|
-
`);let
|
|
69
|
-
`)}var
|
|
70
|
-
`)):(e.push(""),e.push(`Findings (recoverable ~${
|
|
71
|
-
`))}function
|
|
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(`
|
|
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,`
|
|
72
74
|
|
|
73
75
|
`).replace(/<(w:tab|w:br)\/>/g," ").replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&").replace(/\n{3,}/g,`
|
|
74
76
|
|
|
75
|
-
`).trim()}function
|
|
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,`
|
|
76
78
|
|
|
77
|
-
`),!n&&r&&(n=
|
|
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,`
|
|
78
80
|
`).split(`
|
|
79
|
-
`).forEach((m
|
|
80
|
-
`,n));let u=(m
|
|
81
|
-
`);return{id:`${t.name}#${
|
|
82
|
-
`);
|
|
83
|
-
`)
|
|
84
|
-
`)
|
|
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(`
|
|
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):
|
|
85
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.
|
|
86
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.
|
|
87
90
|
3. Refer to earlier content by name; never re-quote it or inline base64.
|
|
88
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.
|
|
89
|
-
5. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.`,
|
|
90
|
-
`+i.applied.map(
|
|
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):
|
|
93
|
+
`+i.applied.map(p=>`- [${p.strategy}] message #${p.messageIndex}: ${p.note} (~${H(p.tokensSaved)})`).join(`
|
|
91
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.
|
|
92
95
|
|
|
93
96
|
PRUNED TURNS DIGEST:
|
|
94
|
-
`+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:
|
|
95
|
-
Skipped: ${d.slice(0,10).join("; ")}${d.length>10?` (+${d.length-10} more)`:""}`:"";return{content:[{type:"text",text:
|
|
96
|
-
`)}]})),e}var
|
|
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)}
|