context-doctor 0.41.0 → 0.42.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 +5 -4
- package/dist/ab.js +3 -1
- package/dist/autopilot.d.ts +1 -1
- package/dist/autopilot.js +38 -24
- package/dist/budget.d.ts +12 -1
- package/dist/budget.js +153 -31
- package/dist/cachettl.js +12 -9
- package/dist/claudedir.d.ts +8 -0
- package/dist/claudedir.js +19 -0
- package/dist/cli.js +63 -9
- package/dist/codexdir.d.ts +11 -0
- package/dist/codexdir.js +20 -0
- package/dist/codexroute.d.ts +1 -0
- package/dist/codexroute.js +3 -1
- package/dist/compactwindow.js +12 -9
- package/dist/cursor.js +20 -5
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +32 -14
- package/dist/effective.d.ts +18 -0
- package/dist/effective.js +39 -4
- package/dist/extract.d.ts +12 -3
- package/dist/extract.js +39 -12
- package/dist/fileparams.d.ts +1 -1
- package/dist/fileparams.js +8 -8
- package/dist/fix.d.ts +3 -1
- package/dist/fix.js +31 -11
- package/dist/hook.js +15 -4
- package/dist/install.js +106 -47
- package/dist/ledger.d.ts +15 -0
- package/dist/ledger.js +30 -1
- package/dist/limits.d.ts +15 -1
- package/dist/limits.js +71 -28
- package/dist/mcp.js +58 -58
- package/dist/overhead.js +2 -1
- package/dist/pack.js +3 -2
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/recall.js +3 -2
- package/dist/scan.d.ts +2 -0
- package/dist/scan.js +2 -1
- package/dist/session.js +2 -1
- package/dist/settingsedit.d.ts +4 -0
- package/dist/settingsedit.js +61 -3
- package/dist/spend.d.ts +8 -1
- package/dist/spend.js +27 -10
- package/dist/subagentmodel.d.ts +19 -4
- package/dist/subagentmodel.js +116 -28
- package/package.json +1 -1
package/dist/mcp.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cdRequire } from 'module'; const require = __cdRequire(import.meta.url);
|
|
3
|
-
var Sb=Object.create;var ec=Object.defineProperty;var Tb=Object.getOwnPropertyDescriptor;var Eb=Object.getOwnPropertyNames;var zb=Object.getPrototypeOf,Rb=Object.prototype.hasOwnProperty;var G=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),yo=(t,e)=>{for(var r in e)ec(t,r,{get:e[r],enumerable:!0})},Pb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Eb(e))!Rb.call(t,o)&&o!==r&&ec(t,o,{get:()=>e[o],enumerable:!(n=Tb(e,o))||n.enumerable});return t};var tc=(t,e,r)=>(r=t!=null?Sb(zb(t)):{},Pb(e||!t||!t.__esModule?ec(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 ot(t){return t&&Object.assign(js,t),js}var Lw,qw,Kt,js,zn=G(()=>{Lw=Object.freeze({status:"aborted"});qw=Symbol("zod_brand"),Kt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},js={}});var Y={};yo(Y,{BIGINT_FORMAT_RANGES:()=>em,Class:()=>ac,NUMBER_FORMAT_RANGES:()=>mc,aborted:()=>Yr,allowsEval:()=>dc,assert:()=>Vw,assertEqual:()=>Uw,assertIs:()=>Hw,assertNever:()=>Bw,assertNotEqual:()=>Fw,assignProp:()=>lc,cached:()=>$o,captureStackTrace:()=>Ds,cleanEnum:()=>s$,cleanRegex:()=>So,clone:()=>st,createTransparentProxy:()=>Yw,defineLazy:()=>fe,esc:()=>Xr,escapeRegex:()=>dr,extend:()=>t$,finalizeIssue:()=>xt,floatSafeRemainder:()=>uc,getElementAtPath:()=>Jw,getEnumValues:()=>wo,getLengthableOrigin:()=>To,getParsedType:()=>Xw,getSizableOrigin:()=>tm,isObject:()=>Rn,isPlainObject:()=>Pn,issue:()=>hc,joinValues:()=>Zs,jsonStringifyReplacer:()=>cc,merge:()=>r$,normalizeParams:()=>L,nullish:()=>ko,numKeys:()=>Gw,omit:()=>e$,optionalKeys:()=>pc,partial:()=>n$,pick:()=>Qw,prefixIssues:()=>At,primitiveTypes:()=>Qp,promiseAllObject:()=>Ww,propertyKeyTypes:()=>fc,randomString:()=>Kw,required:()=>o$,stringifyPrimitive:()=>Ls,unwrapMessage:()=>bo});function Uw(t){return t}function Fw(t){return t}function Hw(t){}function Bw(t){throw new Error}function Vw(t){}function wo(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 Zs(t,e="|"){return t.map(r=>Ls(r)).join(e)}function cc(t,e){return typeof e=="bigint"?e.toString():e}function $o(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ko(t){return t==null}function So(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function uc(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function fe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function lc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Jw(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Ww(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 Kw(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Xr(t){return JSON.stringify(t)}function Rn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Pn(t){if(Rn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Rn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Gw(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function dr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function st(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function L(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 Yw(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 Ls(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function pc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function Qw(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 st(t,{...t._zod.def,shape:r,checks:[]})}function e$(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 st(t,{...t._zod.def,shape:r,checks:[]})}function t$(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 lc(this,"shape",n),n},checks:[]};return st(t,r)}function r$(t,e){return st(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return lc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function n$(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 st(e,{...e._zod.def,shape:o,checks:[]})}function o$(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 st(e,{...e._zod.def,shape:o,checks:[]})}function Yr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function At(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function bo(t){return typeof t=="string"?t:t?.message}function xt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=bo(t.inst?._zod.def?.error?.(t))??bo(e?.error?.(t))??bo(r.customError?.(t))??bo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function tm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function To(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function hc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function s$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ds,dc,Xw,fc,Qp,mc,em,ac,Ot=G(()=>{Ds=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};dc=$o(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});Xw=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}`)}},fc=new Set(["string","number","symbol"]),Qp=new Set(["string","number","bigint","boolean","symbol","undefined"]);mc={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]},em={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};ac=class{constructor(...e){}}});function gc(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 yc(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 rm,qs,Eo,_c=G(()=>{zn();Ot();rm=(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,cc,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},qs=w("$ZodError",rm),Eo=w("$ZodError",rm,{Parent:Error})});var vc,xc,bc,wc,$c,Qr,kc,en,Sc=G(()=>{zn();_c();Ot();vc=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 Kt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>xt(c,s,ot())));throw Ds(a,o?.callee),a}return i.value},xc=vc(Eo),bc=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=>xt(c,s,ot())));throw Ds(a,o?.callee),a}return i.value},wc=bc(Eo),$c=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 Kt;return s.issues.length?{success:!1,error:new(t??qs)(s.issues.map(i=>xt(i,o,ot())))}:{success:!0,data:s.value}},Qr=$c(Eo),kc=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=>xt(i,o,ot())))}:{success:!0,data:s.value}},en=kc(Eo)});function fm(){return new RegExp(a$,"u")}function wm(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 $m(t){return new RegExp(`^${wm(t)}$`)}function km(t){let e=wm({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(`^${xm}T(?:${n})$`)}var nm,om,sm,im,am,cm,um,lm,Tc,dm,a$,pm,mm,hm,gm,ym,Ec,_m,vm,xm,bm,Sm,Tm,Em,zm,Rm,Pm,Im,Fs=G(()=>{nm=/^[cC][^\s-]{8,}$/,om=/^[0-9a-z]+$/,sm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,im=/^[0-9a-vA-V]{20}$/,am=/^[A-Za-z0-9]{27}$/,cm=/^[a-zA-Z0-9_-]{21}$/,um=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,lm=/^([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})$/,Tc=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)$/,dm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,a$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";pm=/^(?:(?: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])$/,mm=/^(([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})$/,hm=/^((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])$/,gm=/^(([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])$/,ym=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ec=/^[A-Za-z0-9_-]*$/,_m=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,vm=/^\+(?:[0-9]){6,14}[0-9]$/,xm="(?:(?:\\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])))",bm=new RegExp(`^${xm}$`);Sm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Tm=/^\d+$/,Em=/^-?\d+(?:\.\d+)?/i,zm=/true|false/i,Rm=/null/i,Pm=/^[^A-Z]*$/,Im=/^[^a-z]*$/});var Pe,Cm,zc,Rc,Am,Om,Nm,Mm,jm,zo,Zm,Dm,Lm,qm,Um,Fm,Hm,Hs=G(()=>{zn();Fs();Ot();Pe=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Cm={number:"number",bigint:"bigint",object:"date"},zc=w("$ZodCheckLessThan",(t,e)=>{Pe.init(t,e);let r=Cm[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})}}),Rc=w("$ZodCheckGreaterThan",(t,e)=>{Pe.init(t,e);let r=Cm[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})}}),Am=w("$ZodCheckMultipleOf",(t,e)=>{Pe.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):uc(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})}}),Om=w("$ZodCheckNumberFormat",(t,e)=>{Pe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=mc[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=Tm)}),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})}}),Nm=w("$ZodCheckMaxLength",(t,e)=>{var r;Pe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ko(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=To(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Mm=w("$ZodCheckMinLength",(t,e)=>{var r;Pe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ko(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=To(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),jm=w("$ZodCheckLengthEquals",(t,e)=>{var r;Pe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ko(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=To(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})}}),zo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Pe.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=()=>{})}),Zm=w("$ZodCheckRegex",(t,e)=>{zo.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})}}),Dm=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Pm),zo.init(t,e)}),Lm=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Im),zo.init(t,e)}),qm=w("$ZodCheckIncludes",(t,e)=>{Pe.init(t,e);let r=dr(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})}}),Um=w("$ZodCheckStartsWith",(t,e)=>{Pe.init(t,e);let r=new RegExp(`^${dr(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})}}),Fm=w("$ZodCheckEndsWith",(t,e)=>{Pe.init(t,e);let r=new RegExp(`.*${dr(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})}}),Hm=w("$ZodCheckOverwrite",(t,e)=>{Pe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Bs,Pc=G(()=>{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 Pb=Object.create;var nc=Object.defineProperty;var Ib=Object.getOwnPropertyDescriptor;var Cb=Object.getOwnPropertyNames;var Ab=Object.getPrototypeOf,Ob=Object.prototype.hasOwnProperty;var G=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),vo=(t,e)=>{for(var r in e)nc(t,r,{get:e[r],enumerable:!0})},Nb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Cb(e))!Ob.call(t,o)&&o!==r&&nc(t,o,{get:()=>e[o],enumerable:!(n=Ib(e,o))||n.enumerable});return t};var oc=(t,e,r)=>(r=t!=null?Pb(Ab(t)):{},Nb(e||!t||!t.__esModule?nc(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 ot(t){return t&&Object.assign(Ds,t),Ds}var Bw,Vw,Gt,Ds,Rn=G(()=>{Bw=Object.freeze({status:"aborted"});Vw=Symbol("zod_brand"),Gt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ds={}});var Y={};vo(Y,{BIGINT_FORMAT_RANGES:()=>om,Class:()=>lc,NUMBER_FORMAT_RANGES:()=>yc,aborted:()=>Qr,allowsEval:()=>mc,assert:()=>Xw,assertEqual:()=>Jw,assertIs:()=>Kw,assertNever:()=>Gw,assertNotEqual:()=>Ww,assignProp:()=>pc,cached:()=>So,captureStackTrace:()=>qs,cleanEnum:()=>l$,cleanRegex:()=>Eo,clone:()=>st,createTransparentProxy:()=>n$,defineLazy:()=>fe,esc:()=>Yr,escapeRegex:()=>fr,extend:()=>i$,finalizeIssue:()=>bt,floatSafeRemainder:()=>fc,getElementAtPath:()=>Yw,getEnumValues:()=>ko,getLengthableOrigin:()=>zo,getParsedType:()=>r$,getSizableOrigin:()=>sm,isObject:()=>Pn,isPlainObject:()=>In,issue:()=>_c,joinValues:()=>Ls,jsonStringifyReplacer:()=>dc,merge:()=>a$,normalizeParams:()=>L,nullish:()=>To,numKeys:()=>t$,omit:()=>s$,optionalKeys:()=>gc,partial:()=>c$,pick:()=>o$,prefixIssues:()=>Ot,primitiveTypes:()=>nm,promiseAllObject:()=>Qw,propertyKeyTypes:()=>hc,randomString:()=>e$,required:()=>u$,stringifyPrimitive:()=>Us,unwrapMessage:()=>$o});function Jw(t){return t}function Ww(t){return t}function Kw(t){}function Gw(t){throw new Error}function Xw(t){}function ko(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 Ls(t,e="|"){return t.map(r=>Us(r)).join(e)}function dc(t,e){return typeof e=="bigint"?e.toString():e}function So(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 Eo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function fc(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function fe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function pc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Yw(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Qw(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 e$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Yr(t){return JSON.stringify(t)}function Pn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function In(t){if(Pn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Pn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function t$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function fr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function st(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function L(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 n$(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 Us(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function gc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function o$(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 st(t,{...t._zod.def,shape:r,checks:[]})}function s$(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 st(t,{...t._zod.def,shape:r,checks:[]})}function i$(t,e){if(!In(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 pc(this,"shape",n),n},checks:[]};return st(t,r)}function a$(t,e){return st(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return pc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function c$(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 st(e,{...e._zod.def,shape:o,checks:[]})}function u$(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 st(e,{...e._zod.def,shape:o,checks:[]})}function Qr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Ot(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function $o(t){return typeof t=="string"?t:t?.message}function bt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=$o(t.inst?._zod.def?.error?.(t))??$o(e?.error?.(t))??$o(r.customError?.(t))??$o(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function sm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function zo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _c(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function l$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var qs,mc,r$,hc,nm,yc,om,lc,Nt=G(()=>{qs=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};mc=So(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});r$=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}`)}},hc=new Set(["string","number","symbol"]),nm=new Set(["string","number","bigint","boolean","symbol","undefined"]);yc={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]},om={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};lc=class{constructor(...e){}}});function vc(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 xc(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 im,Fs,Ro,bc=G(()=>{Rn();Nt();im=(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,dc,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Fs=w("$ZodError",im),Ro=w("$ZodError",im,{Parent:Error})});var wc,$c,kc,Sc,Tc,en,Ec,tn,zc=G(()=>{Rn();bc();Nt();wc=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 Gt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>bt(c,s,ot())));throw qs(a,o?.callee),a}return i.value},$c=wc(Ro),kc=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=>bt(c,s,ot())));throw qs(a,o?.callee),a}return i.value},Sc=kc(Ro),Tc=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 Gt;return s.issues.length?{success:!1,error:new(t??Fs)(s.issues.map(i=>bt(i,o,ot())))}:{success:!0,data:s.value}},en=Tc(Ro),Ec=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=>bt(i,o,ot())))}:{success:!0,data:s.value}},tn=Ec(Ro)});function gm(){return new RegExp(f$,"u")}function Tm(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 Em(t){return new RegExp(`^${Tm(t)}$`)}function zm(t){let e=Tm({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(`^${km}T(?:${n})$`)}var am,cm,um,lm,dm,fm,pm,mm,Rc,hm,f$,ym,_m,vm,xm,bm,Pc,wm,$m,km,Sm,Rm,Pm,Im,Cm,Am,Om,Nm,Bs=G(()=>{am=/^[cC][^\s-]{8,}$/,cm=/^[0-9a-z]+$/,um=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lm=/^[0-9a-vA-V]{20}$/,dm=/^[A-Za-z0-9]{27}$/,fm=/^[a-zA-Z0-9_-]{21}$/,pm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,mm=/^([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})$/,Rc=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)$/,hm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,f$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";ym=/^(?:(?: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])$/,_m=/^(([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})$/,vm=/^((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])$/,xm=/^(([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])$/,bm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pc=/^[A-Za-z0-9_-]*$/,wm=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,$m=/^\+(?:[0-9]){6,14}[0-9]$/,km="(?:(?:\\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])))",Sm=new RegExp(`^${km}$`);Rm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Pm=/^\d+$/,Im=/^-?\d+(?:\.\d+)?/i,Cm=/true|false/i,Am=/null/i,Om=/^[^A-Z]*$/,Nm=/^[^a-z]*$/});var Pe,Mm,Ic,Cc,jm,Zm,Dm,Lm,qm,Po,Um,Fm,Hm,Bm,Vm,Jm,Wm,Vs=G(()=>{Rn();Bs();Nt();Pe=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Mm={number:"number",bigint:"bigint",object:"date"},Ic=w("$ZodCheckLessThan",(t,e)=>{Pe.init(t,e);let r=Mm[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})}}),Cc=w("$ZodCheckGreaterThan",(t,e)=>{Pe.init(t,e);let r=Mm[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})}}),jm=w("$ZodCheckMultipleOf",(t,e)=>{Pe.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):fc(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})}}),Zm=w("$ZodCheckNumberFormat",(t,e)=>{Pe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=yc[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=Pm)}),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})}}),Dm=w("$ZodCheckMaxLength",(t,e)=>{var r;Pe.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=zo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Lm=w("$ZodCheckMinLength",(t,e)=>{var r;Pe.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=zo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),qm=w("$ZodCheckLengthEquals",(t,e)=>{var r;Pe.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=zo(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})}}),Po=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Pe.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=()=>{})}),Um=w("$ZodCheckRegex",(t,e)=>{Po.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})}}),Fm=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Om),Po.init(t,e)}),Hm=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Nm),Po.init(t,e)}),Bm=w("$ZodCheckIncludes",(t,e)=>{Pe.init(t,e);let r=fr(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})}}),Vm=w("$ZodCheckStartsWith",(t,e)=>{Pe.init(t,e);let r=new RegExp(`^${fr(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})}}),Jm=w("$ZodCheckEndsWith",(t,e)=>{Pe.init(t,e);let r=new RegExp(`.*${fr(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})}}),Wm=w("$ZodCheckOverwrite",(t,e)=>{Pe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Js,Ac=G(()=>{Js=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 Gm,Oc=G(()=>{Gm={major:4,minor:0,patch:0}});function lh(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function p$(t){if(!Pc.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return lh(r)}function m$(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 Xm(t,e,r){t.issues.length&&e.issues.push(...Ot(r,t.issues)),e.value[r]=t.value}function Ws(t,e,r){t.issues.length&&e.issues.push(...Ot(r,t.issues)),e.value[r]=t.value}function Ym(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(...Ot(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Qm(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=>bt(s,n,ot())))}),e}function Nc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(In(t)&&In(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Nc(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Nc(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function eh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Qr(t))return t;let n=Nc(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function th(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function rh(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 nh(t,e,r){return Qr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function oh(t){return t.value=Object.freeze(t.value),t}function sh(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(_c(o))}}var ue,Io,pe,Mc,jc,Zc,Dc,Lc,qc,Uc,Fc,Hc,Bc,Vc,ih,ah,ch,uh,Jc,Wc,Kc,Gc,Xc,Yc,Qc,eu,Ks,tu,ru,nu,ou,su,iu,Gs,Xs,au,cu,uu,lu,du,fu,pu,mu,hu,gu,yu,_u,vu,xu,bu,dh=G(()=>{Vs();Rn();Ac();zc();Bs();Nt();Oc();Nt();ue=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Gm;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=Qr(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,m=l._zod.check(s);if(m instanceof Promise&&a?.async===!1)throw new Gt;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==d&&(c||(c=Qr(s,d)))});else{if(s.issues.length===d)continue;c||(c=Qr(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 Gt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=en(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return tn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Io=w("$ZodString",(t,e)=>{ue.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Rm(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),pe=w("$ZodStringFormat",(t,e)=>{Po.init(t,e),Io.init(t,e)}),Mc=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=mm),pe.init(t,e)}),jc=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=Rc(n))}else e.pattern??(e.pattern=Rc());pe.init(t,e)}),Zc=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=hm),pe.init(t,e)}),Dc=w("$ZodURL",(t,e)=>{pe.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:wm.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})}}}),Lc=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=gm()),pe.init(t,e)}),qc=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=fm),pe.init(t,e)}),Uc=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=am),pe.init(t,e)}),Fc=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=cm),pe.init(t,e)}),Hc=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=um),pe.init(t,e)}),Bc=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=lm),pe.init(t,e)}),Vc=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=dm),pe.init(t,e)}),ih=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=zm(e)),pe.init(t,e)}),ah=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Sm),pe.init(t,e)}),ch=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Em(e)),pe.init(t,e)}),uh=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=pm),pe.init(t,e)}),Jc=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ym),pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Wc=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=_m),pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Kc=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=vm),pe.init(t,e)}),Gc=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=xm),pe.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Xc=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=bm),pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{lh(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Yc=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Pc),pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{p$(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Qc=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=$m),pe.init(t,e)});eu=w("$ZodJWT",(t,e)=>{pe.init(t,e),t._zod.check=r=>{m$(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ks=w("$ZodNumber",(t,e)=>{ue.init(t,e),t._zod.pattern=t._zod.bag.pattern??Im,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}}),tu=w("$ZodNumber",(t,e)=>{Zm.init(t,e),Ks.init(t,e)}),ru=w("$ZodBoolean",(t,e)=>{ue.init(t,e),t._zod.pattern=Cm,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}}),nu=w("$ZodNull",(t,e)=>{ue.init(t,e),t._zod.pattern=Am,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}}),ou=w("$ZodUnknown",(t,e)=>{ue.init(t,e),t._zod.parse=r=>r}),su=w("$ZodNever",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});iu=w("$ZodArray",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Xm(u,r,i))):Xm(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Gs=w("$ZodObject",(t,e)=>{ue.init(t,e);let r=So(()=>{let d=Object.keys(e.shape);for(let p of d)if(!(e.shape[p]instanceof ue))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let m=gc(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(m)}});fe(t._zod,"propValues",()=>{let d=e.shape,m={};for(let p in d){let f=d[p]._zod;if(f.values){m[p]??(m[p]=new Set);for(let g of f.values)m[p].add(g)}}return m});let n=d=>{let m=new Js(["shape","payload","ctx"]),p=r.value,f=v=>{let y=Yr(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};m.write("const input = payload.value;");let g=Object.create(null),h=0;for(let v of p.keys)g[v]=`key_${h++}`;m.write("const newResult = {}");for(let v of p.keys)if(p.optionalKeys.has(v)){let y=g[v];m.write(`const ${y} = ${f(v)};`);let x=Yr(v);m.write(`
|
|
6
6
|
if (${y}.issues.length) {
|
|
7
7
|
if (input[${x}] === undefined) {
|
|
8
8
|
if (${x} in input) {
|
|
@@ -24,18 +24,18 @@ var Sb=Object.create;var ec=Object.defineProperty;var Tb=Object.getOwnPropertyDe
|
|
|
24
24
|
`)}else{let y=g[v];m.write(`const ${y} = ${f(v)};`),m.write(`
|
|
25
25
|
if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
|
|
26
26
|
...iss,
|
|
27
|
-
path: iss.path ? [${
|
|
28
|
-
})));`),m.write(`newResult[${Xr(v)}] = ${y}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let _=m.compile();return(v,y)=>_(d,v,y)},o,s=Rn,i=!js.jitless,c=i&&dc.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 y=l.shape;for(let x of l.keys){let $=y[x],O=$._zod.run({value:p[x],issues:[]},m),C=$._zod.optin==="optional"&&$._zod.optout==="optional";O instanceof Promise?f.push(O.then(ae=>C?Wm(ae,d,x,p):Vs(ae,d,x))):C?Wm(O,d,x,p):Vs(O,d,x)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let g=[],h=l.keySet,_=u._zod,v=_.def.type;for(let y of Object.keys(p)){if(h.has(y))continue;if(v==="never"){g.push(y);continue}let x=_.run({value:p[y],issues:[]},m);x instanceof Promise?f.push(x.then($=>Vs($,d,y))):Vs(x,d,y)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:p,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Ks=w("$ZodUnion",(t,e)=>{ue.init(t,e),fe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),fe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),fe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),fe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>So(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=>Km(i,r,t,n)):Km(s,r,t,n)}}),ou=w("$ZodDiscriminatedUnion",(t,e)=>{Ks.init(t,e);let r=t._zod.parse;fe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=$o(()=>{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(!Rn(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)}}),su=w("$ZodIntersection",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Gm(r,c,u)):Gm(r,s,i)}});iu=w("$ZodRecord",(t,e)=>{ue.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(...At(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...At(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=>xt(u,n,ot())),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(...At(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...At(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),au=w("$ZodEnum",(t,e)=>{ue.init(t,e);let r=wo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>fc.has(typeof n)).map(n=>typeof n=="string"?dr(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}}),cu=w("$ZodLiteral",(t,e)=>{ue.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?dr(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}}),uu=w("$ZodTransform",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Kt;return r.value=o,r}}),lu=w("$ZodOptional",(t,e)=>{ue.init(t,e),t._zod.optin="optional",t._zod.optout="optional",fe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),fe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${So(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)}),du=w("$ZodNullable",(t,e)=>{ue.init(t,e),fe(t._zod,"optin",()=>e.innerType._zod.optin),fe(t._zod,"optout",()=>e.innerType._zod.optout),fe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${So(r.source)}|null)$`):void 0}),fe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),fu=w("$ZodDefault",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Xm(s,e)):Xm(o,e)}});pu=w("$ZodPrefault",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),mu=w("$ZodNonOptional",(t,e)=>{ue.init(t,e),fe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Ym(s,t)):Ym(o,t)}});hu=w("$ZodCatch",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"optout",()=>e.innerType._zod.optout),fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>xt(i,n,ot()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>xt(s,n,ot()))},input:r.value}),r.issues=[]),r)}}),gu=w("$ZodPipe",(t,e)=>{ue.init(t,e),fe(t._zod,"values",()=>e.in._zod.values),fe(t._zod,"optin",()=>e.in._zod.optin),fe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Qm(s,e,n)):Qm(o,e,n)}});yu=w("$ZodReadonly",(t,e)=>{ue.init(t,e),fe(t._zod,"propValues",()=>e.innerType._zod.propValues),fe(t._zod,"values",()=>e.innerType._zod.values),fe(t._zod,"optin",()=>e.innerType._zod.optin),fe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(eh):eh(o)}});_u=w("$ZodCustom",(t,e)=>{Pe.init(t,e),ue.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>th(s,r,n,t));th(o,r,n,t)}})});function ch(){return{localeError:d$()}}var l$,d$,uh=G(()=>{Ot();l$=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},d$=()=>{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 ${l$(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ls(n.values[0])}`:`Invalid option: expected one of ${Zs(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":""}: ${Zs(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 Gs=G(()=>{});function lh(){return new Po}var f$,p$,Po,fr,xu=G(()=>{f$=Symbol("ZodOutput"),p$=Symbol("ZodInput"),Po=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)}};fr=lh()});function bu(t,e){return new t({type:"string",...L(e)})}function wu(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...L(e)})}function Xs(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...L(e)})}function $u(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...L(e)})}function ku(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(e)})}function Su(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(e)})}function Tu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(e)})}function Eu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...L(e)})}function zu(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...L(e)})}function Ru(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(e)})}function Pu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...L(e)})}function Iu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(e)})}function Cu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...L(e)})}function Au(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...L(e)})}function Ou(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(e)})}function Nu(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(e)})}function Mu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(e)})}function ju(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(e)})}function Zu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(e)})}function Du(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...L(e)})}function Lu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...L(e)})}function qu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...L(e)})}function Uu(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...L(e)})}function dh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(e)})}function fh(t,e){return new t({type:"string",format:"date",check:"string_format",...L(e)})}function ph(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...L(e)})}function mh(t,e){return new t({type:"string",format:"duration",check:"string_format",...L(e)})}function Fu(t,e){return new t({type:"number",checks:[],...L(e)})}function Hu(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...L(e)})}function Bu(t,e){return new t({type:"boolean",...L(e)})}function Vu(t,e){return new t({type:"null",...L(e)})}function Ju(t){return new t({type:"unknown"})}function Wu(t,e){return new t({type:"never",...L(e)})}function Ys(t,e){return new zc({check:"less_than",...L(e),value:t,inclusive:!1})}function Io(t,e){return new zc({check:"less_than",...L(e),value:t,inclusive:!0})}function Qs(t,e){return new Rc({check:"greater_than",...L(e),value:t,inclusive:!1})}function Co(t,e){return new Rc({check:"greater_than",...L(e),value:t,inclusive:!0})}function ei(t,e){return new Am({check:"multiple_of",...L(e),value:t})}function ti(t,e){return new Nm({check:"max_length",...L(e),maximum:t})}function In(t,e){return new Mm({check:"min_length",...L(e),minimum:t})}function ri(t,e){return new jm({check:"length_equals",...L(e),length:t})}function Ku(t,e){return new Zm({check:"string_format",format:"regex",...L(e),pattern:t})}function Gu(t){return new Dm({check:"string_format",format:"lowercase",...L(t)})}function Xu(t){return new Lm({check:"string_format",format:"uppercase",...L(t)})}function Yu(t,e){return new qm({check:"string_format",format:"includes",...L(e),includes:t})}function Qu(t,e){return new Um({check:"string_format",format:"starts_with",...L(e),prefix:t})}function el(t,e){return new Fm({check:"string_format",format:"ends_with",...L(e),suffix:t})}function tn(t){return new Hm({check:"overwrite",tx:t})}function tl(t){return tn(e=>e.normalize(t))}function rl(){return tn(t=>t.trim())}function nl(){return tn(t=>t.toLowerCase())}function ol(){return tn(t=>t.toUpperCase())}function hh(t,e,r){return new t({type:"array",element:e,...L(r)})}function sl(t,e,r){let n=L(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function il(t,e,r){return new t({type:"custom",check:"custom",fn:e,...L(r)})}var gh=G(()=>{Hs();Ot()});var yh=G(()=>{});function al(t,e){if(t instanceof Po){let n=new ni(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 ni(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 ni,_h=G(()=>{xu();Ot();ni=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??fr,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:g,maximum:h,format:_,patterns:v,contentEncoding:y}=e._zod.bag;if(typeof g=="number"&&(f.minLength=g),typeof h=="number"&&(f.maxLength=h),_&&(f.format=s[_]??_,f.format===""&&delete f.format),y&&(f.contentEncoding=y),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=p,{minimum:g,maximum:h,format:_,multipleOf:v,exclusiveMaximum:y,exclusiveMinimum:x}=e._zod.bag;typeof _=="string"&&_.includes("int")?f.type="integer":f.type="number",typeof x=="number"&&(f.exclusiveMinimum=x),typeof g=="number"&&(f.minimum=g,typeof x=="number"&&(x>=g?delete f.minimum:delete f.exclusiveMinimum)),typeof y=="number"&&(f.exclusiveMaximum=y),typeof h=="number"&&(f.maximum=h,typeof y=="number"&&(y<=h?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:g,maximum:h}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof h=="number"&&(f.maxItems=h),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 g=o.shape;for(let v in g)f.properties[v]=this.process(g[v],{...d,path:[...d.path,"properties",v]});let h=new Set(Object.keys(g)),_=new Set([...h].filter(v=>{let y=o.shape[v]._zod;return this.io==="input"?y.optin===void 0:y.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((g,h)=>this.process(g,{...d,path:[...d.path,"anyOf",h]}));break}case"intersection":{let f=p,g=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),h=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),_=y=>"allOf"in y&&Object.keys(y).length===1,v=[..._(g)?g.allOf:[g],..._(h)?h.allOf:[h]];f.allOf=v;break}case"tuple":{let f=p;f.type="array";let g=o.items.map((v,y)=>this.process(v,{...d,path:[...d.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?f.prefixItems=g:f.items=g,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:h,maximum:_}=e._zod.bag;typeof h=="number"&&(f.minItems=h),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,g=wo(o.entries);g.every(h=>typeof h=="number")&&(f.type="number"),g.every(h=>typeof h=="string")&&(f.type="string"),f.enum=g;break}case"literal":{let f=p,g=[];for(let h of o.values)if(h===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof h=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(h))}else g.push(h);if(g.length!==0)if(g.length===1){let h=g[0];f.type=h===null?"null":typeof h,f.const=h}else g.every(h=>typeof h=="number")&&(f.type="number"),g.every(h=>typeof h=="string")&&(f.type="string"),g.every(h=>typeof h=="boolean")&&(f.type="string"),g.every(h=>h===null)&&(f.type="null"),f.enum=g;break}case"file":{let f=p,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:h,maximum:_,mime:v}=e._zod.bag;h!==void 0&&(g.minLength=h),_!==void 0&&(g.maxLength=_),v?v.length===1?(g.contentMediaType=v[0],Object.assign(f,g)):f.anyOf=v.map(y=>({...g,contentMediaType:y})):Object.assign(f,g);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,g=e._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=g.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"&&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 g=n.external.registry.get(l[0])?.id,h=n.external.uri??(v=>v);if(g)return{ref:h(g)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${h("__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 g in f)delete f[g];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 ? [${Yr(v)}, ...iss.path] : [${Yr(v)}]
|
|
28
|
+
})));`),m.write(`newResult[${Yr(v)}] = ${y}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let _=m.compile();return(v,y)=>_(d,v,y)},o,s=Pn,i=!Ds.jitless,c=i&&mc.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 y=l.shape;for(let x of l.keys){let $=y[x],O=$._zod.run({value:p[x],issues:[]},m),C=$._zod.optin==="optional"&&$._zod.optout==="optional";O instanceof Promise?f.push(O.then(ae=>C?Ym(ae,d,x,p):Ws(ae,d,x))):C?Ym(O,d,x,p):Ws(O,d,x)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let g=[],h=l.keySet,_=u._zod,v=_.def.type;for(let y of Object.keys(p)){if(h.has(y))continue;if(v==="never"){g.push(y);continue}let x=_.run({value:p[y],issues:[]},m);x instanceof Promise?f.push(x.then($=>Ws($,d,y))):Ws(x,d,y)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:p,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Xs=w("$ZodUnion",(t,e)=>{ue.init(t,e),fe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),fe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),fe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),fe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Eo(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=>Qm(i,r,t,n)):Qm(s,r,t,n)}}),au=w("$ZodDiscriminatedUnion",(t,e)=>{Xs.init(t,e);let r=t._zod.parse;fe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=So(()=>{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(!Pn(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)}}),cu=w("$ZodIntersection",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>eh(r,c,u)):eh(r,s,i)}});uu=w("$ZodRecord",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!In(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(...Ot(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Ot(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=>bt(u,n,ot())),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(...Ot(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Ot(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),lu=w("$ZodEnum",(t,e)=>{ue.init(t,e);let r=ko(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>hc.has(typeof n)).map(n=>typeof n=="string"?fr(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}}),du=w("$ZodLiteral",(t,e)=>{ue.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?fr(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}}),fu=w("$ZodTransform",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Gt;return r.value=o,r}}),pu=w("$ZodOptional",(t,e)=>{ue.init(t,e),t._zod.optin="optional",t._zod.optout="optional",fe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),fe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Eo(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)}),mu=w("$ZodNullable",(t,e)=>{ue.init(t,e),fe(t._zod,"optin",()=>e.innerType._zod.optin),fe(t._zod,"optout",()=>e.innerType._zod.optout),fe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Eo(r.source)}|null)$`):void 0}),fe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),hu=w("$ZodDefault",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>th(s,e)):th(o,e)}});gu=w("$ZodPrefault",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),yu=w("$ZodNonOptional",(t,e)=>{ue.init(t,e),fe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>rh(s,t)):rh(o,t)}});_u=w("$ZodCatch",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"optout",()=>e.innerType._zod.optout),fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>bt(i,n,ot()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>bt(s,n,ot()))},input:r.value}),r.issues=[]),r)}}),vu=w("$ZodPipe",(t,e)=>{ue.init(t,e),fe(t._zod,"values",()=>e.in._zod.values),fe(t._zod,"optin",()=>e.in._zod.optin),fe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>nh(s,e,n)):nh(o,e,n)}});xu=w("$ZodReadonly",(t,e)=>{ue.init(t,e),fe(t._zod,"propValues",()=>e.innerType._zod.propValues),fe(t._zod,"values",()=>e.innerType._zod.values),fe(t._zod,"optin",()=>e.innerType._zod.optin),fe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(oh):oh(o)}});bu=w("$ZodCustom",(t,e)=>{Pe.init(t,e),ue.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>sh(s,r,n,t));sh(o,r,n,t)}})});function fh(){return{localeError:g$()}}var h$,g$,ph=G(()=>{Nt();h$=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},g$=()=>{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 ${h$(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Us(n.values[0])}`:`Invalid option: expected one of ${Ls(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":""}: ${Ls(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 Ys=G(()=>{});function mh(){return new Co}var y$,_$,Co,pr,$u=G(()=>{y$=Symbol("ZodOutput"),_$=Symbol("ZodInput"),Co=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)}};pr=mh()});function ku(t,e){return new t({type:"string",...L(e)})}function Su(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...L(e)})}function Qs(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...L(e)})}function Tu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...L(e)})}function Eu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(e)})}function zu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(e)})}function Ru(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(e)})}function Pu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...L(e)})}function Iu(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...L(e)})}function Cu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(e)})}function Au(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...L(e)})}function Ou(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(e)})}function Nu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...L(e)})}function Mu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...L(e)})}function ju(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(e)})}function Zu(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(e)})}function Du(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(e)})}function Lu(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(e)})}function qu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(e)})}function Uu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...L(e)})}function Fu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...L(e)})}function Hu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...L(e)})}function Bu(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...L(e)})}function hh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(e)})}function gh(t,e){return new t({type:"string",format:"date",check:"string_format",...L(e)})}function yh(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...L(e)})}function _h(t,e){return new t({type:"string",format:"duration",check:"string_format",...L(e)})}function Vu(t,e){return new t({type:"number",checks:[],...L(e)})}function Ju(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...L(e)})}function Wu(t,e){return new t({type:"boolean",...L(e)})}function Ku(t,e){return new t({type:"null",...L(e)})}function Gu(t){return new t({type:"unknown"})}function Xu(t,e){return new t({type:"never",...L(e)})}function ei(t,e){return new Ic({check:"less_than",...L(e),value:t,inclusive:!1})}function Ao(t,e){return new Ic({check:"less_than",...L(e),value:t,inclusive:!0})}function ti(t,e){return new Cc({check:"greater_than",...L(e),value:t,inclusive:!1})}function Oo(t,e){return new Cc({check:"greater_than",...L(e),value:t,inclusive:!0})}function ri(t,e){return new jm({check:"multiple_of",...L(e),value:t})}function ni(t,e){return new Dm({check:"max_length",...L(e),maximum:t})}function Cn(t,e){return new Lm({check:"min_length",...L(e),minimum:t})}function oi(t,e){return new qm({check:"length_equals",...L(e),length:t})}function Yu(t,e){return new Um({check:"string_format",format:"regex",...L(e),pattern:t})}function Qu(t){return new Fm({check:"string_format",format:"lowercase",...L(t)})}function el(t){return new Hm({check:"string_format",format:"uppercase",...L(t)})}function tl(t,e){return new Bm({check:"string_format",format:"includes",...L(e),includes:t})}function rl(t,e){return new Vm({check:"string_format",format:"starts_with",...L(e),prefix:t})}function nl(t,e){return new Jm({check:"string_format",format:"ends_with",...L(e),suffix:t})}function rn(t){return new Wm({check:"overwrite",tx:t})}function ol(t){return rn(e=>e.normalize(t))}function sl(){return rn(t=>t.trim())}function il(){return rn(t=>t.toLowerCase())}function al(){return rn(t=>t.toUpperCase())}function vh(t,e,r){return new t({type:"array",element:e,...L(r)})}function cl(t,e,r){let n=L(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function ul(t,e,r){return new t({type:"custom",check:"custom",fn:e,...L(r)})}var xh=G(()=>{Vs();Nt()});var bh=G(()=>{});function ll(t,e){if(t instanceof Co){let n=new si(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 si(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 si,wh=G(()=>{$u();Nt();si=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??pr,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:g,maximum:h,format:_,patterns:v,contentEncoding:y}=e._zod.bag;if(typeof g=="number"&&(f.minLength=g),typeof h=="number"&&(f.maxLength=h),_&&(f.format=s[_]??_,f.format===""&&delete f.format),y&&(f.contentEncoding=y),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=p,{minimum:g,maximum:h,format:_,multipleOf:v,exclusiveMaximum:y,exclusiveMinimum:x}=e._zod.bag;typeof _=="string"&&_.includes("int")?f.type="integer":f.type="number",typeof x=="number"&&(f.exclusiveMinimum=x),typeof g=="number"&&(f.minimum=g,typeof x=="number"&&(x>=g?delete f.minimum:delete f.exclusiveMinimum)),typeof y=="number"&&(f.exclusiveMaximum=y),typeof h=="number"&&(f.maximum=h,typeof y=="number"&&(y<=h?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:g,maximum:h}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof h=="number"&&(f.maxItems=h),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 g=o.shape;for(let v in g)f.properties[v]=this.process(g[v],{...d,path:[...d.path,"properties",v]});let h=new Set(Object.keys(g)),_=new Set([...h].filter(v=>{let y=o.shape[v]._zod;return this.io==="input"?y.optin===void 0:y.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((g,h)=>this.process(g,{...d,path:[...d.path,"anyOf",h]}));break}case"intersection":{let f=p,g=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),h=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),_=y=>"allOf"in y&&Object.keys(y).length===1,v=[..._(g)?g.allOf:[g],..._(h)?h.allOf:[h]];f.allOf=v;break}case"tuple":{let f=p;f.type="array";let g=o.items.map((v,y)=>this.process(v,{...d,path:[...d.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?f.prefixItems=g:f.items=g,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:h,maximum:_}=e._zod.bag;typeof h=="number"&&(f.minItems=h),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,g=ko(o.entries);g.every(h=>typeof h=="number")&&(f.type="number"),g.every(h=>typeof h=="string")&&(f.type="string"),f.enum=g;break}case"literal":{let f=p,g=[];for(let h of o.values)if(h===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof h=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(h))}else g.push(h);if(g.length!==0)if(g.length===1){let h=g[0];f.type=h===null?"null":typeof h,f.const=h}else g.every(h=>typeof h=="number")&&(f.type="number"),g.every(h=>typeof h=="string")&&(f.type="string"),g.every(h=>typeof h=="boolean")&&(f.type="string"),g.every(h=>h===null)&&(f.type="null"),f.enum=g;break}case"file":{let f=p,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:h,maximum:_,mime:v}=e._zod.bag;h!==void 0&&(g.minLength=h),_!==void 0&&(g.maxLength=_),v?v.length===1?(g.contentMediaType=v[0],Object.assign(f,g)):f.anyOf=v.map(y=>({...g,contentMediaType:y})):Object.assign(f,g);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,g=e._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=g.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"&&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 g=n.external.registry.get(l[0])?.id,h=n.external.uri??(v=>v);if(g)return{ref:h(g)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${h("__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 g in f)delete f[g];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>
|
|
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 g=m.ref;if(m.ref=null,g){a(g,d);let h=this.seen.get(g).schema;h.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(h)):(Object.assign(p,h),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 vh=G(()=>{});var Ue=G(()=>{zn();Sc();_c();ah();Hs();Ic();Ot();Fs();Gs();xu();Pc();yh();gh();_h();vh()});var ul=G(()=>{Ue()});var Ao={};yo(Ao,{ZodISODate:()=>$h,ZodISODateTime:()=>wh,ZodISODuration:()=>Sh,ZodISOTime:()=>kh,date:()=>dl,datetime:()=>ll,duration:()=>pl,time:()=>fl});function ll(t){return dh(wh,t)}function dl(t){return fh($h,t)}function fl(t){return ph(kh,t)}function pl(t){return mh(Sh,t)}var wh,$h,kh,Sh,ml=G(()=>{Ue();hl();wh=w("ZodISODateTime",(t,e)=>{rh.init(t,e),ve.init(t,e)});$h=w("ZodISODate",(t,e)=>{nh.init(t,e),ve.init(t,e)});kh=w("ZodISOTime",(t,e)=>{oh.init(t,e),ve.init(t,e)});Sh=w("ZodISODuration",(t,e)=>{sh.init(t,e),ve.init(t,e)})});var Th,Sj,Oo,gl=G(()=>{Ue();Ue();Th=(t,e)=>{qs.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>yc(t,r)},flatten:{value:r=>gc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},Sj=w("ZodError",Th),Oo=w("ZodError",Th,{Parent:Error})});var Eh,zh,Rh,Ph,yl=G(()=>{Ue();gl();Eh=vc(Oo),zh=bc(Oo),Rh=$c(Oo),Ph=kc(Oo)});function b(t){return bu(sk,t)}function se(t){return Fu(Nh,t)}function Ch(t){return Hu($k,t)}function ze(t){return Bu(kk,t)}function Mh(t){return Vu(Sk,t)}function xe(){return Ju(Tk)}function zk(t){return Wu(Ek,t)}function Q(t,e){return hh(Rk,t,e)}function P(t,e){let r={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new jh(r)}function Fe(t,e){return new jh({type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},catchall:xe(),...Y.normalizeParams(e)})}function he(t,e){return new Zh({type:"union",options:t,...Y.normalizeParams(e)})}function xl(t,e,r){return new Pk({type:"union",options:e,discriminator:t,...Y.normalizeParams(r)})}function ai(t,e){return new Ik({type:"intersection",left:t,right:e})}function me(t,e,r){return new Ck({type:"record",keyType:t,valueType:e,...Y.normalizeParams(r)})}function Xe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new _l({type:"enum",entries:r,...Y.normalizeParams(e)})}function M(t,e){return new Ak({type:"literal",values:Array.isArray(t)?t:[t],...Y.normalizeParams(e)})}function Dh(t){return new Ok({type:"transform",transform:t})}function be(t){return new Lh({type:"optional",innerType:t})}function Ah(t){return new Nk({type:"nullable",innerType:t})}function jk(t,e){return new Mk({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Dk(t,e){return new Zk({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Lk(t,e){return new qh({type:"nonoptional",innerType:t,...Y.normalizeParams(e)})}function Uk(t,e){return new qk({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function vl(t,e){return new Fk({type:"pipe",in:t,out:e})}function Bk(t){return new Hk({type:"readonly",innerType:t})}function Vk(t){let e=new Pe({check:"custom"});return e._zod.check=t,e}function Fh(t,e){return sl(Uh,t??(()=>!0),e)}function Jk(t,e={}){return il(Uh,t,e)}function Wk(t){let e=Vk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Y.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(Y.issue(o))}},t(r.value,r)));return e}function bl(t,e){return vl(Dh(t),e)}var $e,Oh,sk,ve,ik,Ih,ii,ak,ck,uk,lk,dk,fk,pk,mk,hk,gk,yk,_k,vk,xk,bk,wk,Nh,$k,kk,Sk,Tk,Ek,Rk,jh,Zh,Pk,Ik,Ck,_l,Ak,Ok,Lh,Nk,Mk,Zk,qh,qk,Fk,Hk,Uh,hl=G(()=>{Ue();Ue();ul();ml();yl();$e=w("ZodType",(t,e)=>(ue.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>st(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Eh(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Rh(t,r,n),t.parseAsync=async(r,n)=>zh(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ph(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(Jk(r,n)),t.superRefine=r=>t.check(Wk(r)),t.overwrite=r=>t.check(tn(r)),t.optional=()=>be(t),t.nullable=()=>Ah(t),t.nullish=()=>be(Ah(t)),t.nonoptional=r=>Lk(t,r),t.array=()=>Q(t),t.or=r=>he([t,r]),t.and=r=>ai(t,r),t.transform=r=>vl(t,Dh(r)),t.default=r=>jk(t,r),t.prefault=r=>Dk(t,r),t.catch=r=>Uk(t,r),t.pipe=r=>vl(t,r),t.readonly=()=>Bk(t),t.describe=r=>{let n=t.clone();return fr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return fr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return fr.get(t);let n=t.clone();return fr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Oh=w("_ZodString",(t,e)=>{Ro.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(Ku(...n)),t.includes=(...n)=>t.check(Yu(...n)),t.startsWith=(...n)=>t.check(Qu(...n)),t.endsWith=(...n)=>t.check(el(...n)),t.min=(...n)=>t.check(In(...n)),t.max=(...n)=>t.check(ti(...n)),t.length=(...n)=>t.check(ri(...n)),t.nonempty=(...n)=>t.check(In(1,...n)),t.lowercase=n=>t.check(Gu(n)),t.uppercase=n=>t.check(Xu(n)),t.trim=()=>t.check(rl()),t.normalize=(...n)=>t.check(tl(...n)),t.toLowerCase=()=>t.check(nl()),t.toUpperCase=()=>t.check(ol())}),sk=w("ZodString",(t,e)=>{Ro.init(t,e),Oh.init(t,e),t.email=r=>t.check(wu(ik,r)),t.url=r=>t.check(Eu(ak,r)),t.jwt=r=>t.check(Uu(wk,r)),t.emoji=r=>t.check(zu(ck,r)),t.guid=r=>t.check(Xs(Ih,r)),t.uuid=r=>t.check($u(ii,r)),t.uuidv4=r=>t.check(ku(ii,r)),t.uuidv6=r=>t.check(Su(ii,r)),t.uuidv7=r=>t.check(Tu(ii,r)),t.nanoid=r=>t.check(Ru(uk,r)),t.guid=r=>t.check(Xs(Ih,r)),t.cuid=r=>t.check(Pu(lk,r)),t.cuid2=r=>t.check(Iu(dk,r)),t.ulid=r=>t.check(Cu(fk,r)),t.base64=r=>t.check(Du(vk,r)),t.base64url=r=>t.check(Lu(xk,r)),t.xid=r=>t.check(Au(pk,r)),t.ksuid=r=>t.check(Ou(mk,r)),t.ipv4=r=>t.check(Nu(hk,r)),t.ipv6=r=>t.check(Mu(gk,r)),t.cidrv4=r=>t.check(ju(yk,r)),t.cidrv6=r=>t.check(Zu(_k,r)),t.e164=r=>t.check(qu(bk,r)),t.datetime=r=>t.check(ll(r)),t.date=r=>t.check(dl(r)),t.time=r=>t.check(fl(r)),t.duration=r=>t.check(pl(r))});ve=w("ZodStringFormat",(t,e)=>{pe.init(t,e),Oh.init(t,e)}),ik=w("ZodEmail",(t,e)=>{Nc.init(t,e),ve.init(t,e)}),Ih=w("ZodGUID",(t,e)=>{Ac.init(t,e),ve.init(t,e)}),ii=w("ZodUUID",(t,e)=>{Oc.init(t,e),ve.init(t,e)}),ak=w("ZodURL",(t,e)=>{Mc.init(t,e),ve.init(t,e)}),ck=w("ZodEmoji",(t,e)=>{jc.init(t,e),ve.init(t,e)}),uk=w("ZodNanoID",(t,e)=>{Zc.init(t,e),ve.init(t,e)}),lk=w("ZodCUID",(t,e)=>{Dc.init(t,e),ve.init(t,e)}),dk=w("ZodCUID2",(t,e)=>{Lc.init(t,e),ve.init(t,e)}),fk=w("ZodULID",(t,e)=>{qc.init(t,e),ve.init(t,e)}),pk=w("ZodXID",(t,e)=>{Uc.init(t,e),ve.init(t,e)}),mk=w("ZodKSUID",(t,e)=>{Fc.init(t,e),ve.init(t,e)}),hk=w("ZodIPv4",(t,e)=>{Hc.init(t,e),ve.init(t,e)}),gk=w("ZodIPv6",(t,e)=>{Bc.init(t,e),ve.init(t,e)}),yk=w("ZodCIDRv4",(t,e)=>{Vc.init(t,e),ve.init(t,e)}),_k=w("ZodCIDRv6",(t,e)=>{Jc.init(t,e),ve.init(t,e)}),vk=w("ZodBase64",(t,e)=>{Wc.init(t,e),ve.init(t,e)}),xk=w("ZodBase64URL",(t,e)=>{Kc.init(t,e),ve.init(t,e)}),bk=w("ZodE164",(t,e)=>{Gc.init(t,e),ve.init(t,e)}),wk=w("ZodJWT",(t,e)=>{Xc.init(t,e),ve.init(t,e)}),Nh=w("ZodNumber",(t,e)=>{Js.init(t,e),$e.init(t,e),t.gt=(n,o)=>t.check(Qs(n,o)),t.gte=(n,o)=>t.check(Co(n,o)),t.min=(n,o)=>t.check(Co(n,o)),t.lt=(n,o)=>t.check(Ys(n,o)),t.lte=(n,o)=>t.check(Io(n,o)),t.max=(n,o)=>t.check(Io(n,o)),t.int=n=>t.check(Ch(n)),t.safe=n=>t.check(Ch(n)),t.positive=n=>t.check(Qs(0,n)),t.nonnegative=n=>t.check(Co(0,n)),t.negative=n=>t.check(Ys(0,n)),t.nonpositive=n=>t.check(Io(0,n)),t.multipleOf=(n,o)=>t.check(ei(n,o)),t.step=(n,o)=>t.check(ei(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});$k=w("ZodNumberFormat",(t,e)=>{Yc.init(t,e),Nh.init(t,e)});kk=w("ZodBoolean",(t,e)=>{Qc.init(t,e),$e.init(t,e)});Sk=w("ZodNull",(t,e)=>{eu.init(t,e),$e.init(t,e)});Tk=w("ZodUnknown",(t,e)=>{tu.init(t,e),$e.init(t,e)});Ek=w("ZodNever",(t,e)=>{ru.init(t,e),$e.init(t,e)});Rk=w("ZodArray",(t,e)=>{nu.init(t,e),$e.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(In(r,n)),t.nonempty=r=>t.check(In(1,r)),t.max=(r,n)=>t.check(ti(r,n)),t.length=(r,n)=>t.check(ri(r,n)),t.unwrap=()=>t.element});jh=w("ZodObject",(t,e)=>{Ws.init(t,e),$e.init(t,e),Y.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Xe(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:zk()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>Y.extend(t,r),t.merge=r=>Y.merge(t,r),t.pick=r=>Y.pick(t,r),t.omit=r=>Y.omit(t,r),t.partial=(...r)=>Y.partial(Lh,t,r[0]),t.required=(...r)=>Y.required(qh,t,r[0])});Zh=w("ZodUnion",(t,e)=>{Ks.init(t,e),$e.init(t,e),t.options=e.options});Pk=w("ZodDiscriminatedUnion",(t,e)=>{Zh.init(t,e),ou.init(t,e)});Ik=w("ZodIntersection",(t,e)=>{su.init(t,e),$e.init(t,e)});Ck=w("ZodRecord",(t,e)=>{iu.init(t,e),$e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});_l=w("ZodEnum",(t,e)=>{au.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 _l({...e,checks:[],...Y.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 _l({...e,checks:[],...Y.normalizeParams(o),entries:s})}});Ak=w("ZodLiteral",(t,e)=>{cu.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]}})});Ok=w("ZodTransform",(t,e)=>{uu.init(t,e),$e.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Y.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(Y.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Lh=w("ZodOptional",(t,e)=>{lu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Nk=w("ZodNullable",(t,e)=>{du.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Mk=w("ZodDefault",(t,e)=>{fu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});Zk=w("ZodPrefault",(t,e)=>{pu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});qh=w("ZodNonOptional",(t,e)=>{mu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});qk=w("ZodCatch",(t,e)=>{hu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Fk=w("ZodPipe",(t,e)=>{gu.init(t,e),$e.init(t,e),t.in=e.in,t.out=e.out});Hk=w("ZodReadonly",(t,e)=>{yu.init(t,e),$e.init(t,e)});Uh=w("ZodCustom",(t,e)=>{_u.init(t,e),$e.init(t,e)})});var Hh=G(()=>{});var Bh=G(()=>{});var Vh=G(()=>{Ue();hl();ul();gl();yl();Hh();Ue();uh();Gs();ml();Bh();ot(ch())});var Jh=G(()=>{Vh()});var Wh=G(()=>{Jh()});function ug(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function lg(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var $l,Kh,Nn,hr,ui,Te,Gh,Xh,qj,Xk,Yk,kl,it,No,Yh,Ie,ut,lt,Ce,li,Qh,Gt,eg,tg,Sl,Xt,A,Tl,Mn,Mo,Uj,di,Qk,fi,eS,jo,On,rg,tS,rS,nS,oS,sS,iS,pi,El,aS,cS,zl,mi,uS,lS,hi,dS,Zo,Do,fS,Lo,jn,pS,qo,gi,yi,_i,Fj,vi,xi,bi,ng,og,sg,Rl,ig,Uo,Zn,ag,mS,wi,hS,$i,gS,Pl,yS,ki,_S,vS,xS,bS,wS,$S,kS,SS,TS,ES,Si,zS,RS,Ti,Il,Cl,Al,PS,IS,CS,Ol,AS,OS,NS,MS,jS,cg,Ei,ZS,zi,Hj,DS,Dn,LS,Bj,Fo,qS,Nl,US,FS,HS,BS,VS,JS,WS,ci,KS,GS,XS,Ho,Ml,YS,QS,eT,tT,rT,nT,oT,sT,iT,aT,cT,uT,lT,dT,fT,pT,mT,hT,Ln,gT,yT,_T,Ri,vT,xT,bT,jl,wT,Vj,Jj,Wj,Kj,Gj,Xj,I,wl,gr=G(()=>{Wh();$l="2025-11-25",Kh="2025-03-26",Nn=[$l,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],hr="io.modelcontextprotocol/related-task",ui="2.0",Te=Fh(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Gh=he([b(),se().int()]),Xh=b(),qj=Fe({ttl:se().optional(),pollInterval:se().optional()}),Xk=P({ttl:se().optional()}),Yk=P({taskId:b()}),kl=Fe({progressToken:Gh.optional(),[hr]:Yk.optional()}),it=P({_meta:kl.optional()}),No=it.extend({task:Xk.optional()}),Yh=t=>No.safeParse(t).success,Ie=P({method:b(),params:it.loose().optional()}),ut=P({_meta:kl.optional()}),lt=P({method:b(),params:ut.loose().optional()}),Ce=Fe({_meta:kl.optional()}),li=he([b(),se().int()]),Qh=P({jsonrpc:M(ui),id:li,...Ie.shape}).strict(),Gt=t=>Qh.safeParse(t).success,eg=P({jsonrpc:M(ui),...lt.shape}).strict(),tg=t=>eg.safeParse(t).success,Sl=P({jsonrpc:M(ui),id:li,result:Ce}).strict(),Xt=t=>Sl.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={}));Tl=P({jsonrpc:M(ui),id:li.optional(),error:P({code:se().int(),message:b(),data:xe().optional()})}).strict(),Mn=t=>Tl.safeParse(t).success,Mo=he([Qh,eg,Sl,Tl]),Uj=he([Sl,Tl]),di=Ce.strict(),Qk=ut.extend({requestId:li.optional(),reason:b().optional()}),fi=lt.extend({method:M("notifications/cancelled"),params:Qk}),eS=P({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Xe(["light","dark"]).optional()}),jo=P({icons:Q(eS).optional()}),On=P({name:b(),title:b().optional()}),rg=On.extend({...On.shape,...jo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),tS=ai(P({applyDefaults:ze().optional()}),me(b(),xe())),rS=bl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ai(P({form:tS.optional(),url:Te.optional()}),me(b(),xe()).optional())),nS=Fe({list:Te.optional(),cancel:Te.optional(),requests:Fe({sampling:Fe({createMessage:Te.optional()}).optional(),elicitation:Fe({create:Te.optional()}).optional()}).optional()}),oS=Fe({list:Te.optional(),cancel:Te.optional(),requests:Fe({tools:Fe({call:Te.optional()}).optional()}).optional()}),sS=P({experimental:me(b(),Te).optional(),sampling:P({context:Te.optional(),tools:Te.optional()}).optional(),elicitation:rS.optional(),roots:P({listChanged:ze().optional()}).optional(),tasks:nS.optional(),extensions:me(b(),Te).optional()}),iS=it.extend({protocolVersion:b(),capabilities:sS,clientInfo:rg}),pi=Ie.extend({method:M("initialize"),params:iS}),El=t=>pi.safeParse(t).success,aS=P({experimental:me(b(),Te).optional(),logging:Te.optional(),completions:Te.optional(),prompts:P({listChanged:ze().optional()}).optional(),resources:P({subscribe:ze().optional(),listChanged:ze().optional()}).optional(),tools:P({listChanged:ze().optional()}).optional(),tasks:oS.optional(),extensions:me(b(),Te).optional()}),cS=Ce.extend({protocolVersion:b(),capabilities:aS,serverInfo:rg,instructions:b().optional()}),zl=lt.extend({method:M("notifications/initialized"),params:ut.optional()}),mi=Ie.extend({method:M("ping"),params:it.optional()}),uS=P({progress:se(),total:be(se()),message:be(b())}),lS=P({...ut.shape,...uS.shape,progressToken:Gh}),hi=lt.extend({method:M("notifications/progress"),params:lS}),dS=it.extend({cursor:Xh.optional()}),Zo=Ie.extend({params:dS.optional()}),Do=Ce.extend({nextCursor:Xh.optional()}),fS=Xe(["working","input_required","completed","failed","cancelled"]),Lo=P({taskId:b(),status:fS,ttl:he([se(),Mh()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:be(se()),statusMessage:be(b())}),jn=Ce.extend({task:Lo}),pS=ut.merge(Lo),qo=lt.extend({method:M("notifications/tasks/status"),params:pS}),gi=Ie.extend({method:M("tasks/get"),params:it.extend({taskId:b()})}),yi=Ce.merge(Lo),_i=Ie.extend({method:M("tasks/result"),params:it.extend({taskId:b()})}),Fj=Ce.loose(),vi=Zo.extend({method:M("tasks/list")}),xi=Do.extend({tasks:Q(Lo)}),bi=Ie.extend({method:M("tasks/cancel"),params:it.extend({taskId:b()})}),ng=Ce.merge(Lo),og=P({uri:b(),mimeType:be(b()),_meta:me(b(),xe()).optional()}),sg=og.extend({text:b()}),Rl=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ig=og.extend({blob:Rl}),Uo=Xe(["user","assistant"]),Zn=P({audience:Q(Uo).optional(),priority:se().min(0).max(1).optional(),lastModified:Ao.datetime({offset:!0}).optional()}),ag=P({...On.shape,...jo.shape,uri:b(),description:be(b()),mimeType:be(b()),size:be(se()),annotations:Zn.optional(),_meta:be(Fe({}))}),mS=P({...On.shape,...jo.shape,uriTemplate:b(),description:be(b()),mimeType:be(b()),annotations:Zn.optional(),_meta:be(Fe({}))}),wi=Zo.extend({method:M("resources/list")}),hS=Do.extend({resources:Q(ag)}),$i=Zo.extend({method:M("resources/templates/list")}),gS=Do.extend({resourceTemplates:Q(mS)}),Pl=it.extend({uri:b()}),yS=Pl,ki=Ie.extend({method:M("resources/read"),params:yS}),_S=Ce.extend({contents:Q(he([sg,ig]))}),vS=lt.extend({method:M("notifications/resources/list_changed"),params:ut.optional()}),xS=Pl,bS=Ie.extend({method:M("resources/subscribe"),params:xS}),wS=Pl,$S=Ie.extend({method:M("resources/unsubscribe"),params:wS}),kS=ut.extend({uri:b()}),SS=lt.extend({method:M("notifications/resources/updated"),params:kS}),TS=P({name:b(),description:be(b()),required:be(ze())}),ES=P({...On.shape,...jo.shape,description:be(b()),arguments:be(Q(TS)),_meta:be(Fe({}))}),Si=Zo.extend({method:M("prompts/list")}),zS=Do.extend({prompts:Q(ES)}),RS=it.extend({name:b(),arguments:me(b(),b()).optional()}),Ti=Ie.extend({method:M("prompts/get"),params:RS}),Il=P({type:M("text"),text:b(),annotations:Zn.optional(),_meta:me(b(),xe()).optional()}),Cl=P({type:M("image"),data:Rl,mimeType:b(),annotations:Zn.optional(),_meta:me(b(),xe()).optional()}),Al=P({type:M("audio"),data:Rl,mimeType:b(),annotations:Zn.optional(),_meta:me(b(),xe()).optional()}),PS=P({type:M("tool_use"),name:b(),id:b(),input:me(b(),xe()),_meta:me(b(),xe()).optional()}),IS=P({type:M("resource"),resource:he([sg,ig]),annotations:Zn.optional(),_meta:me(b(),xe()).optional()}),CS=ag.extend({type:M("resource_link")}),Ol=he([Il,Cl,Al,CS,IS]),AS=P({role:Uo,content:Ol}),OS=Ce.extend({description:b().optional(),messages:Q(AS)}),NS=lt.extend({method:M("notifications/prompts/list_changed"),params:ut.optional()}),MS=P({title:b().optional(),readOnlyHint:ze().optional(),destructiveHint:ze().optional(),idempotentHint:ze().optional(),openWorldHint:ze().optional()}),jS=P({taskSupport:Xe(["required","optional","forbidden"]).optional()}),cg=P({...On.shape,...jo.shape,description:b().optional(),inputSchema:P({type:M("object"),properties:me(b(),Te).optional(),required:Q(b()).optional()}).catchall(xe()),outputSchema:P({type:M("object"),properties:me(b(),Te).optional(),required:Q(b()).optional()}).catchall(xe()).optional(),annotations:MS.optional(),execution:jS.optional(),_meta:me(b(),xe()).optional()}),Ei=Zo.extend({method:M("tools/list")}),ZS=Do.extend({tools:Q(cg)}),zi=Ce.extend({content:Q(Ol).default([]),structuredContent:me(b(),xe()).optional(),isError:ze().optional()}),Hj=zi.or(Ce.extend({toolResult:xe()})),DS=No.extend({name:b(),arguments:me(b(),xe()).optional()}),Dn=Ie.extend({method:M("tools/call"),params:DS}),LS=lt.extend({method:M("notifications/tools/list_changed"),params:ut.optional()}),Bj=P({autoRefresh:ze().default(!0),debounceMs:se().int().nonnegative().default(300)}),Fo=Xe(["debug","info","notice","warning","error","critical","alert","emergency"]),qS=it.extend({level:Fo}),Nl=Ie.extend({method:M("logging/setLevel"),params:qS}),US=ut.extend({level:Fo,logger:b().optional(),data:xe()}),FS=lt.extend({method:M("notifications/message"),params:US}),HS=P({name:b().optional()}),BS=P({hints:Q(HS).optional(),costPriority:se().min(0).max(1).optional(),speedPriority:se().min(0).max(1).optional(),intelligencePriority:se().min(0).max(1).optional()}),VS=P({mode:Xe(["auto","required","none"]).optional()}),JS=P({type:M("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q(Ol).default([]),structuredContent:P({}).loose().optional(),isError:ze().optional(),_meta:me(b(),xe()).optional()}),WS=xl("type",[Il,Cl,Al]),ci=xl("type",[Il,Cl,Al,PS,JS]),KS=P({role:Uo,content:he([ci,Q(ci)]),_meta:me(b(),xe()).optional()}),GS=No.extend({messages:Q(KS),modelPreferences:BS.optional(),systemPrompt:b().optional(),includeContext:Xe(["none","thisServer","allServers"]).optional(),temperature:se().optional(),maxTokens:se().int(),stopSequences:Q(b()).optional(),metadata:Te.optional(),tools:Q(cg).optional(),toolChoice:VS.optional()}),XS=Ie.extend({method:M("sampling/createMessage"),params:GS}),Ho=Ce.extend({model:b(),stopReason:be(Xe(["endTurn","stopSequence","maxTokens"]).or(b())),role:Uo,content:WS}),Ml=Ce.extend({model:b(),stopReason:be(Xe(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Uo,content:he([ci,Q(ci)])}),YS=P({type:M("boolean"),title:b().optional(),description:b().optional(),default:ze().optional()}),QS=P({type:M("string"),title:b().optional(),description:b().optional(),minLength:se().optional(),maxLength:se().optional(),format:Xe(["email","uri","date","date-time"]).optional(),default:b().optional()}),eT=P({type:Xe(["number","integer"]),title:b().optional(),description:b().optional(),minimum:se().optional(),maximum:se().optional(),default:se().optional()}),tT=P({type:M("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),rT=P({type:M("string"),title:b().optional(),description:b().optional(),oneOf:Q(P({const:b(),title:b()})),default:b().optional()}),nT=P({type:M("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),oT=he([tT,rT]),sT=P({type:M("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({type:M("string"),enum:Q(b())}),default:Q(b()).optional()}),iT=P({type:M("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({anyOf:Q(P({const:b(),title:b()}))}),default:Q(b()).optional()}),aT=he([sT,iT]),cT=he([nT,oT,aT]),uT=he([cT,YS,QS,eT]),lT=No.extend({mode:M("form").optional(),message:b(),requestedSchema:P({type:M("object"),properties:me(b(),uT),required:Q(b()).optional()})}),dT=No.extend({mode:M("url"),message:b(),elicitationId:b(),url:b().url()}),fT=he([lT,dT]),pT=Ie.extend({method:M("elicitation/create"),params:fT}),mT=ut.extend({elicitationId:b()}),hT=lt.extend({method:M("notifications/elicitation/complete"),params:mT}),Ln=Ce.extend({action:Xe(["accept","decline","cancel"]),content:bl(t=>t===null?void 0:t,me(b(),he([b(),se(),ze(),Q(b())])).optional())}),gT=P({type:M("ref/resource"),uri:b()}),yT=P({type:M("ref/prompt"),name:b()}),_T=it.extend({ref:he([yT,gT]),argument:P({name:b(),value:b()}),context:P({arguments:me(b(),b()).optional()}).optional()}),Ri=Ie.extend({method:M("completion/complete"),params:_T});vT=Ce.extend({completion:Fe({values:Q(b()).max(100),total:be(se().int()),hasMore:be(ze())})}),xT=P({uri:b().startsWith("file://"),name:b().optional(),_meta:me(b(),xe()).optional()}),bT=Ie.extend({method:M("roots/list"),params:it.optional()}),jl=Ce.extend({roots:Q(xT)}),wT=lt.extend({method:M("notifications/roots/list_changed"),params:ut.optional()}),Vj=he([mi,pi,Ri,Nl,Ti,Si,wi,$i,ki,bS,$S,Dn,Ei,gi,_i,vi,bi]),Jj=he([fi,hi,zl,wT,qo]),Wj=he([di,Ho,Ml,Ln,jl,yi,xi,jn]),Kj=he([mi,XS,pT,bT,gi,_i,vi,bi]),Gj=he([fi,hi,FS,SS,vS,LS,NS,qo,hT]),Xj=he([di,cS,vT,OS,zS,hS,gS,_S,zi,ZS,yi,xi,jn]),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 wl(o.elicitations,r)}return new t(e,r,n)}},wl=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 Wo=E(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 Vo=class{};oe._CodeOrName=Vo;oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var on=class extends Vo{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=on;var dt=class extends Vo{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 on&&(r[n.str]=(r[n.str]||0)+1),r),{})}};oe._Code=dt;oe.nil=new dt("");function Bg(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Jl(r,e[n]),r.push(t[++n]);return new dt(r)}oe._=Bg;var Vl=new dt("+");function Vg(t,...e){let r=[Jo(t[0])],n=0;for(;n<e.length;)r.push(Vl),Jl(r,e[n]),r.push(Vl,Jo(t[++n]));return AT(r),new dt(r)}oe.str=Vg;function Jl(t,e){e instanceof dt?t.push(...e._items):e instanceof on?t.push(e):t.push(MT(e))}oe.addCodeArg=Jl;function AT(t){let e=1;for(;e<t.length-1;){if(t[e]===Vl){let r=OT(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function OT(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof on||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 on))return`"${t}${e.slice(1)}`}function NT(t,e){return e.emptyStr()?t:t.emptyStr()?e:Vg`${t}${e}`}oe.strConcat=NT;function MT(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Jo(Array.isArray(t)?t.join(","):t)}function jT(t){return new dt(Jo(t))}oe.stringify=jT;function Jo(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oe.safeStringify=Jo;function ZT(t){return typeof t=="string"&&oe.IDENTIFIER.test(t)?new dt(`.${t}`):Bg`[${t}]`}oe.getProperty=ZT;function DT(t){if(typeof t=="string"&&oe.IDENTIFIER.test(t))return new dt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}oe.getEsmExportName=DT;function LT(t){return new dt(t.toString())}oe.regexpCode=LT});var Gl=E(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ye=Wo(),Wl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ni;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ni||(Qe.UsedValueState=Ni={}));Qe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Mi=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.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}}};Qe.Scope=Mi;var ji=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Qe.ValueScopeName=ji;var qT=(0,Ye._)`\n`,Kl=class extends Mi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?qT:Ye.nil}}get(){return this._scope}name(e){return new ji(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,Ye._)`${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=Ye.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,Ni.Started);let l=r(u);if(l){let d=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ye._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ye._)`${s}${l}${this.opts._n}`;else throw new Wl(u);c.set(u,Ni.Completed)})}return s}};Qe.ValueScope=Kl});var J=E(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.or=W.and=W.not=W.CodeGen=W.operators=W.varKinds=W.ValueScopeName=W.ValueScope=W.Scope=W.Name=W.regexpCode=W.stringify=W.getProperty=W.nil=W.strConcat=W.str=W._=void 0;var te=Wo(),$t=Gl(),_r=Wo();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return _r._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return _r.str}});Object.defineProperty(W,"strConcat",{enumerable:!0,get:function(){return _r.strConcat}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return _r.nil}});Object.defineProperty(W,"getProperty",{enumerable:!0,get:function(){return _r.getProperty}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return _r.stringify}});Object.defineProperty(W,"regexpCode",{enumerable:!0,get:function(){return _r.regexpCode}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return _r.Name}});var qi=Gl();Object.defineProperty(W,"Scope",{enumerable:!0,get:function(){return qi.Scope}});Object.defineProperty(W,"ValueScope",{enumerable:!0,get:function(){return qi.ValueScope}});Object.defineProperty(W,"ValueScopeName",{enumerable:!0,get:function(){return qi.ValueScopeName}});Object.defineProperty(W,"varKinds",{enumerable:!0,get:function(){return qi.varKinds}});W.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var Yt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Xl=class extends Yt{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=Un(this.rhs,e,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},Zi=class extends Yt{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 te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Un(this.rhs,e,r),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return Li(e,this.rhs)}},Yl=class extends Zi{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ql=class extends Yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ed=class extends Yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},td=class extends Yt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},rd=class extends Yt{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=Un(this.code,e,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},Ko=class extends Yt{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)||(UT(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>cn(e,r.names),{})}},Qt=class extends Ko{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},nd=class extends Ko{},qn=class extends Qt{};qn.kind="else";var sn=class t extends Qt{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 qn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Jg(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=Un(this.condition,e,r),this}get names(){let e=super.names;return Li(e,this.condition),this.else&&cn(e,this.else.names),e}};sn.kind="if";var an=class extends Qt{};an.kind="for";var od=class extends an{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=Un(this.iteration,e,r),this}get names(){return cn(super.names,this.iteration.names)}},sd=class extends an{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=Li(super.names,this.from);return Li(e,this.to)}},Di=class extends an{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=Un(this.iterable,e,r),this}get names(){return cn(super.names,this.iterable.names)}},Go=class extends Qt{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)}};Go.kind="func";var Xo=class extends Ko{render(e){return"return "+super.render(e)}};Xo.kind="return";var id=class extends Qt{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&&cn(e,this.catch.names),this.finally&&cn(e,this.finally.names),e}},Yo=class extends Qt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Yo.kind="catch";var Qo=class extends Qt{render(e){return"finally"+super.render(e)}};Qo.kind="finally";var ad=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 nd]}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 Xl(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 Zi(e,r,n))}add(e,r){return this._leafNode(new Yl(e,W.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new rd(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,te.addCodeArg)(r,o));return r.push("}"),new te._Code(r)}if(e,r,n){if(this._blockNode(new sn(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 sn(e))}else(){return this._elseNode(new qn)}endIf(){return this._endBlockNode(sn,qn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new od(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 sd(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 te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${i}.length`,a=>{this.var(s,(0,te._)`${i}[${a}]`),n(s)})}return this._for(new Di("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,te._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Di("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(an)}label(e){return this._leafNode(new Ql(e))}break(e){return this._leafNode(new ed(e))}return(e){let r=new Xo;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Xo)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new id;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Yo(s),r(s)}return n&&(this._currNode=o.finally=new Qo,this.code(n)),this._endBlockNode(Yo,Qo)}throw(e){return this._leafNode(new td(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=te.nil,n,o){return this._blockNode(new Go(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Go)}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 sn))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}};W.CodeGen=ad;function cn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Li(t,e){return e instanceof te._CodeOrName?cn(t,e.names):t}function Un(t,e,r){if(t instanceof te.Name)return n(t);if(!o(t))return t;return new te._Code(t._items.reduce((s,i)=>(i instanceof te.Name&&(i=n(i)),i instanceof te._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 te._Code&&s._items.some(i=>i instanceof te.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function UT(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Jg(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${cd(t)}`}W.not=Jg;var FT=Wg(W.operators.AND);function HT(...t){return t.reduce(FT)}W.and=HT;var BT=Wg(W.operators.OR);function VT(...t){return t.reduce(BT)}W.or=VT;function Wg(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${cd(e)} ${t} ${cd(r)}`}function cd(t){return t instanceof te.Name?t:(0,te._)`(${t})`}});var re=E(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.checkStrictMode=K.getErrorPath=K.Type=K.useFunc=K.setEvaluated=K.evaluatedPropsToName=K.mergeEvaluated=K.eachItem=K.unescapeJsonPointer=K.escapeJsonPointer=K.escapeFragment=K.unescapeFragment=K.schemaRefOrVal=K.schemaHasRulesButRef=K.schemaHasRules=K.checkUnknownRules=K.alwaysValidSchema=K.toHash=void 0;var de=J(),JT=Wo();function WT(t){let e={};for(let r of t)e[r]=!0;return e}K.toHash=WT;function KT(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Xg(t,e),!Yg(e,t.self.RULES.all))}K.alwaysValidSchema=KT;function Xg(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]||ty(t,`unknown keyword: "${s}"`)}K.checkUnknownRules=Xg;function Yg(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}K.schemaHasRules=Yg;function GT(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}K.schemaHasRulesButRef=GT;function XT({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,de._)`${r}`}return(0,de._)`${t}${e}${(0,de.getProperty)(n)}`}K.schemaRefOrVal=XT;function YT(t){return Qg(decodeURIComponent(t))}K.unescapeFragment=YT;function QT(t){return encodeURIComponent(ld(t))}K.escapeFragment=QT;function ld(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}K.escapeJsonPointer=ld;function Qg(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}K.unescapeJsonPointer=Qg;function eE(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}K.eachItem=eE;function Kg({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof de.Name?(s instanceof de.Name?t(o,s,i):e(o,s,i),i):s instanceof de.Name?(e(o,i,s),s):r(s,i);return a===de.Name&&!(c instanceof de.Name)?n(o,c):c}}K.mergeEvaluated={props:Kg({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,de._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,de._)`${r} || {}`).code((0,de._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,de._)`${r} || {}`),dd(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:ey}),items:Kg({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,de._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,de._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function ey(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,de._)`{}`);return e!==void 0&&dd(t,r,e),r}K.evaluatedPropsToName=ey;function dd(t,e,r){Object.keys(r).forEach(n=>t.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}K.setEvaluated=dd;var Gg={};function tE(t,e){return t.scopeValue("func",{ref:e,code:Gg[e.code]||(Gg[e.code]=new JT._Code(e.code))})}K.useFunc=tE;var ud;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ud||(K.Type=ud={}));function rE(t,e,r){if(t instanceof de.Name){let n=e===ud.Num;return r?n?(0,de._)`"[" + ${t} + "]"`:(0,de._)`"['" + ${t} + "']"`:n?(0,de._)`"/" + ${t}`:(0,de._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,de.getProperty)(t).toString():"/"+ld(t)}K.getErrorPath=rE;function ty(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}K.checkStrictMode=ty});var er=E(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var je=J(),nE={data:new je.Name("data"),valCxt:new je.Name("valCxt"),instancePath:new je.Name("instancePath"),parentData:new je.Name("parentData"),parentDataProperty:new je.Name("parentDataProperty"),rootData:new je.Name("rootData"),dynamicAnchors:new je.Name("dynamicAnchors"),vErrors:new je.Name("vErrors"),errors:new je.Name("errors"),this:new je.Name("this"),self:new je.Name("self"),scope:new je.Name("scope"),json:new je.Name("json"),jsonPos:new je.Name("jsonPos"),jsonLen:new je.Name("jsonLen"),jsonPart:new je.Name("jsonPart")};fd.default=nE});var es=E(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.extendErrors=Ze.resetErrorsCount=Ze.reportExtraError=Ze.reportError=Ze.keyword$DataError=Ze.keywordError=void 0;var ne=J(),Ui=re(),Be=er();Ze.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};Ze.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function oE(t,e=Ze.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=oy(t,e,r);n??(i||a)?ry(s,c):ny(o,(0,ne._)`[${c}]`)}Ze.reportError=oE;function sE(t,e=Ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=oy(t,e,r);ry(o,a),s||i||ny(n,Be.default.vErrors)}Ze.reportExtraError=sE;function iE(t,e){t.assign(Be.default.errors,e),t.if((0,ne._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}Ze.resetErrorsCount=iE;function aE({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,Be.default.errors,a=>{t.const(i,(0,ne._)`${Be.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Be.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}Ze.extendErrors=aE;function ry(t,e){let r=t.const("err",e);t.if((0,ne._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Be.default.vErrors}.push(${r})`),t.code((0,ne._)`${Be.default.errors}++`)}function ny(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 un={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 oy(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:cE(t,e,r)}function cE(t,e,r={}){let{gen:n,it:o}=t,s=[uE(o,r),lE(t,r)];return dE(t,e,s),n.object(...s)}function uE({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,Ui.getErrorPath)(e,Ui.Type.Str)}`:t;return[Be.default.instancePath,(0,ne.strConcat)(Be.default.instancePath,r)]}function lE({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,Ui.getErrorPath)(r,Ui.Type.Str)}`),[un.schemaPath,o]}function dE(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([un.keyword,o],[un.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([un.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([un.schema,i],[un.parentSchema,(0,ne._)`${l}${d}`],[Be.default.data,s]),u&&n.push([un.propertyName,u])}});var iy=E(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.boolOrEmptySchema=Fn.topBoolOrEmptySchema=void 0;var fE=es(),pE=J(),mE=er(),hE={message:"boolean schema is false"};function gE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?sy(t,!1):typeof r=="object"&&r.$async===!0?e.return(mE.default.data):(e.assign((0,pE._)`${n}.errors`,null),e.return(!0))}Fn.topBoolOrEmptySchema=gE;function yE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),sy(t)):r.var(e,!0)}Fn.boolOrEmptySchema=yE;function sy(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,fE.reportError)(o,hE,void 0,e)}});var pd=E(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.getRules=Hn.isJSONType=void 0;var _E=["string","number","integer","boolean","null","object","array"],vE=new Set(_E);function xE(t){return typeof t=="string"&&vE.has(t)}Hn.isJSONType=xE;function bE(){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:{}}}Hn.getRules=bE});var md=E(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.shouldUseRule=vr.shouldUseGroup=vr.schemaHasRulesForType=void 0;function wE({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&ay(t,n)}vr.schemaHasRulesForType=wE;function ay(t,e){return e.rules.some(r=>cy(t,r))}vr.shouldUseGroup=ay;function cy(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))}vr.shouldUseRule=cy});var ts=E(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;var $E=pd(),kE=md(),SE=es(),B=J(),uy=re(),Bn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Bn||(De.DataType=Bn={}));function TE(t){let e=ly(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}De.getSchemaTypes=TE;function ly(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every($E.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}De.getJSONTypes=ly;function EE(t,e){let{gen:r,data:n,opts:o}=t,s=zE(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,kE.schemaHasRulesForType)(t,e[0]));if(i){let a=gd(e,n,o.strictNumbers,Bn.Wrong);r.if(a,()=>{s.length?RE(t,e,s):yd(t)})}return i}De.coerceAndCheckDataType=EE;var dy=new Set(["string","number","integer","boolean","null"]);function zE(t,e){return e?t.filter(r=>dy.has(r)||e==="array"&&r==="array"):[]}function RE(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,B._)`typeof ${o}`),a=n.let("coerced",(0,B._)`undefined`);s.coerceTypes==="array"&&n.if((0,B._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,B._)`${o}[0]`).assign(i,(0,B._)`typeof ${o}`).if(gd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,B._)`${a} !== undefined`);for(let u of r)(dy.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),yd(t),n.endIf(),n.if((0,B._)`${a} !== undefined`,()=>{n.assign(o,a),PE(t,a)});function c(u){switch(u){case"string":n.elseIf((0,B._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,B._)`"" + ${o}`).elseIf((0,B._)`${o} === null`).assign(a,(0,B._)`""`);return;case"number":n.elseIf((0,B._)`${i} == "boolean" || ${o} === null
|
|
30
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let 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 g=m.ref;if(m.ref=null,g){a(g,d);let h=this.seen.get(g).schema;h.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(h)):(Object.assign(p,h),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 $h=G(()=>{});var Ue=G(()=>{Rn();zc();bc();dh();Vs();Oc();Nt();Bs();Ys();$u();Ac();bh();xh();wh();$h()});var fl=G(()=>{Ue()});var No={};vo(No,{ZodISODate:()=>Eh,ZodISODateTime:()=>Th,ZodISODuration:()=>Rh,ZodISOTime:()=>zh,date:()=>ml,datetime:()=>pl,duration:()=>gl,time:()=>hl});function pl(t){return hh(Th,t)}function ml(t){return gh(Eh,t)}function hl(t){return yh(zh,t)}function gl(t){return _h(Rh,t)}var Th,Eh,zh,Rh,yl=G(()=>{Ue();_l();Th=w("ZodISODateTime",(t,e)=>{ih.init(t,e),ve.init(t,e)});Eh=w("ZodISODate",(t,e)=>{ah.init(t,e),ve.init(t,e)});zh=w("ZodISOTime",(t,e)=>{ch.init(t,e),ve.init(t,e)});Rh=w("ZodISODuration",(t,e)=>{uh.init(t,e),ve.init(t,e)})});var Ph,Oj,Mo,vl=G(()=>{Ue();Ue();Ph=(t,e)=>{Fs.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>xc(t,r)},flatten:{value:r=>vc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},Oj=w("ZodError",Ph),Mo=w("ZodError",Ph,{Parent:Error})});var Ih,Ch,Ah,Oh,xl=G(()=>{Ue();vl();Ih=wc(Mo),Ch=kc(Mo),Ah=Tc(Mo),Oh=Ec(Mo)});function b(t){return ku(lk,t)}function se(t){return Vu(Dh,t)}function Mh(t){return Ju(zk,t)}function ze(t){return Wu(Rk,t)}function Lh(t){return Ku(Pk,t)}function xe(){return Gu(Ik)}function Ak(t){return Xu(Ck,t)}function Q(t,e){return vh(Ok,t,e)}function P(t,e){let r={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new qh(r)}function Fe(t,e){return new qh({type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},catchall:xe(),...Y.normalizeParams(e)})}function he(t,e){return new Uh({type:"union",options:t,...Y.normalizeParams(e)})}function $l(t,e,r){return new Nk({type:"union",options:e,discriminator:t,...Y.normalizeParams(r)})}function ui(t,e){return new Mk({type:"intersection",left:t,right:e})}function me(t,e,r){return new jk({type:"record",keyType:t,valueType:e,...Y.normalizeParams(r)})}function Xe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new bl({type:"enum",entries:r,...Y.normalizeParams(e)})}function M(t,e){return new Zk({type:"literal",values:Array.isArray(t)?t:[t],...Y.normalizeParams(e)})}function Fh(t){return new Dk({type:"transform",transform:t})}function be(t){return new Hh({type:"optional",innerType:t})}function jh(t){return new Lk({type:"nullable",innerType:t})}function Uk(t,e){return new qk({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Hk(t,e){return new Fk({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Bk(t,e){return new Bh({type:"nonoptional",innerType:t,...Y.normalizeParams(e)})}function Jk(t,e){return new Vk({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function wl(t,e){return new Wk({type:"pipe",in:t,out:e})}function Gk(t){return new Kk({type:"readonly",innerType:t})}function Xk(t){let e=new Pe({check:"custom"});return e._zod.check=t,e}function Jh(t,e){return cl(Vh,t??(()=>!0),e)}function Yk(t,e={}){return ul(Vh,t,e)}function Qk(t){let e=Xk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Y.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(Y.issue(o))}},t(r.value,r)));return e}function kl(t,e){return wl(Fh(t),e)}var $e,Zh,lk,ve,dk,Nh,ci,fk,pk,mk,hk,gk,yk,_k,vk,xk,bk,wk,$k,kk,Sk,Tk,Ek,Dh,zk,Rk,Pk,Ik,Ck,Ok,qh,Uh,Nk,Mk,jk,bl,Zk,Dk,Hh,Lk,qk,Fk,Bh,Vk,Wk,Kk,Vh,_l=G(()=>{Ue();Ue();fl();yl();xl();$e=w("ZodType",(t,e)=>(ue.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>st(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Ih(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Ah(t,r,n),t.parseAsync=async(r,n)=>Ch(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Oh(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(Yk(r,n)),t.superRefine=r=>t.check(Qk(r)),t.overwrite=r=>t.check(rn(r)),t.optional=()=>be(t),t.nullable=()=>jh(t),t.nullish=()=>be(jh(t)),t.nonoptional=r=>Bk(t,r),t.array=()=>Q(t),t.or=r=>he([t,r]),t.and=r=>ui(t,r),t.transform=r=>wl(t,Fh(r)),t.default=r=>Uk(t,r),t.prefault=r=>Hk(t,r),t.catch=r=>Jk(t,r),t.pipe=r=>wl(t,r),t.readonly=()=>Gk(t),t.describe=r=>{let n=t.clone();return pr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return pr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return pr.get(t);let n=t.clone();return pr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Zh=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(Yu(...n)),t.includes=(...n)=>t.check(tl(...n)),t.startsWith=(...n)=>t.check(rl(...n)),t.endsWith=(...n)=>t.check(nl(...n)),t.min=(...n)=>t.check(Cn(...n)),t.max=(...n)=>t.check(ni(...n)),t.length=(...n)=>t.check(oi(...n)),t.nonempty=(...n)=>t.check(Cn(1,...n)),t.lowercase=n=>t.check(Qu(n)),t.uppercase=n=>t.check(el(n)),t.trim=()=>t.check(sl()),t.normalize=(...n)=>t.check(ol(...n)),t.toLowerCase=()=>t.check(il()),t.toUpperCase=()=>t.check(al())}),lk=w("ZodString",(t,e)=>{Io.init(t,e),Zh.init(t,e),t.email=r=>t.check(Su(dk,r)),t.url=r=>t.check(Pu(fk,r)),t.jwt=r=>t.check(Bu(Ek,r)),t.emoji=r=>t.check(Iu(pk,r)),t.guid=r=>t.check(Qs(Nh,r)),t.uuid=r=>t.check(Tu(ci,r)),t.uuidv4=r=>t.check(Eu(ci,r)),t.uuidv6=r=>t.check(zu(ci,r)),t.uuidv7=r=>t.check(Ru(ci,r)),t.nanoid=r=>t.check(Cu(mk,r)),t.guid=r=>t.check(Qs(Nh,r)),t.cuid=r=>t.check(Au(hk,r)),t.cuid2=r=>t.check(Ou(gk,r)),t.ulid=r=>t.check(Nu(yk,r)),t.base64=r=>t.check(Uu(kk,r)),t.base64url=r=>t.check(Fu(Sk,r)),t.xid=r=>t.check(Mu(_k,r)),t.ksuid=r=>t.check(ju(vk,r)),t.ipv4=r=>t.check(Zu(xk,r)),t.ipv6=r=>t.check(Du(bk,r)),t.cidrv4=r=>t.check(Lu(wk,r)),t.cidrv6=r=>t.check(qu($k,r)),t.e164=r=>t.check(Hu(Tk,r)),t.datetime=r=>t.check(pl(r)),t.date=r=>t.check(ml(r)),t.time=r=>t.check(hl(r)),t.duration=r=>t.check(gl(r))});ve=w("ZodStringFormat",(t,e)=>{pe.init(t,e),Zh.init(t,e)}),dk=w("ZodEmail",(t,e)=>{Zc.init(t,e),ve.init(t,e)}),Nh=w("ZodGUID",(t,e)=>{Mc.init(t,e),ve.init(t,e)}),ci=w("ZodUUID",(t,e)=>{jc.init(t,e),ve.init(t,e)}),fk=w("ZodURL",(t,e)=>{Dc.init(t,e),ve.init(t,e)}),pk=w("ZodEmoji",(t,e)=>{Lc.init(t,e),ve.init(t,e)}),mk=w("ZodNanoID",(t,e)=>{qc.init(t,e),ve.init(t,e)}),hk=w("ZodCUID",(t,e)=>{Uc.init(t,e),ve.init(t,e)}),gk=w("ZodCUID2",(t,e)=>{Fc.init(t,e),ve.init(t,e)}),yk=w("ZodULID",(t,e)=>{Hc.init(t,e),ve.init(t,e)}),_k=w("ZodXID",(t,e)=>{Bc.init(t,e),ve.init(t,e)}),vk=w("ZodKSUID",(t,e)=>{Vc.init(t,e),ve.init(t,e)}),xk=w("ZodIPv4",(t,e)=>{Jc.init(t,e),ve.init(t,e)}),bk=w("ZodIPv6",(t,e)=>{Wc.init(t,e),ve.init(t,e)}),wk=w("ZodCIDRv4",(t,e)=>{Kc.init(t,e),ve.init(t,e)}),$k=w("ZodCIDRv6",(t,e)=>{Gc.init(t,e),ve.init(t,e)}),kk=w("ZodBase64",(t,e)=>{Xc.init(t,e),ve.init(t,e)}),Sk=w("ZodBase64URL",(t,e)=>{Yc.init(t,e),ve.init(t,e)}),Tk=w("ZodE164",(t,e)=>{Qc.init(t,e),ve.init(t,e)}),Ek=w("ZodJWT",(t,e)=>{eu.init(t,e),ve.init(t,e)}),Dh=w("ZodNumber",(t,e)=>{Ks.init(t,e),$e.init(t,e),t.gt=(n,o)=>t.check(ti(n,o)),t.gte=(n,o)=>t.check(Oo(n,o)),t.min=(n,o)=>t.check(Oo(n,o)),t.lt=(n,o)=>t.check(ei(n,o)),t.lte=(n,o)=>t.check(Ao(n,o)),t.max=(n,o)=>t.check(Ao(n,o)),t.int=n=>t.check(Mh(n)),t.safe=n=>t.check(Mh(n)),t.positive=n=>t.check(ti(0,n)),t.nonnegative=n=>t.check(Oo(0,n)),t.negative=n=>t.check(ei(0,n)),t.nonpositive=n=>t.check(Ao(0,n)),t.multipleOf=(n,o)=>t.check(ri(n,o)),t.step=(n,o)=>t.check(ri(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});zk=w("ZodNumberFormat",(t,e)=>{tu.init(t,e),Dh.init(t,e)});Rk=w("ZodBoolean",(t,e)=>{ru.init(t,e),$e.init(t,e)});Pk=w("ZodNull",(t,e)=>{nu.init(t,e),$e.init(t,e)});Ik=w("ZodUnknown",(t,e)=>{ou.init(t,e),$e.init(t,e)});Ck=w("ZodNever",(t,e)=>{su.init(t,e),$e.init(t,e)});Ok=w("ZodArray",(t,e)=>{iu.init(t,e),$e.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Cn(r,n)),t.nonempty=r=>t.check(Cn(1,r)),t.max=(r,n)=>t.check(ni(r,n)),t.length=(r,n)=>t.check(oi(r,n)),t.unwrap=()=>t.element});qh=w("ZodObject",(t,e)=>{Gs.init(t,e),$e.init(t,e),Y.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Xe(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:Ak()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>Y.extend(t,r),t.merge=r=>Y.merge(t,r),t.pick=r=>Y.pick(t,r),t.omit=r=>Y.omit(t,r),t.partial=(...r)=>Y.partial(Hh,t,r[0]),t.required=(...r)=>Y.required(Bh,t,r[0])});Uh=w("ZodUnion",(t,e)=>{Xs.init(t,e),$e.init(t,e),t.options=e.options});Nk=w("ZodDiscriminatedUnion",(t,e)=>{Uh.init(t,e),au.init(t,e)});Mk=w("ZodIntersection",(t,e)=>{cu.init(t,e),$e.init(t,e)});jk=w("ZodRecord",(t,e)=>{uu.init(t,e),$e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});bl=w("ZodEnum",(t,e)=>{lu.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 bl({...e,checks:[],...Y.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 bl({...e,checks:[],...Y.normalizeParams(o),entries:s})}});Zk=w("ZodLiteral",(t,e)=>{du.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]}})});Dk=w("ZodTransform",(t,e)=>{fu.init(t,e),$e.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Y.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(Y.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Hh=w("ZodOptional",(t,e)=>{pu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Lk=w("ZodNullable",(t,e)=>{mu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});qk=w("ZodDefault",(t,e)=>{hu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});Fk=w("ZodPrefault",(t,e)=>{gu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Bh=w("ZodNonOptional",(t,e)=>{yu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Vk=w("ZodCatch",(t,e)=>{_u.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Wk=w("ZodPipe",(t,e)=>{vu.init(t,e),$e.init(t,e),t.in=e.in,t.out=e.out});Kk=w("ZodReadonly",(t,e)=>{xu.init(t,e),$e.init(t,e)});Vh=w("ZodCustom",(t,e)=>{bu.init(t,e),$e.init(t,e)})});var Wh=G(()=>{});var Kh=G(()=>{});var Gh=G(()=>{Ue();_l();fl();vl();xl();Wh();Ue();ph();Ys();yl();Kh();ot(fh())});var Xh=G(()=>{Gh()});var Yh=G(()=>{Xh()});function pg(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function mg(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Tl,Qh,Mn,gr,di,Te,eg,tg,Gj,rS,nS,El,it,jo,rg,Ie,lt,dt,Ce,fi,ng,Xt,og,sg,zl,Yt,A,Rl,jn,Zo,Xj,pi,oS,mi,sS,Do,Nn,ig,iS,aS,cS,uS,lS,dS,hi,Pl,fS,pS,Il,gi,mS,hS,yi,gS,Lo,qo,yS,Uo,Zn,_S,Fo,_i,vi,xi,Yj,bi,wi,$i,ag,cg,ug,Cl,lg,Ho,Dn,dg,vS,ki,xS,Si,bS,Al,wS,Ti,$S,kS,SS,TS,ES,zS,RS,PS,IS,CS,Ei,AS,OS,zi,Ol,Nl,Ml,NS,MS,jS,jl,ZS,DS,LS,qS,US,fg,Ri,FS,Pi,Qj,HS,Ln,BS,eZ,Bo,VS,Zl,JS,WS,KS,GS,XS,YS,QS,li,eT,tT,rT,Vo,Dl,nT,oT,sT,iT,aT,cT,uT,lT,dT,fT,pT,mT,hT,gT,yT,_T,vT,xT,qn,bT,wT,$T,Ii,kT,ST,TT,Ll,ET,tZ,rZ,nZ,oZ,sZ,iZ,I,Sl,yr=G(()=>{Yh();Tl="2025-11-25",Qh="2025-03-26",Mn=[Tl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],gr="io.modelcontextprotocol/related-task",di="2.0",Te=Jh(t=>t!==null&&(typeof t=="object"||typeof t=="function")),eg=he([b(),se().int()]),tg=b(),Gj=Fe({ttl:se().optional(),pollInterval:se().optional()}),rS=P({ttl:se().optional()}),nS=P({taskId:b()}),El=Fe({progressToken:eg.optional(),[gr]:nS.optional()}),it=P({_meta:El.optional()}),jo=it.extend({task:rS.optional()}),rg=t=>jo.safeParse(t).success,Ie=P({method:b(),params:it.loose().optional()}),lt=P({_meta:El.optional()}),dt=P({method:b(),params:lt.loose().optional()}),Ce=Fe({_meta:El.optional()}),fi=he([b(),se().int()]),ng=P({jsonrpc:M(di),id:fi,...Ie.shape}).strict(),Xt=t=>ng.safeParse(t).success,og=P({jsonrpc:M(di),...dt.shape}).strict(),sg=t=>og.safeParse(t).success,zl=P({jsonrpc:M(di),id:fi,result:Ce}).strict(),Yt=t=>zl.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={}));Rl=P({jsonrpc:M(di),id:fi.optional(),error:P({code:se().int(),message:b(),data:xe().optional()})}).strict(),jn=t=>Rl.safeParse(t).success,Zo=he([ng,og,zl,Rl]),Xj=he([zl,Rl]),pi=Ce.strict(),oS=lt.extend({requestId:fi.optional(),reason:b().optional()}),mi=dt.extend({method:M("notifications/cancelled"),params:oS}),sS=P({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Xe(["light","dark"]).optional()}),Do=P({icons:Q(sS).optional()}),Nn=P({name:b(),title:b().optional()}),ig=Nn.extend({...Nn.shape,...Do.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),iS=ui(P({applyDefaults:ze().optional()}),me(b(),xe())),aS=kl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ui(P({form:iS.optional(),url:Te.optional()}),me(b(),xe()).optional())),cS=Fe({list:Te.optional(),cancel:Te.optional(),requests:Fe({sampling:Fe({createMessage:Te.optional()}).optional(),elicitation:Fe({create:Te.optional()}).optional()}).optional()}),uS=Fe({list:Te.optional(),cancel:Te.optional(),requests:Fe({tools:Fe({call:Te.optional()}).optional()}).optional()}),lS=P({experimental:me(b(),Te).optional(),sampling:P({context:Te.optional(),tools:Te.optional()}).optional(),elicitation:aS.optional(),roots:P({listChanged:ze().optional()}).optional(),tasks:cS.optional(),extensions:me(b(),Te).optional()}),dS=it.extend({protocolVersion:b(),capabilities:lS,clientInfo:ig}),hi=Ie.extend({method:M("initialize"),params:dS}),Pl=t=>hi.safeParse(t).success,fS=P({experimental:me(b(),Te).optional(),logging:Te.optional(),completions:Te.optional(),prompts:P({listChanged:ze().optional()}).optional(),resources:P({subscribe:ze().optional(),listChanged:ze().optional()}).optional(),tools:P({listChanged:ze().optional()}).optional(),tasks:uS.optional(),extensions:me(b(),Te).optional()}),pS=Ce.extend({protocolVersion:b(),capabilities:fS,serverInfo:ig,instructions:b().optional()}),Il=dt.extend({method:M("notifications/initialized"),params:lt.optional()}),gi=Ie.extend({method:M("ping"),params:it.optional()}),mS=P({progress:se(),total:be(se()),message:be(b())}),hS=P({...lt.shape,...mS.shape,progressToken:eg}),yi=dt.extend({method:M("notifications/progress"),params:hS}),gS=it.extend({cursor:tg.optional()}),Lo=Ie.extend({params:gS.optional()}),qo=Ce.extend({nextCursor:tg.optional()}),yS=Xe(["working","input_required","completed","failed","cancelled"]),Uo=P({taskId:b(),status:yS,ttl:he([se(),Lh()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:be(se()),statusMessage:be(b())}),Zn=Ce.extend({task:Uo}),_S=lt.merge(Uo),Fo=dt.extend({method:M("notifications/tasks/status"),params:_S}),_i=Ie.extend({method:M("tasks/get"),params:it.extend({taskId:b()})}),vi=Ce.merge(Uo),xi=Ie.extend({method:M("tasks/result"),params:it.extend({taskId:b()})}),Yj=Ce.loose(),bi=Lo.extend({method:M("tasks/list")}),wi=qo.extend({tasks:Q(Uo)}),$i=Ie.extend({method:M("tasks/cancel"),params:it.extend({taskId:b()})}),ag=Ce.merge(Uo),cg=P({uri:b(),mimeType:be(b()),_meta:me(b(),xe()).optional()}),ug=cg.extend({text:b()}),Cl=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),lg=cg.extend({blob:Cl}),Ho=Xe(["user","assistant"]),Dn=P({audience:Q(Ho).optional(),priority:se().min(0).max(1).optional(),lastModified:No.datetime({offset:!0}).optional()}),dg=P({...Nn.shape,...Do.shape,uri:b(),description:be(b()),mimeType:be(b()),size:be(se()),annotations:Dn.optional(),_meta:be(Fe({}))}),vS=P({...Nn.shape,...Do.shape,uriTemplate:b(),description:be(b()),mimeType:be(b()),annotations:Dn.optional(),_meta:be(Fe({}))}),ki=Lo.extend({method:M("resources/list")}),xS=qo.extend({resources:Q(dg)}),Si=Lo.extend({method:M("resources/templates/list")}),bS=qo.extend({resourceTemplates:Q(vS)}),Al=it.extend({uri:b()}),wS=Al,Ti=Ie.extend({method:M("resources/read"),params:wS}),$S=Ce.extend({contents:Q(he([ug,lg]))}),kS=dt.extend({method:M("notifications/resources/list_changed"),params:lt.optional()}),SS=Al,TS=Ie.extend({method:M("resources/subscribe"),params:SS}),ES=Al,zS=Ie.extend({method:M("resources/unsubscribe"),params:ES}),RS=lt.extend({uri:b()}),PS=dt.extend({method:M("notifications/resources/updated"),params:RS}),IS=P({name:b(),description:be(b()),required:be(ze())}),CS=P({...Nn.shape,...Do.shape,description:be(b()),arguments:be(Q(IS)),_meta:be(Fe({}))}),Ei=Lo.extend({method:M("prompts/list")}),AS=qo.extend({prompts:Q(CS)}),OS=it.extend({name:b(),arguments:me(b(),b()).optional()}),zi=Ie.extend({method:M("prompts/get"),params:OS}),Ol=P({type:M("text"),text:b(),annotations:Dn.optional(),_meta:me(b(),xe()).optional()}),Nl=P({type:M("image"),data:Cl,mimeType:b(),annotations:Dn.optional(),_meta:me(b(),xe()).optional()}),Ml=P({type:M("audio"),data:Cl,mimeType:b(),annotations:Dn.optional(),_meta:me(b(),xe()).optional()}),NS=P({type:M("tool_use"),name:b(),id:b(),input:me(b(),xe()),_meta:me(b(),xe()).optional()}),MS=P({type:M("resource"),resource:he([ug,lg]),annotations:Dn.optional(),_meta:me(b(),xe()).optional()}),jS=dg.extend({type:M("resource_link")}),jl=he([Ol,Nl,Ml,jS,MS]),ZS=P({role:Ho,content:jl}),DS=Ce.extend({description:b().optional(),messages:Q(ZS)}),LS=dt.extend({method:M("notifications/prompts/list_changed"),params:lt.optional()}),qS=P({title:b().optional(),readOnlyHint:ze().optional(),destructiveHint:ze().optional(),idempotentHint:ze().optional(),openWorldHint:ze().optional()}),US=P({taskSupport:Xe(["required","optional","forbidden"]).optional()}),fg=P({...Nn.shape,...Do.shape,description:b().optional(),inputSchema:P({type:M("object"),properties:me(b(),Te).optional(),required:Q(b()).optional()}).catchall(xe()),outputSchema:P({type:M("object"),properties:me(b(),Te).optional(),required:Q(b()).optional()}).catchall(xe()).optional(),annotations:qS.optional(),execution:US.optional(),_meta:me(b(),xe()).optional()}),Ri=Lo.extend({method:M("tools/list")}),FS=qo.extend({tools:Q(fg)}),Pi=Ce.extend({content:Q(jl).default([]),structuredContent:me(b(),xe()).optional(),isError:ze().optional()}),Qj=Pi.or(Ce.extend({toolResult:xe()})),HS=jo.extend({name:b(),arguments:me(b(),xe()).optional()}),Ln=Ie.extend({method:M("tools/call"),params:HS}),BS=dt.extend({method:M("notifications/tools/list_changed"),params:lt.optional()}),eZ=P({autoRefresh:ze().default(!0),debounceMs:se().int().nonnegative().default(300)}),Bo=Xe(["debug","info","notice","warning","error","critical","alert","emergency"]),VS=it.extend({level:Bo}),Zl=Ie.extend({method:M("logging/setLevel"),params:VS}),JS=lt.extend({level:Bo,logger:b().optional(),data:xe()}),WS=dt.extend({method:M("notifications/message"),params:JS}),KS=P({name:b().optional()}),GS=P({hints:Q(KS).optional(),costPriority:se().min(0).max(1).optional(),speedPriority:se().min(0).max(1).optional(),intelligencePriority:se().min(0).max(1).optional()}),XS=P({mode:Xe(["auto","required","none"]).optional()}),YS=P({type:M("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q(jl).default([]),structuredContent:P({}).loose().optional(),isError:ze().optional(),_meta:me(b(),xe()).optional()}),QS=$l("type",[Ol,Nl,Ml]),li=$l("type",[Ol,Nl,Ml,NS,YS]),eT=P({role:Ho,content:he([li,Q(li)]),_meta:me(b(),xe()).optional()}),tT=jo.extend({messages:Q(eT),modelPreferences:GS.optional(),systemPrompt:b().optional(),includeContext:Xe(["none","thisServer","allServers"]).optional(),temperature:se().optional(),maxTokens:se().int(),stopSequences:Q(b()).optional(),metadata:Te.optional(),tools:Q(fg).optional(),toolChoice:XS.optional()}),rT=Ie.extend({method:M("sampling/createMessage"),params:tT}),Vo=Ce.extend({model:b(),stopReason:be(Xe(["endTurn","stopSequence","maxTokens"]).or(b())),role:Ho,content:QS}),Dl=Ce.extend({model:b(),stopReason:be(Xe(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Ho,content:he([li,Q(li)])}),nT=P({type:M("boolean"),title:b().optional(),description:b().optional(),default:ze().optional()}),oT=P({type:M("string"),title:b().optional(),description:b().optional(),minLength:se().optional(),maxLength:se().optional(),format:Xe(["email","uri","date","date-time"]).optional(),default:b().optional()}),sT=P({type:Xe(["number","integer"]),title:b().optional(),description:b().optional(),minimum:se().optional(),maximum:se().optional(),default:se().optional()}),iT=P({type:M("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),aT=P({type:M("string"),title:b().optional(),description:b().optional(),oneOf:Q(P({const:b(),title:b()})),default:b().optional()}),cT=P({type:M("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),uT=he([iT,aT]),lT=P({type:M("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({type:M("string"),enum:Q(b())}),default:Q(b()).optional()}),dT=P({type:M("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({anyOf:Q(P({const:b(),title:b()}))}),default:Q(b()).optional()}),fT=he([lT,dT]),pT=he([cT,uT,fT]),mT=he([pT,nT,oT,sT]),hT=jo.extend({mode:M("form").optional(),message:b(),requestedSchema:P({type:M("object"),properties:me(b(),mT),required:Q(b()).optional()})}),gT=jo.extend({mode:M("url"),message:b(),elicitationId:b(),url:b().url()}),yT=he([hT,gT]),_T=Ie.extend({method:M("elicitation/create"),params:yT}),vT=lt.extend({elicitationId:b()}),xT=dt.extend({method:M("notifications/elicitation/complete"),params:vT}),qn=Ce.extend({action:Xe(["accept","decline","cancel"]),content:kl(t=>t===null?void 0:t,me(b(),he([b(),se(),ze(),Q(b())])).optional())}),bT=P({type:M("ref/resource"),uri:b()}),wT=P({type:M("ref/prompt"),name:b()}),$T=it.extend({ref:he([wT,bT]),argument:P({name:b(),value:b()}),context:P({arguments:me(b(),b()).optional()}).optional()}),Ii=Ie.extend({method:M("completion/complete"),params:$T});kT=Ce.extend({completion:Fe({values:Q(b()).max(100),total:be(se().int()),hasMore:be(ze())})}),ST=P({uri:b().startsWith("file://"),name:b().optional(),_meta:me(b(),xe()).optional()}),TT=Ie.extend({method:M("roots/list"),params:it.optional()}),Ll=Ce.extend({roots:Q(ST)}),ET=dt.extend({method:M("notifications/roots/list_changed"),params:lt.optional()}),tZ=he([gi,hi,Ii,Zl,zi,Ei,ki,Si,Ti,TS,zS,Ln,Ri,_i,xi,bi,$i]),rZ=he([mi,yi,Il,ET,Fo]),nZ=he([pi,Vo,Dl,qn,Ll,vi,wi,Zn]),oZ=he([gi,rT,_T,TT,_i,xi,bi,$i]),sZ=he([mi,yi,WS,PS,kS,BS,LS,Fo,xT]),iZ=he([pi,pS,kT,DS,AS,xS,bS,$S,Pi,FS,vi,wi,Zn]),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 Sl(o.elicitations,r)}return new t(e,r,n)}},Sl=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 Go=E(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 Wo=class{};oe._CodeOrName=Wo;oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var sn=class extends Wo{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=sn;var ft=class extends Wo{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 sn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};oe._Code=ft;oe.nil=new ft("");function Kg(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Gl(r,e[n]),r.push(t[++n]);return new ft(r)}oe._=Kg;var Kl=new ft("+");function Gg(t,...e){let r=[Ko(t[0])],n=0;for(;n<e.length;)r.push(Kl),Gl(r,e[n]),r.push(Kl,Ko(t[++n]));return ZT(r),new ft(r)}oe.str=Gg;function Gl(t,e){e instanceof ft?t.push(...e._items):e instanceof sn?t.push(e):t.push(qT(e))}oe.addCodeArg=Gl;function ZT(t){let e=1;for(;e<t.length-1;){if(t[e]===Kl){let r=DT(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function DT(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof sn||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 sn))return`"${t}${e.slice(1)}`}function LT(t,e){return e.emptyStr()?t:t.emptyStr()?e:Gg`${t}${e}`}oe.strConcat=LT;function qT(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ko(Array.isArray(t)?t.join(","):t)}function UT(t){return new ft(Ko(t))}oe.stringify=UT;function Ko(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oe.safeStringify=Ko;function FT(t){return typeof t=="string"&&oe.IDENTIFIER.test(t)?new ft(`.${t}`):Kg`[${t}]`}oe.getProperty=FT;function HT(t){if(typeof t=="string"&&oe.IDENTIFIER.test(t))return new ft(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}oe.getEsmExportName=HT;function BT(t){return new ft(t.toString())}oe.regexpCode=BT});var Ql=E(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ye=Go(),Xl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ji;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ji||(Qe.UsedValueState=ji={}));Qe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Zi=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.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}}};Qe.Scope=Zi;var Di=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Qe.ValueScopeName=Di;var VT=(0,Ye._)`\n`,Yl=class extends Zi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?VT:Ye.nil}}get(){return this._scope}name(e){return new Di(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,Ye._)`${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=Ye.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,ji.Started);let l=r(u);if(l){let d=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ye._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ye._)`${s}${l}${this.opts._n}`;else throw new Xl(u);c.set(u,ji.Completed)})}return s}};Qe.ValueScope=Yl});var J=E(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.or=W.and=W.not=W.CodeGen=W.operators=W.varKinds=W.ValueScopeName=W.ValueScope=W.Scope=W.Name=W.regexpCode=W.stringify=W.getProperty=W.nil=W.strConcat=W.str=W._=void 0;var te=Go(),kt=Ql(),vr=Go();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(W,"strConcat",{enumerable:!0,get:function(){return vr.strConcat}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(W,"getProperty",{enumerable:!0,get:function(){return vr.getProperty}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(W,"regexpCode",{enumerable:!0,get:function(){return vr.regexpCode}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return vr.Name}});var Fi=Ql();Object.defineProperty(W,"Scope",{enumerable:!0,get:function(){return Fi.Scope}});Object.defineProperty(W,"ValueScope",{enumerable:!0,get:function(){return Fi.ValueScope}});Object.defineProperty(W,"ValueScopeName",{enumerable:!0,get:function(){return Fi.ValueScopeName}});Object.defineProperty(W,"varKinds",{enumerable:!0,get:function(){return Fi.varKinds}});W.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var Qt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ed=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?kt.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=Fn(this.rhs,e,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},Li=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 te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Fn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return Ui(e,this.rhs)}},td=class extends Li{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},rd=class extends Qt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},nd=class extends Qt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},od=class extends Qt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},sd=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=Fn(this.code,e,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},Xo=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)||(JT(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>un(e,r.names),{})}},er=class extends Xo{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},id=class extends Xo{},Un=class extends er{};Un.kind="else";var an=class t extends er{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 Un(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Xg(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=Fn(this.condition,e,r),this}get names(){let e=super.names;return Ui(e,this.condition),this.else&&un(e,this.else.names),e}};an.kind="if";var cn=class extends er{};cn.kind="for";var ad=class extends cn{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=Fn(this.iteration,e,r),this}get names(){return un(super.names,this.iteration.names)}},cd=class extends cn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?kt.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=Ui(super.names,this.from);return Ui(e,this.to)}},qi=class extends cn{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=Fn(this.iterable,e,r),this}get names(){return un(super.names,this.iterable.names)}},Yo=class extends er{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)}};Yo.kind="func";var Qo=class extends Xo{render(e){return"return "+super.render(e)}};Qo.kind="return";var ud=class extends er{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&&un(e,this.catch.names),this.finally&&un(e,this.finally.names),e}},es=class extends er{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};es.kind="catch";var ts=class extends er{render(e){return"finally"+super.render(e)}};ts.kind="finally";var ld=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
31
|
+
`:""},this._extScope=e,this._scope=new kt.Scope({parent:e}),this._nodes=[new id]}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 ed(e,s,n)),s}const(e,r,n){return this._def(kt.varKinds.const,e,r,n)}let(e,r,n){return this._def(kt.varKinds.let,e,r,n)}var(e,r,n){return this._def(kt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Li(e,r,n))}add(e,r){return this._leafNode(new td(e,W.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new sd(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,te.addCodeArg)(r,o));return r.push("}"),new te._Code(r)}if(e,r,n){if(this._blockNode(new an(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 an(e))}else(){return this._elseNode(new Un)}endIf(){return this._endBlockNode(an,Un)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new ad(e),r)}forRange(e,r,n,o,s=this.opts.es5?kt.varKinds.var:kt.varKinds.let){let i=this._scope.toName(e);return this._for(new cd(s,i,r,n),()=>o(i))}forOf(e,r,n,o=kt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${i}.length`,a=>{this.var(s,(0,te._)`${i}[${a}]`),n(s)})}return this._for(new qi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?kt.varKinds.var:kt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new qi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(cn)}label(e){return this._leafNode(new rd(e))}break(e){return this._leafNode(new nd(e))}return(e){let r=new Qo;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Qo)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ud;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new es(s),r(s)}return n&&(this._currNode=o.finally=new ts,this.code(n)),this._endBlockNode(es,ts)}throw(e){return this._leafNode(new od(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=te.nil,n,o){return this._blockNode(new Yo(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Yo)}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 an))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}};W.CodeGen=ld;function un(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ui(t,e){return e instanceof te._CodeOrName?un(t,e.names):t}function Fn(t,e,r){if(t instanceof te.Name)return n(t);if(!o(t))return t;return new te._Code(t._items.reduce((s,i)=>(i instanceof te.Name&&(i=n(i)),i instanceof te._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 te._Code&&s._items.some(i=>i instanceof te.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function JT(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Xg(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${dd(t)}`}W.not=Xg;var WT=Yg(W.operators.AND);function KT(...t){return t.reduce(WT)}W.and=KT;var GT=Yg(W.operators.OR);function XT(...t){return t.reduce(GT)}W.or=XT;function Yg(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${dd(e)} ${t} ${dd(r)}`}function dd(t){return t instanceof te.Name?t:(0,te._)`(${t})`}});var re=E(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.checkStrictMode=K.getErrorPath=K.Type=K.useFunc=K.setEvaluated=K.evaluatedPropsToName=K.mergeEvaluated=K.eachItem=K.unescapeJsonPointer=K.escapeJsonPointer=K.escapeFragment=K.unescapeFragment=K.schemaRefOrVal=K.schemaHasRulesButRef=K.schemaHasRules=K.checkUnknownRules=K.alwaysValidSchema=K.toHash=void 0;var de=J(),YT=Go();function QT(t){let e={};for(let r of t)e[r]=!0;return e}K.toHash=QT;function eE(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ty(t,e),!ry(e,t.self.RULES.all))}K.alwaysValidSchema=eE;function ty(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]||sy(t,`unknown keyword: "${s}"`)}K.checkUnknownRules=ty;function ry(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}K.schemaHasRules=ry;function tE(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}K.schemaHasRulesButRef=tE;function rE({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,de._)`${r}`}return(0,de._)`${t}${e}${(0,de.getProperty)(n)}`}K.schemaRefOrVal=rE;function nE(t){return ny(decodeURIComponent(t))}K.unescapeFragment=nE;function oE(t){return encodeURIComponent(pd(t))}K.escapeFragment=oE;function pd(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}K.escapeJsonPointer=pd;function ny(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}K.unescapeJsonPointer=ny;function sE(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}K.eachItem=sE;function Qg({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof de.Name?(s instanceof de.Name?t(o,s,i):e(o,s,i),i):s instanceof de.Name?(e(o,i,s),s):r(s,i);return a===de.Name&&!(c instanceof de.Name)?n(o,c):c}}K.mergeEvaluated={props:Qg({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,de._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,de._)`${r} || {}`).code((0,de._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,de._)`${r} || {}`),md(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:oy}),items:Qg({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,de._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,de._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function oy(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,de._)`{}`);return e!==void 0&&md(t,r,e),r}K.evaluatedPropsToName=oy;function md(t,e,r){Object.keys(r).forEach(n=>t.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}K.setEvaluated=md;var ey={};function iE(t,e){return t.scopeValue("func",{ref:e,code:ey[e.code]||(ey[e.code]=new YT._Code(e.code))})}K.useFunc=iE;var fd;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(fd||(K.Type=fd={}));function aE(t,e,r){if(t instanceof de.Name){let n=e===fd.Num;return r?n?(0,de._)`"[" + ${t} + "]"`:(0,de._)`"['" + ${t} + "']"`:n?(0,de._)`"/" + ${t}`:(0,de._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,de.getProperty)(t).toString():"/"+pd(t)}K.getErrorPath=aE;function sy(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}K.checkStrictMode=sy});var tr=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var je=J(),cE={data:new je.Name("data"),valCxt:new je.Name("valCxt"),instancePath:new je.Name("instancePath"),parentData:new je.Name("parentData"),parentDataProperty:new je.Name("parentDataProperty"),rootData:new je.Name("rootData"),dynamicAnchors:new je.Name("dynamicAnchors"),vErrors:new je.Name("vErrors"),errors:new je.Name("errors"),this:new je.Name("this"),self:new je.Name("self"),scope:new je.Name("scope"),json:new je.Name("json"),jsonPos:new je.Name("jsonPos"),jsonLen:new je.Name("jsonLen"),jsonPart:new je.Name("jsonPart")};hd.default=cE});var rs=E(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.extendErrors=Ze.resetErrorsCount=Ze.reportExtraError=Ze.reportError=Ze.keyword$DataError=Ze.keywordError=void 0;var ne=J(),Hi=re(),Be=tr();Ze.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};Ze.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function uE(t,e=Ze.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=cy(t,e,r);n??(i||a)?iy(s,c):ay(o,(0,ne._)`[${c}]`)}Ze.reportError=uE;function lE(t,e=Ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=cy(t,e,r);iy(o,a),s||i||ay(n,Be.default.vErrors)}Ze.reportExtraError=lE;function dE(t,e){t.assign(Be.default.errors,e),t.if((0,ne._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}Ze.resetErrorsCount=dE;function fE({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,Be.default.errors,a=>{t.const(i,(0,ne._)`${Be.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Be.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}Ze.extendErrors=fE;function iy(t,e){let r=t.const("err",e);t.if((0,ne._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Be.default.vErrors}.push(${r})`),t.code((0,ne._)`${Be.default.errors}++`)}function ay(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 ln={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 cy(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:pE(t,e,r)}function pE(t,e,r={}){let{gen:n,it:o}=t,s=[mE(o,r),hE(t,r)];return gE(t,e,s),n.object(...s)}function mE({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,Hi.getErrorPath)(e,Hi.Type.Str)}`:t;return[Be.default.instancePath,(0,ne.strConcat)(Be.default.instancePath,r)]}function hE({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,Hi.getErrorPath)(r,Hi.Type.Str)}`),[ln.schemaPath,o]}function gE(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([ln.keyword,o],[ln.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([ln.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([ln.schema,i],[ln.parentSchema,(0,ne._)`${l}${d}`],[Be.default.data,s]),u&&n.push([ln.propertyName,u])}});var ly=E(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.boolOrEmptySchema=Hn.topBoolOrEmptySchema=void 0;var yE=rs(),_E=J(),vE=tr(),xE={message:"boolean schema is false"};function bE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?uy(t,!1):typeof r=="object"&&r.$async===!0?e.return(vE.default.data):(e.assign((0,_E._)`${n}.errors`,null),e.return(!0))}Hn.topBoolOrEmptySchema=bE;function wE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),uy(t)):r.var(e,!0)}Hn.boolOrEmptySchema=wE;function uy(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,yE.reportError)(o,xE,void 0,e)}});var gd=E(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.getRules=Bn.isJSONType=void 0;var $E=["string","number","integer","boolean","null","object","array"],kE=new Set($E);function SE(t){return typeof t=="string"&&kE.has(t)}Bn.isJSONType=SE;function TE(){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:{}}}Bn.getRules=TE});var yd=E(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.shouldUseRule=xr.shouldUseGroup=xr.schemaHasRulesForType=void 0;function EE({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&dy(t,n)}xr.schemaHasRulesForType=EE;function dy(t,e){return e.rules.some(r=>fy(t,r))}xr.shouldUseGroup=dy;function fy(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))}xr.shouldUseRule=fy});var ns=E(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;var zE=gd(),RE=yd(),PE=rs(),B=J(),py=re(),Vn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Vn||(De.DataType=Vn={}));function IE(t){let e=my(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}De.getSchemaTypes=IE;function my(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(zE.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}De.getJSONTypes=my;function CE(t,e){let{gen:r,data:n,opts:o}=t,s=AE(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,RE.schemaHasRulesForType)(t,e[0]));if(i){let a=vd(e,n,o.strictNumbers,Vn.Wrong);r.if(a,()=>{s.length?OE(t,e,s):xd(t)})}return i}De.coerceAndCheckDataType=CE;var hy=new Set(["string","number","integer","boolean","null"]);function AE(t,e){return e?t.filter(r=>hy.has(r)||e==="array"&&r==="array"):[]}function OE(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,B._)`typeof ${o}`),a=n.let("coerced",(0,B._)`undefined`);s.coerceTypes==="array"&&n.if((0,B._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,B._)`${o}[0]`).assign(i,(0,B._)`typeof ${o}`).if(vd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,B._)`${a} !== undefined`);for(let u of r)(hy.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),xd(t),n.endIf(),n.if((0,B._)`${a} !== undefined`,()=>{n.assign(o,a),NE(t,a)});function c(u){switch(u){case"string":n.elseIf((0,B._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,B._)`"" + ${o}`).elseIf((0,B._)`${o} === null`).assign(a,(0,B._)`""`);return;case"number":n.elseIf((0,B._)`${i} == "boolean" || ${o} === null
|
|
32
32
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,B._)`+${o}`);return;case"integer":n.elseIf((0,B._)`${i} === "boolean" || ${o} === null
|
|
33
33
|
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,B._)`+${o}`);return;case"boolean":n.elseIf((0,B._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,B._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,B._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,B._)`${i} === "string" || ${i} === "number"
|
|
34
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,B._)`[${o}]`)}}}function PE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,B._)`${e} !== undefined`,()=>t.assign((0,B._)`${e}[${r}]`,n))}function hd(t,e,r,n=Bn.Correct){let o=n===Bn.Correct?B.operators.EQ:B.operators.NEQ,s;switch(t){case"null":return(0,B._)`${e} ${o} null`;case"array":s=(0,B._)`Array.isArray(${e})`;break;case"object":s=(0,B._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,B._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,B._)`typeof ${e} ${o} ${t}`}return n===Bn.Correct?s:(0,B.not)(s);function i(a=B.nil){return(0,B.and)((0,B._)`typeof ${e} == "number"`,a,r?(0,B._)`isFinite(${e})`:B.nil)}}De.checkDataType=hd;function gd(t,e,r,n){if(t.length===1)return hd(t[0],e,r,n);let o,s=(0,uy.toHash)(t);if(s.array&&s.object){let i=(0,B._)`typeof ${e} != "object"`;o=s.null?i:(0,B._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=B.nil;s.number&&delete s.integer;for(let i in s)o=(0,B.and)(o,hd(i,e,r,n));return o}De.checkDataTypes=gd;var IE={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,B._)`{type: ${t}}`:(0,B._)`{type: ${e}}`};function yd(t){let e=CE(t);(0,SE.reportError)(e,IE)}De.reportTypeError=yd;function CE(t){let{gen:e,data:r,schema:n}=t,o=(0,uy.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var py=E(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.assignDefaults=void 0;var Vn=J(),AE=re();function OE(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)fy(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>fy(t,s,o.default))}Fi.assignDefaults=OE;function fy(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Vn._)`${s}${(0,Vn.getProperty)(e)}`;if(o){(0,AE.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Vn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Vn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Vn._)`${a} = ${(0,Vn.stringify)(r)}`)}});var ft=E(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var ge=J(),_d=re(),xr=er(),NE=re();function ME(t,e){let{gen:r,data:n,it:o}=t;r.if(xd(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}le.checkReportMissingProp=ME;function jE({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(xd(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}le.checkMissingProp=jE;function ZE(t,e){t.setParams({missingProperty:e},!0),t.error()}le.reportMissingProp=ZE;function my(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=my;function vd(t,e,r){return(0,ge._)`${my(t)}.call(${e}, ${r})`}le.isOwnProperty=vd;function DE(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${vd(t,e,r)}`:o}le.propertyInData=DE;function xd(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(vd(t,e,r))):o}le.noPropertyInData=xd;function hy(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=hy;function LE(t,e){return hy(e).filter(r=>!(0,_d.alwaysValidSchema)(t,e[r]))}le.schemaProperties=LE;function qE({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=[[xr.default.instancePath,(0,ge.strConcat)(xr.default.instancePath,s)],[xr.default.parentData,i.parentData],[xr.default.parentDataProperty,i.parentDataProperty],[xr.default.rootData,xr.default.rootData]];i.opts.dynamicRef&&d.push([xr.default.dynamicAnchors,xr.default.dynamicAnchors]);let m=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${m})`:(0,ge._)`${a}(${m})`}le.callValidateCode=qE;var UE=(0,ge._)`new RegExp`;function FE({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"?UE:(0,NE.useFunc)(t,o)}(${r}, ${n})`})}le.usePattern=FE;function HE(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:_d.Type.Num},s),e.if((0,ge.not)(s),a)})}}le.validateArray=HE;function BE(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,_d.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}le.validateUnion=BE});var _y=E(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.validateKeywordUsage=Mt.validSchemaType=Mt.funcKeywordCode=Mt.macroKeywordCode=void 0;var Ve=J(),ln=er(),VE=ft(),JE=es();function WE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=yy(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Mt.macroKeywordCode=WE;function KE(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;XE(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=yy(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)g(),e.modifying&&gy(t),h(()=>t.error());else{let _=e.async?p():f();e.modifying&&gy(t),h(()=>GE(t,_))}}function p(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,Ve._)`await `),v=>n.assign(d,!1).if((0,Ve._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,Ve._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,Ve._)`${l}.errors`;return n.assign(_,null),g(Ve.nil),_}function g(_=e.async?(0,Ve._)`await `:Ve.nil){let v=c.opts.passContext?ln.default.this:ln.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ve._)`${_}${(0,VE.callValidateCode)(t,l,v,y)}`,e.modifying)}function h(_){var v;n.if((0,Ve.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}Mt.funcKeywordCode=KE;function gy(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function GE(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(ln.default.vErrors,(0,Ve._)`${ln.default.vErrors} === null ? ${e} : ${ln.default.vErrors}.concat(${e})`).assign(ln.default.errors,(0,Ve._)`${ln.default.vErrors}.length`),(0,JE.extendErrors)(t)},()=>t.error())}function XE({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function yy(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ve.stringify)(r)})}function YE(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")}Mt.validSchemaType=YE;function QE({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)}}Mt.validateKeywordUsage=QE});var xy=E(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.extendSubschemaMode=br.extendSubschemaData=br.getSubschema=void 0;var jt=J(),vy=re();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,jt._)`${t.schemaPath}${(0,jt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,jt._)`${t.schemaPath}${(0,jt.getProperty)(e)}${(0,jt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,vy.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')}br.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,jt._)`${e.data}${(0,jt.getProperty)(r)}`,!0);c(m),t.errorPath=(0,jt.str)`${u}${(0,vy.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,jt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof jt.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]}}br.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}br.extendSubschemaMode=rz});var bd=E((p4,by)=>{"use strict";by.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 $y=E((m4,wy)=>{"use strict";var wr=wy.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(){};Hi(e,n,o,t,"",t)};wr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};wr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};wr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};wr.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 Hi(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 wr.arrayKeywords)for(var m=0;m<d.length;m++)Hi(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in wr.propsKeywords){if(d&&typeof d=="object")for(var p in d)Hi(t,e,r,d[p],o+"/"+l+"/"+nz(p),s,o,l,n,p)}else(l in wr.keywords||t.allKeys&&!(l in wr.skipKeywords))&&Hi(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 rs=E(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var oz=re(),sz=bd(),iz=$y(),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?!wd(t):e?ky(t)<=e:!1}et.inlineRef=cz;var uz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function wd(t){for(let e in t){if(uz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(wd)||typeof r=="object"&&wd(r))return!0}return!1}function ky(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+=ky(n)),e===1/0))return 1/0}return e}function Sy(t,e="",r){r!==!1&&(e=Jn(e));let n=t.parse(e);return Ty(t,n)}et.getFullPath=Sy;function Ty(t,e){return t.serialize(e).split("#")[0]+"#"}et._getFullPath=Ty;var lz=/#\/?$/;function Jn(t){return t?t.replace(lz,""):""}et.normalizeId=Jn;function dz(t,e,r){return r=Jn(r),t.resolve(e,r)}et.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=Jn(t[r]||e),s={"":o},i=Sy(n,o,!1),a={},c=new Set;return iz(t,{allKeys:!0},(d,m,p,f)=>{if(f===void 0)return;let g=i+m,h=s[f];typeof d[r]=="string"&&(h=_.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[m]=h;function _(y){let x=this.opts.uriResolver.resolve;if(y=Jn(h?x(h,y):y),c.has(y))throw l(y);c.add(y);let $=this.refs[y];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,y):y!==Jn(g)&&(y[0]==="#"?(u(d,a[y],y),a[y]=d):this.refs[y]=g),y}function v(y){if(typeof y=="string"){if(!fz.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),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`)}}et.getSchemaRefs=pz});var ss=E($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.getData=$r.KeywordCxt=$r.validateFunctionCode=void 0;var Iy=iy(),Ey=ts(),kd=md(),Bi=ts(),mz=py(),os=_y(),$d=xy(),j=J(),U=er(),hz=rs(),tr=re(),ns=es();function gz(t){if(Oy(t)&&(Ny(t),Ay(t))){vz(t);return}Cy(t,()=>(0,Iy.topBoolOrEmptySchema)(t))}$r.validateFunctionCode=gz;function Cy({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,j._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{t.code((0,j._)`"use strict"; ${zy(r,o)}`),_z(t,o),t.code(s)}):t.func(e,(0,j._)`${U.default.data}, ${yz(o)}`,n.$async,()=>t.code(zy(r,o)).code(s))}function yz(t){return(0,j._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${t.dynamicRef?(0,j._)`, ${U.default.dynamicAnchors}={}`:j.nil}}={}`}function _z(t,e){t.if(U.default.valCxt,()=>{t.var(U.default.instancePath,(0,j._)`${U.default.valCxt}.${U.default.instancePath}`),t.var(U.default.parentData,(0,j._)`${U.default.valCxt}.${U.default.parentData}`),t.var(U.default.parentDataProperty,(0,j._)`${U.default.valCxt}.${U.default.parentDataProperty}`),t.var(U.default.rootData,(0,j._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,j._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{t.var(U.default.instancePath,(0,j._)`""`),t.var(U.default.parentData,(0,j._)`undefined`),t.var(U.default.parentDataProperty,(0,j._)`undefined`),t.var(U.default.rootData,U.default.data),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,j._)`{}`)})}function vz(t){let{schema:e,opts:r,gen:n}=t;Cy(t,()=>{r.$comment&&e.$comment&&jy(t),kz(t),n.let(U.default.vErrors,null),n.let(U.default.errors,0),r.unevaluated&&xz(t),My(t),Ez(t)})}function xz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,j._)`${r}.evaluated`),e.if((0,j._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${t.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${t.evaluated}.items`,(0,j._)`undefined`))}function zy(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${r} */`:j.nil}function bz(t,e){if(Oy(t)&&(Ny(t),Ay(t))){wz(t,e);return}(0,Iy.boolOrEmptySchema)(t,e)}function Ay({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 Oy(t){return typeof t.schema!="boolean"}function wz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&jy(t),Sz(t),Tz(t);let s=n.const("_errs",U.default.errors);My(t,s),n.var(e,(0,j._)`${s} === ${U.default.errors}`)}function Ny(t){(0,tr.checkUnknownRules)(t),$z(t)}function My(t,e){if(t.opts.jtd)return Ry(t,[],!1,e);let r=(0,Ey.getSchemaTypes)(t.schema),n=(0,Ey.coerceAndCheckDataType)(t,r);Ry(t,r,!n,e)}function $z(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,tr.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,tr.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 Tz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function jy({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,j._)`${U.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,j.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,j._)`${U.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,j._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,j._)`new ${o}(${U.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,U.default.vErrors),s.unevaluated&&zz(t),e.return((0,j._)`${U.default.errors} === 0`))}function zz({gen:t,evaluated:e,props:r,items:n}){r instanceof j.Name&&t.assign((0,j._)`${e}.props`,r),n instanceof j.Name&&t.assign((0,j._)`${e}.items`,n)}function Ry(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,tr.schemaHasRulesButRef)(s,l))){o.block(()=>Dy(t,"$ref",l.all.$ref.definition));return}c.jtd||Rz(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,kd.shouldUseGroup)(s,m)&&(m.type?(o.if((0,Bi.checkDataType)(m.type,i,c.strictNumbers)),Py(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,Bi.reportTypeError)(t)),o.endIf()):Py(t,m),a||o.if((0,j._)`${U.default.errors} === ${n||0}`))}}function Py(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,kd.shouldUseRule)(n,s)&&Dy(t,s.keyword,s.definition,e.type)})}function Rz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Pz(t,e),t.opts.allowUnionTypes||Iz(t,e),Cz(t,t.dataTypes))}function Pz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Zy(t.dataTypes,r)||Sd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Oz(t,e)}}function Iz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Sd(t,"use allowUnionTypes to allow union type keyword")}function Cz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,kd.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Az(e,i))&&Sd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Az(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Zy(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Oz(t,e){let r=[];for(let n of t.dataTypes)Zy(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Sd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,tr.checkStrictMode)(t,e,t.opts.strictTypes)}var Vi=class{constructor(e,r,n){if((0,os.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,tr.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",Ly(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,os.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",U.default.errors))}result(e,r,n){this.failResult((0,j.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,j.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,j._)`${r} !== undefined && (${(0,j.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?ns.reportExtraError:ns.reportError)(this,this.def.error,r)}$dataError(){(0,ns.reportError)(this,this.def.$dataError||ns.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ns.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=j.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=j.nil,r=j.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,j.or)((0,j._)`${o} === undefined`,r)),e!==j.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,j.or)(i(),a());function i(){if(n.length){if(!(r instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,Bi.checkDataTypes)(c,r,s.opts.strictNumbers,Bi.DataType.Wrong)}`}return j.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,j._)`!${c}(${r})`}return j.nil}}subschema(e,r){let n=(0,$d.getSubschema)(this.it,e);(0,$d.extendSubschemaData)(n,this.it,e),(0,$d.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=tr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=tr.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,j.Name)),!0}};$r.KeywordCxt=Vi;function Dy(t,e,r,n){let o=new Vi(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,os.funcKeywordCode)(o,r):"macro"in r?(0,os.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,os.funcKeywordCode)(o,r)}var Nz=/^\/(?:[^~]|~0|~1)*$/,Mz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ly(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return U.default.rootData;if(t[0]==="/"){if(!Nz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=U.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,j._)`${s}${(0,j.getProperty)((0,tr.unescapeJsonPointer)(u))}`,i=(0,j._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}$r.getData=Ly});var Ji=E(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var Td=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Ed.default=Td});var is=E(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var zd=rs(),Rd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,zd.resolveUrl)(e,r,n),this.missingSchema=(0,zd.normalizeId)((0,zd.getFullPath)(e,this.missingRef))}};Pd.default=Rd});var Ki=E(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.resolveSchema=pt.getCompilingSchema=pt.resolveRef=pt.compileSchema=pt.SchemaEnv=void 0;var kt=J(),jz=Ji(),dn=er(),St=rs(),qy=re(),Zz=ss(),Wn=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,St.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};pt.SchemaEnv=Wn;function Cd(t){let e=Uy.call(this,t);if(e)return e;let r=(0,St.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new kt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:jz.default,code:(0,kt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:dn.default.data,parentData:dn.default.parentData,parentDataProperty:dn.default.parentDataProperty,dataNames:[dn.default.data],dataPathArr:[kt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,kt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:kt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,kt._)`""`,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(dn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${dn.default.self}`,`${dn.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:g}=u;p.evaluated={props:f instanceof kt.Name?void 0:f,items:g instanceof kt.Name?void 0:g,dynamicProps:f instanceof kt.Name,dynamicItems:g instanceof kt.Name},p.source&&(p.source.evaluated=(0,kt.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)}}pt.compileSchema=Cd;function Dz(t,e,r){var n;r=(0,St.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 Wn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Lz.call(this,s)}pt.resolveRef=Dz;function Lz(t){return(0,St.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Cd.call(this,t)}function Uy(t){for(let e of this._compilations)if(qz(e,t))return e}pt.getCompilingSchema=Uy;function qz(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]||Wi.call(this,t,e)}function Wi(t,e){let r=this.opts.uriResolver.parse(e),n=(0,St._getFullPath)(this.opts.uriResolver,r),o=(0,St.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Id.call(this,r,t);let s=(0,St.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Wi.call(this,t,i);return typeof a?.schema!="object"?void 0:Id.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Cd.call(this,i),s===(0,St.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,St.resolveUrl)(this.opts.uriResolver,o,u)),new Wn({schema:a,schemaId:c,root:t,baseId:o})}return Id.call(this,r,i)}}pt.resolveSchema=Wi;var Fz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Id(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,qy.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Fz.has(a)&&u&&(e=(0,St.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,qy.schemaHasRulesButRef)(r,this.RULES)){let a=(0,St.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Wi.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Wn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Fy=E((x4,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 Zd=E((b4,Gy)=>{"use strict";var Bz=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),Vz=RegExp.prototype.test.bind(/^\d*$/u),fn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Nd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),By=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Md=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),Jz=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),tt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)tt[e]="%"+t[e>>4]+t[e&15]}function Le(t){return t<2048?tt[192|t>>6]+tt[128|t&63]:t<65536?tt[224|t>>12]+tt[128|t>>6&63]+tt[128|t&63]:tt[240|t>>18]+tt[128|t>>12&63]+tt[128|t>>6&63]+tt[128|t&63]}function Wz(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 Kz=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&&fn(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function Hy(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 eR(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(!Kz(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:Hy(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 Hy(i)}function Ad(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(tR(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=eR(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function tR(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function rR(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 nR={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},oR=/[@/?#:]/g,sR=/[@/?#]/g;function Vy(t,e){let r=e?sR:oR;return r.lastIndex=0,t.replace(r,n=>nR[n])}function Jy(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(fn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Nd(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function iR(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(fn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Nd(i)?e+=i:e+="%"+s,r+=2;continue}}if(By(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=Ky(o)?n:tt[o];else if(o<55296||o>57343)e+=Le(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Le(65536+(o-55296<<10)+(s-56320)),r++):e+=Le(65533)}else e+=Le(65533)}}return e}function aR(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(fn(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),By(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=tt[i];else if(i<55296||i>57343)r+=Le(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=Le(65536+(i-55296<<10)+(a-56320)),o++):r+=Le(65533)}else r+=Le(65533)}}return r}function jd(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(fn(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=tt[s];else if(s<55296||s>57343)r+=Le(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Le(65536+(s-55296<<10)+(i-56320)),n++):r+=Le(65533)}else r+=Le(65533)}}return r}function Wy(t){return jd(t,Jz)}function cR(t){return jd(t,Md)}function uR(t){return jd(t,Md)}function Ky(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 lR(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(fn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Nd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Md(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=Ky(o)?n:tt[o];else if(o<55296||o>57343)e+=Le(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Le(65536+(o-55296<<10)+(s-56320)),r++):e+=Le(65533)}else e+=Le(65533)}}return e}function dR(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(fn(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function fR(t){let e=[];if(t.userinfo!==void 0&&(e.push(Wy(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!Od(r)){let n=Ad(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=Jy(r,!0),n=Ad(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=Vy(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!Vz(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}Gy.exports={nonSimpleDomain:Yz,recomposeAuthority:fR,reescapeHostDelimiters:Vy,normalizePercentEncoding:Jy,normalizePathEncoding:iR,serializePathEncoding:aR,normalizeQueryFragmentEncoding:lR,encodeUserinfo:Wy,encodeQuery:cR,encodeFragment:uR,escapePreservingEscapes:dR,removeDotSegments:rR,isIPv4:Od,isUUID:Bz,normalizeIPv6:Ad,stringArrayToHexStripped:Wz}});var t_=E((w4,e_)=>{"use strict";var{isUUID:pR}=Zd(),mR=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,hR=["http","https","ws","wss","urn","urn:uuid"];function gR(t){return hR.indexOf(t)!==-1}function Dd(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 Xy(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Yy(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 yR(t){return t.secure=Dd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function _R(t){if((t.port===(Dd(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 vR(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(mR);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 xR(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 bR(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!pR(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function wR(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Qy={scheme:"http",domainHost:!0,parse:Xy,serialize:Yy},$R={scheme:"https",domainHost:Qy.domainHost,parse:Xy,serialize:Yy},Gi={scheme:"ws",domainHost:!0,parse:yR,serialize:_R},kR={scheme:"wss",domainHost:Gi.domainHost,parse:Gi.parse,serialize:Gi.serialize},SR={scheme:"urn",parse:vR,serialize:xR,skipNormalize:!0},TR={scheme:"urn:uuid",parse:bR,serialize:wR,skipNormalize:!0},Xi={http:Qy,https:$R,ws:Gi,wss:kR,urn:SR,"urn:uuid":TR};Object.setPrototypeOf(Xi,null);function Ld(t){return t&&(Xi[t]||Xi[t.toLowerCase()])||void 0}e_.exports={wsIsSecure:Dd,SCHEMES:Xi,isValidSchemeName:gR,getSchemeHandler:Ld}});var m_=E(($4,ea)=>{"use strict";var{normalizeIPv6:i_,removeDotSegments:cs,recomposeAuthority:ER,normalizePercentEncoding:qd,normalizePathEncoding:zR,serializePathEncoding:r_,normalizeQueryFragmentEncoding:n_,encodeQuery:RR,encodeFragment:PR,reescapeHostDelimiters:IR,isIPv4:a_,nonSimpleDomain:CR}=Zd(),{SCHEMES:c_,getSchemeHandler:Ud}=t_(),u_=/^[A-Za-z][A-Za-z0-9+.-]*$/u,l_="URI scheme is malformed.";function o_(t){let e=unescape(String(t));if(!u_.test(e))throw new TypeError(l_);return e}function AR(t,e){return typeof t=="string"?t=qR(t,e):typeof t=="object"&&(t=Qi(pn(t,e),e)),t}function OR(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}=Yi(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:m,malformedSchemeSpecific:p,malformedHost:f,malformedScheme:g}=Yi(e,n);if(s||d||i||m||a||p||c||f||u||g)throw new Error(o.error||l.error||"URI is malformed.");let h=d_(o,l,n,!0),_=Ud(r&&r.scheme||h.scheme),v=h.host,y=v!==void 0&&v!==""&&(a_(v)||i_(v).isIPV6);f_(h,r||{},_,y);let x=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(h.error&&!x)throw new Error(h.error);return n.skipEscape=!0,pn(h,n)}function d_(t,e,r,n){let o={};return n||(t=Qi(pn(t,r),r),e=Qi(pn(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=cs(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=cs(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=cs(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=cs(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 NR(t,e,r){let n=s_(t,r),o=s_(e,r);return n!==void 0&&o!==void 0&&n===o}function pn(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=o_(r.scheme));let s=Ud(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=qd(r.path):r.path=r_(r.path,a)),n.reference!=="suffix"&&r.scheme&&(r.scheme=o_(r.scheme),o.push(r.scheme,":"));let c=ER(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=cs(u)),a&&(u=r_(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return r.query!==void 0&&o.push("?",RR(r.query)),r.fragment!==void 0&&o.push("#",PR(r.fragment)),o.join("")}var MR=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,jR=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,ZR=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function DR(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 as(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 Fd(t){return t[0]==="["&&t[t.length-1]==="]"}function LR(t){let e=t[4];return as(t[3])||e!==void 0&&!Fd(e)&&as(e)||as(t[6])||as(t[7])||as(t[8])}function f_(t,e,r,n){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!Fd(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&CR(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 Yi(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(jR);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let m=t.match(ZR);if(m!==null){let f=m[1],g=f.replace(/[\t\n\r]/g,"");g.length>=2&&(g.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==g.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let p=t.match(MR);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 h=unescape(n.scheme);u_.test(h)?n.scheme=h.toLowerCase():(n.error=n.error||l_,u=!0)}s=LR(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let f=DR(n,p);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(a_(n.host)===!1){let _=Fd(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=i_(n.host);l=y.isIPV6||y.isIPVFuture===!0,c=v&&(!_||y.error===!0),n.host=l?y.host:y.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 g=Ud(r.scheme||n.scheme);if(c||(a=f_(n,r,g,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let h=l?n.host:qd(n.host,!0);l||(h=qd(h.toLowerCase())),n.host=IR(h,l)}(!g||g&&!g.skipNormalize)&&(n.path&&(n.path=zR(n.path)),n.query&&(n.query=n_(n.query)),n.fragment&&(n.fragment=n_(n.fragment))),g&&g.parse&&(g.parse(n,r),g===c_.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 Qi(t,e){return Yi(t,e).parsed}function qR(t,e){return p_(t,e).normalized}function p_(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Yi(t,e);return{normalized:n||o||s||i||a?t:pn(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function s_(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:pn(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=p_(r,e);return o||s||i||a||c?void 0:n}var Hd={SCHEMES:c_,normalize:AR,resolve:OR,resolveComponent:d_,equal:NR,serialize:pn,parse:Qi};ea.exports=Hd;ea.exports.default=Hd;ea.exports.fastUri=Hd});var g_=E(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var h_=m_();h_.code='require("ajv/dist/runtime/uri").default';Bd.default=h_});var k_=E(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=void 0;var UR=ss();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return UR.KeywordCxt}});var Kn=J();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Kn._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Kn.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Kn.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Kn.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Kn.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Kn.CodeGen}});var FR=Ji(),b_=is(),HR=pd(),us=Ki(),BR=J(),ls=rs(),ta=ts(),Jd=re(),y_=Fy(),VR=g_(),w_=(t,e)=>new RegExp(t,e);w_.code="new RegExp";var JR=["removeAdditional","useDefaults","coerceTypes"],WR=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),KR={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."},GR={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},__=200;function XR(t){var e,r,n,o,s,i,a,c,u,l,d,m,p,f,g,h,_,v,y,x,$,O,C,ae,ce;let Ee=t.strict,F=(e=t.code)===null||e===void 0?void 0:e.optimize,_e=F===!0||F===void 0?1:F||0,Rt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:w_,Ar=(o=t.uriResolver)!==null&&o!==void 0?o:VR.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ee)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Ee)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Ee)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:Ee)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:Ee)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:_e,regExp:Rt}:{optimize:_e,regExp:Rt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:__,loopEnum:(h=t.loopEnum)!==null&&h!==void 0?h:__,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(y=t.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(O=t.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(C=t.validateFormats)!==null&&C!==void 0?C:!0,unicodeRegExp:(ae=t.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(ce=t.int32range)!==null&&ce!==void 0?ce:!0,uriResolver:Ar}}var ds=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,...XR(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new BR.ValueScope({scope:{},prefixes:WR,es5:r,lines:n}),this.logger=nP(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,HR.getRules)(),v_.call(this,KR,e,"NOT SUPPORTED"),v_.call(this,GR,e,"DEPRECATED","warn"),this._metaOpts=tP.call(this),e.formats&&QR.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&eP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),YR.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=y_;n==="id"&&(o={...y_},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 b_.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,ls.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=x_.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new us.SchemaEnv({schema:{},schemaId:n});if(r=us.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=x_.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,ls.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(sP.call(this,n,r),!r)return(0,Jd.eachItem)(n,s=>Vd.call(this,s)),this;aP.call(this,r);let o={...r,type:(0,ta.getJSONTypes)(r.type),schemaType:(0,ta.getJSONTypes)(r.schemaType)};return(0,Jd.eachItem)(n,o.type.length===0?s=>Vd.call(this,s,o):s=>o.type.forEach(i=>Vd.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]=$_(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,ls.normalizeId)(i||n);let u=ls.getSchemaRefs.call(this,e,n);return c=new us.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):us.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{us.compileSchema.call(this,e)}finally{this.opts=r}}};ds.ValidationError=FR.default;ds.MissingRefError=b_.default;Ae.default=ds;function v_(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 x_(t){return t=(0,ls.normalizeId)(t),this.schemas[t]||this.refs[t]}function YR(){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 QR(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function eP(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 tP(){let t={...this.opts};for(let e of JR)delete t[e];return t}var rP={log(){},warn(){},error(){}};function nP(t){if(t===!1)return rP;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 oP=/^[a-z_$][a-z0-9_$:-]*$/i;function sP(t,e){let{RULES:r}=this;if((0,Jd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!oP.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 Vd(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,ta.getJSONTypes)(e.type),schemaType:(0,ta.getJSONTypes)(e.schemaType)}};e.before?iP.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 iP(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 aP(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=$_(e)),t.validateSchema=this.compile(e,!0))}var cP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function $_(t){return{anyOf:[t,cP]}}});var S_=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var uP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Wd.default=uP});var R_=E(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.callRef=mn.getValidate=void 0;var lP=is(),T_=ft(),rt=J(),Gn=er(),E_=Ki(),ra=re(),dP={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=E_.resolveRef.call(c,u,o,r);if(l===void 0)throw new lP.default(n.opts.uriResolver,o,r);if(l instanceof E_.SchemaEnv)return m(l);return p(l);function d(){if(s===u)return na(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return na(t,(0,rt._)`${f}.validate`,u,u.$async)}function m(f){let g=z_(t,f);na(t,g,f,f.$async)}function p(f){let g=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,rt.stringify)(f)}:{ref:f}),h=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:rt.nil,topSchemaRef:g,errSchemaPath:r},h);t.mergeEvaluated(_),t.ok(h)}}};function z_(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,rt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}mn.getValidate=z_;function na(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Gn.default.this:rt.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,rt._)`await ${(0,T_.callValidateCode)(t,e,u)}`),p(e),i||o.assign(f,!0)},g=>{o.if((0,rt._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),m(g),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,T_.callValidateCode)(t,e,u),()=>p(e),()=>m(e))}function m(f){let g=(0,rt._)`${f}.errors`;o.assign(Gn.default.vErrors,(0,rt._)`${Gn.default.vErrors} === null ? ${g} : ${Gn.default.vErrors}.concat(${g})`),o.assign(Gn.default.errors,(0,rt._)`${Gn.default.vErrors}.length`)}function p(f){var g;if(!s.opts.unevaluated)return;let h=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(h&&!h.dynamicProps)h.props!==void 0&&(s.props=ra.mergeEvaluated.props(o,h.props,s.props));else{let _=o.var("props",(0,rt._)`${f}.evaluated.props`);s.props=ra.mergeEvaluated.props(o,_,s.props,rt.Name)}if(s.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(s.items=ra.mergeEvaluated.items(o,h.items,s.items));else{let _=o.var("items",(0,rt._)`${f}.evaluated.items`);s.items=ra.mergeEvaluated.items(o,_,s.items,rt.Name)}}}mn.callRef=na;mn.default=dP});var P_=E(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var fP=S_(),pP=R_(),mP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",fP.default,pP.default];Kd.default=mP});var I_=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var oa=J(),kr=oa.operators,sa={maximum:{okStr:"<=",ok:kr.LTE,fail:kr.GT},minimum:{okStr:">=",ok:kr.GTE,fail:kr.LT},exclusiveMaximum:{okStr:"<",ok:kr.LT,fail:kr.GTE},exclusiveMinimum:{okStr:">",ok:kr.GT,fail:kr.LTE}},hP={message:({keyword:t,schemaCode:e})=>(0,oa.str)`must be ${sa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,oa._)`{comparison: ${sa[t].okStr}, limit: ${e}}`},gP={keyword:Object.keys(sa),type:"number",schemaType:"number",$data:!0,error:hP,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,oa._)`${r} ${sa[e].fail} ${n} || isNaN(${r})`)}};Gd.default=gP});var C_=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var fs=J(),yP={message:({schemaCode:t})=>(0,fs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,fs._)`{multipleOf: ${t}}`},_P={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:yP,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,fs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,fs._)`${i} !== parseInt(${i})`;t.fail$data((0,fs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Xd.default=_P});var O_=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});function A_(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}Yd.default=A_;A_.code='require("ajv/dist/runtime/ucs2length").default'});var N_=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var hn=J(),vP=re(),xP=O_(),bP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,hn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,hn._)`{limit: ${t}}`},wP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:bP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?hn.operators.GT:hn.operators.LT,i=o.opts.unicode===!1?(0,hn._)`${r}.length`:(0,hn._)`${(0,vP.useFunc)(t.gen,xP.default)}(${r})`;t.fail$data((0,hn._)`${i} ${s} ${n}`)}};Qd.default=wP});var M_=E(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var $P=ft(),kP=re(),Xn=J(),SP={message:({schemaCode:t})=>(0,Xn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Xn._)`{pattern: ${t}}`},TP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:SP,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,Xn._)`new RegExp`:(0,kP.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Xn._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Xn._)`!${l}`)}else{let c=(0,$P.usePattern)(t,o);t.fail$data((0,Xn._)`!${c}.test(${r})`)}}};ef.default=TP});var j_=E(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var ps=J(),EP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ps.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ps._)`{limit: ${t}}`},zP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:EP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ps.operators.GT:ps.operators.LT;t.fail$data((0,ps._)`Object.keys(${r}).length ${o} ${n}`)}};tf.default=zP});var Z_=E(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var ms=ft(),hs=J(),RP=re(),PP={message:({params:{missingProperty:t}})=>(0,hs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,hs._)`{missingProperty: ${t}}`},IP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:PP,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 g of r)if(p?.[g]===void 0&&!f.has(g)){let h=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${g}" is not defined at "${h}" (strictRequired)`;(0,RP.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(hs.nil,d);else for(let p of r)(0,ms.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,ms.checkMissingProp)(t,r,p)),(0,ms.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,ms.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function m(p,f){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,ms.propertyInData)(e,o,p,a.ownProperties)),e.if((0,hs.not)(f),()=>{t.error(),e.break()})},hs.nil)}}};rf.default=IP});var D_=E(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var gs=J(),CP={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,gs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,gs._)`{limit: ${t}}`},AP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:CP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?gs.operators.GT:gs.operators.LT;t.fail$data((0,gs._)`${r}.length ${o} ${n}`)}};nf.default=AP});var ia=E(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var L_=bd();L_.code='require("ajv/dist/runtime/equal").default';of.default=L_});var q_=E(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var sf=ts(),Oe=J(),OP=re(),NP=ia(),MP={message:({params:{i:t,j:e}})=>(0,Oe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Oe._)`{i: ${t}, j: ${e}}`},jP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:MP,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,sf.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Oe._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Oe._)`${r}.length`),g=e.let("j");t.setParams({i:f,j:g}),e.assign(c,!0),e.if((0,Oe._)`${f} > 1`,()=>(d()?m:p)(f,g))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function m(f,g){let h=e.name("item"),_=(0,sf.checkDataTypes)(u,h,a.opts.strictNumbers,sf.DataType.Wrong),v=e.const("indices",(0,Oe._)`{}`);e.for((0,Oe._)`;${f}--;`,()=>{e.let(h,(0,Oe._)`${r}[${f}]`),e.if(_,(0,Oe._)`continue`),u.length>1&&e.if((0,Oe._)`typeof ${h} == "string"`,(0,Oe._)`${h} += "_"`),e.if((0,Oe._)`typeof ${v}[${h}] == "number"`,()=>{e.assign(g,(0,Oe._)`${v}[${h}]`),t.error(),e.assign(c,!1).break()}).code((0,Oe._)`${v}[${h}] = ${f}`)})}function p(f,g){let h=(0,OP.useFunc)(e,NP.default),_=e.name("outer");e.label(_).for((0,Oe._)`;${f}--;`,()=>e.for((0,Oe._)`${g} = ${f}; ${g}--;`,()=>e.if((0,Oe._)`${h}(${r}[${f}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};af.default=jP});var U_=E(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var cf=J(),ZP=re(),DP=ia(),LP={message:"must be equal to constant",params:({schemaCode:t})=>(0,cf._)`{allowedValue: ${t}}`},qP={keyword:"const",$data:!0,error:LP,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,cf._)`!${(0,ZP.useFunc)(e,DP.default)}(${r}, ${o})`):t.fail((0,cf._)`${s} !== ${r}`)}};uf.default=qP});var F_=E(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var ys=J(),UP=re(),FP=ia(),HP={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ys._)`{allowedValues: ${t}}`},BP={keyword:"enum",schemaType:"array",$data:!0,error:HP,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,UP.useFunc)(e,FP.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,ys.or)(...o.map((f,g)=>m(p,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,p=>e.if((0,ys._)`${u()}(${r}, ${p})`,()=>e.assign(l,!0).break()))}function m(p,f){let g=o[f];return typeof g=="object"&&g!==null?(0,ys._)`${u()}(${r}, ${p}[${f}])`:(0,ys._)`${r} === ${g}`}}};lf.default=BP});var H_=E(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var VP=I_(),JP=C_(),WP=N_(),KP=M_(),GP=j_(),XP=Z_(),YP=D_(),QP=q_(),e1=U_(),t1=F_(),r1=[VP.default,JP.default,WP.default,KP.default,GP.default,XP.default,YP.default,QP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},e1.default,t1.default];df.default=r1});var pf=E(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.validateAdditionalItems=void 0;var gn=J(),ff=re(),n1={message:({params:{len:t}})=>(0,gn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,gn._)`{limit: ${t}}`},o1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:n1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,ff.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}B_(t,n)}};function B_(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,gn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,gn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ff.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,gn._)`${a} <= ${e.length}`);r.if((0,gn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:ff.Type.Num},u),i.allErrors||r.if((0,gn.not)(u),()=>r.break())})}}_s.validateAdditionalItems=B_;_s.default=o1});var mf=E(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});vs.validateTuple=void 0;var V_=J(),aa=re(),s1=ft(),i1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return J_(t,"additionalItems",e);r.items=!0,!(0,aa.alwaysValidSchema)(r,e)&&t.ok((0,s1.validateArray)(t))}};function J_(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=aa.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,V_._)`${s}.length`);r.forEach((d,m)=>{(0,aa.alwaysValidSchema)(a,d)||(n.if((0,V_._)`${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,g=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(m.strictTuples&&!g){let h=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,aa.checkStrictMode)(a,h,m.strictTuples)}}}vs.validateTuple=J_;vs.default=i1});var W_=E(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var a1=mf(),c1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,a1.validateTuple)(t,"items")};hf.default=c1});var G_=E(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var K_=J(),u1=re(),l1=ft(),d1=pf(),f1={message:({params:{len:t}})=>(0,K_.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,K_._)`{limit: ${t}}`},p1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:f1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,u1.alwaysValidSchema)(n,e)&&(o?(0,d1.validateAdditionalItems)(t,o):t.ok((0,l1.validateArray)(t)))}};gf.default=p1});var X_=E(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var mt=J(),ca=re(),m1={message:({params:{min:t,max:e}})=>e===void 0?(0,mt.str)`must contain at least ${t} valid item(s)`:(0,mt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,mt._)`{minContains: ${t}}`:(0,mt._)`{minContains: ${t}, maxContains: ${e}}`},h1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:m1,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,mt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ca.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ca.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ca.alwaysValidSchema)(s,r)){let g=(0,mt._)`${l} >= ${i}`;a!==void 0&&(g=(0,mt._)`${g} && ${l} <= ${a}`),t.pass(g);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,mt._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let g=e.name("_valid"),h=e.let("count",0);p(g,()=>e.if(g,()=>f(h)))}function p(g,h){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:ca.Type.Num,compositeRule:!0},g),h()})}function f(g){e.code((0,mt._)`${g}++`),a===void 0?e.if((0,mt._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,mt._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,mt._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};yf.default=h1});var e0=E(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.validateSchemaDeps=Zt.validatePropertyDeps=Zt.error=void 0;var _f=J(),g1=re(),xs=ft();Zt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,_f.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,_f._)`{property: ${t},
|
|
34
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,B._)`[${o}]`)}}}function NE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,B._)`${e} !== undefined`,()=>t.assign((0,B._)`${e}[${r}]`,n))}function _d(t,e,r,n=Vn.Correct){let o=n===Vn.Correct?B.operators.EQ:B.operators.NEQ,s;switch(t){case"null":return(0,B._)`${e} ${o} null`;case"array":s=(0,B._)`Array.isArray(${e})`;break;case"object":s=(0,B._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,B._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,B._)`typeof ${e} ${o} ${t}`}return n===Vn.Correct?s:(0,B.not)(s);function i(a=B.nil){return(0,B.and)((0,B._)`typeof ${e} == "number"`,a,r?(0,B._)`isFinite(${e})`:B.nil)}}De.checkDataType=_d;function vd(t,e,r,n){if(t.length===1)return _d(t[0],e,r,n);let o,s=(0,py.toHash)(t);if(s.array&&s.object){let i=(0,B._)`typeof ${e} != "object"`;o=s.null?i:(0,B._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=B.nil;s.number&&delete s.integer;for(let i in s)o=(0,B.and)(o,_d(i,e,r,n));return o}De.checkDataTypes=vd;var ME={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,B._)`{type: ${t}}`:(0,B._)`{type: ${e}}`};function xd(t){let e=jE(t);(0,PE.reportError)(e,ME)}De.reportTypeError=xd;function jE(t){let{gen:e,data:r,schema:n}=t,o=(0,py.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var yy=E(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});Bi.assignDefaults=void 0;var Jn=J(),ZE=re();function DE(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)gy(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>gy(t,s,o.default))}Bi.assignDefaults=DE;function gy(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Jn._)`${s}${(0,Jn.getProperty)(e)}`;if(o){(0,ZE.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Jn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Jn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Jn._)`${a} = ${(0,Jn.stringify)(r)}`)}});var pt=E(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var ge=J(),bd=re(),br=tr(),LE=re();function qE(t,e){let{gen:r,data:n,it:o}=t;r.if($d(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}le.checkReportMissingProp=qE;function UE({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)($d(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}le.checkMissingProp=UE;function FE(t,e){t.setParams({missingProperty:e},!0),t.error()}le.reportMissingProp=FE;function _y(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=_y;function wd(t,e,r){return(0,ge._)`${_y(t)}.call(${e}, ${r})`}le.isOwnProperty=wd;function HE(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${wd(t,e,r)}`:o}le.propertyInData=HE;function $d(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(wd(t,e,r))):o}le.noPropertyInData=$d;function vy(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=vy;function BE(t,e){return vy(e).filter(r=>!(0,bd.alwaysValidSchema)(t,e[r]))}le.schemaProperties=BE;function VE({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=[[br.default.instancePath,(0,ge.strConcat)(br.default.instancePath,s)],[br.default.parentData,i.parentData],[br.default.parentDataProperty,i.parentDataProperty],[br.default.rootData,br.default.rootData]];i.opts.dynamicRef&&d.push([br.default.dynamicAnchors,br.default.dynamicAnchors]);let m=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${m})`:(0,ge._)`${a}(${m})`}le.callValidateCode=VE;var JE=(0,ge._)`new RegExp`;function WE({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"?JE:(0,LE.useFunc)(t,o)}(${r}, ${n})`})}le.usePattern=WE;function KE(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:bd.Type.Num},s),e.if((0,ge.not)(s),a)})}}le.validateArray=KE;function GE(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,bd.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}le.validateUnion=GE});var wy=E(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.validateKeywordUsage=jt.validSchemaType=jt.funcKeywordCode=jt.macroKeywordCode=void 0;var Ve=J(),dn=tr(),XE=pt(),YE=rs();function QE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=by(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}jt.macroKeywordCode=QE;function ez(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;rz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=by(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)g(),e.modifying&&xy(t),h(()=>t.error());else{let _=e.async?p():f();e.modifying&&xy(t),h(()=>tz(t,_))}}function p(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,Ve._)`await `),v=>n.assign(d,!1).if((0,Ve._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,Ve._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,Ve._)`${l}.errors`;return n.assign(_,null),g(Ve.nil),_}function g(_=e.async?(0,Ve._)`await `:Ve.nil){let v=c.opts.passContext?dn.default.this:dn.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ve._)`${_}${(0,XE.callValidateCode)(t,l,v,y)}`,e.modifying)}function h(_){var v;n.if((0,Ve.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}jt.funcKeywordCode=ez;function xy(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function tz(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(dn.default.vErrors,(0,Ve._)`${dn.default.vErrors} === null ? ${e} : ${dn.default.vErrors}.concat(${e})`).assign(dn.default.errors,(0,Ve._)`${dn.default.vErrors}.length`),(0,YE.extendErrors)(t)},()=>t.error())}function rz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function by(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ve.stringify)(r)})}function nz(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")}jt.validSchemaType=nz;function oz({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)}}jt.validateKeywordUsage=oz});var ky=E(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.extendSubschemaMode=wr.extendSubschemaData=wr.getSubschema=void 0;var Zt=J(),$y=re();function sz(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,$y.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')}wr.getSubschema=sz;function iz(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,$y.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]}}wr.extendSubschemaData=iz;function az(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}wr.extendSubschemaMode=az});var kd=E((w4,Sy)=>{"use strict";Sy.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 Ey=E(($4,Ty)=>{"use strict";var $r=Ty.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(){};Vi(e,n,o,t,"",t)};$r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};$r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};$r.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};$r.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 Vi(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 $r.arrayKeywords)for(var m=0;m<d.length;m++)Vi(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in $r.propsKeywords){if(d&&typeof d=="object")for(var p in d)Vi(t,e,r,d[p],o+"/"+l+"/"+cz(p),s,o,l,n,p)}else(l in $r.keywords||t.allKeys&&!(l in $r.skipKeywords))&&Vi(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function cz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var os=E(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var uz=re(),lz=kd(),dz=Ey(),fz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function pz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Sd(t):e?zy(t)<=e:!1}et.inlineRef=pz;var mz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Sd(t){for(let e in t){if(mz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Sd)||typeof r=="object"&&Sd(r))return!0}return!1}function zy(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!fz.has(r)&&(typeof t[r]=="object"&&(0,uz.eachItem)(t[r],n=>e+=zy(n)),e===1/0))return 1/0}return e}function Ry(t,e="",r){r!==!1&&(e=Wn(e));let n=t.parse(e);return Py(t,n)}et.getFullPath=Ry;function Py(t,e){return t.serialize(e).split("#")[0]+"#"}et._getFullPath=Py;var hz=/#\/?$/;function Wn(t){return t?t.replace(hz,""):""}et.normalizeId=Wn;function gz(t,e,r){return r=Wn(r),t.resolve(e,r)}et.resolveUrl=gz;var yz=/^[a-z_][-a-z0-9._]*$/i;function _z(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Wn(t[r]||e),s={"":o},i=Ry(n,o,!1),a={},c=new Set;return dz(t,{allKeys:!0},(d,m,p,f)=>{if(f===void 0)return;let g=i+m,h=s[f];typeof d[r]=="string"&&(h=_.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[m]=h;function _(y){let x=this.opts.uriResolver.resolve;if(y=Wn(h?x(h,y):y),c.has(y))throw l(y);c.add(y);let $=this.refs[y];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,y):y!==Wn(g)&&(y[0]==="#"?(u(d,a[y],y),a[y]=d):this.refs[y]=g),y}function v(y){if(typeof y=="string"){if(!yz.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(d,m,p){if(m!==void 0&&!lz(d,m))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}et.getSchemaRefs=_z});var as=E(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.getData=kr.KeywordCxt=kr.validateFunctionCode=void 0;var Ny=ly(),Iy=ns(),Ed=yd(),Ji=ns(),vz=yy(),is=wy(),Td=ky(),j=J(),U=tr(),xz=os(),rr=re(),ss=rs();function bz(t){if(Zy(t)&&(Dy(t),jy(t))){kz(t);return}My(t,()=>(0,Ny.topBoolOrEmptySchema)(t))}kr.validateFunctionCode=bz;function My({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,j._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{t.code((0,j._)`"use strict"; ${Cy(r,o)}`),$z(t,o),t.code(s)}):t.func(e,(0,j._)`${U.default.data}, ${wz(o)}`,n.$async,()=>t.code(Cy(r,o)).code(s))}function wz(t){return(0,j._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${t.dynamicRef?(0,j._)`, ${U.default.dynamicAnchors}={}`:j.nil}}={}`}function $z(t,e){t.if(U.default.valCxt,()=>{t.var(U.default.instancePath,(0,j._)`${U.default.valCxt}.${U.default.instancePath}`),t.var(U.default.parentData,(0,j._)`${U.default.valCxt}.${U.default.parentData}`),t.var(U.default.parentDataProperty,(0,j._)`${U.default.valCxt}.${U.default.parentDataProperty}`),t.var(U.default.rootData,(0,j._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,j._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{t.var(U.default.instancePath,(0,j._)`""`),t.var(U.default.parentData,(0,j._)`undefined`),t.var(U.default.parentDataProperty,(0,j._)`undefined`),t.var(U.default.rootData,U.default.data),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,j._)`{}`)})}function kz(t){let{schema:e,opts:r,gen:n}=t;My(t,()=>{r.$comment&&e.$comment&&qy(t),Rz(t),n.let(U.default.vErrors,null),n.let(U.default.errors,0),r.unevaluated&&Sz(t),Ly(t),Cz(t)})}function Sz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,j._)`${r}.evaluated`),e.if((0,j._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${t.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${t.evaluated}.items`,(0,j._)`undefined`))}function Cy(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${r} */`:j.nil}function Tz(t,e){if(Zy(t)&&(Dy(t),jy(t))){Ez(t,e);return}(0,Ny.boolOrEmptySchema)(t,e)}function jy({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 Zy(t){return typeof t.schema!="boolean"}function Ez(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&qy(t),Pz(t),Iz(t);let s=n.const("_errs",U.default.errors);Ly(t,s),n.var(e,(0,j._)`${s} === ${U.default.errors}`)}function Dy(t){(0,rr.checkUnknownRules)(t),zz(t)}function Ly(t,e){if(t.opts.jtd)return Ay(t,[],!1,e);let r=(0,Iy.getSchemaTypes)(t.schema),n=(0,Iy.coerceAndCheckDataType)(t,r);Ay(t,r,!n,e)}function zz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,rr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Rz(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,rr.checkStrictMode)(t,"default is ignored in the schema root")}function Pz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,xz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Iz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function qy({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,j._)`${U.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,j.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,j._)`${U.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Cz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,j._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,j._)`new ${o}(${U.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,U.default.vErrors),s.unevaluated&&Az(t),e.return((0,j._)`${U.default.errors} === 0`))}function Az({gen:t,evaluated:e,props:r,items:n}){r instanceof j.Name&&t.assign((0,j._)`${e}.props`,r),n instanceof j.Name&&t.assign((0,j._)`${e}.items`,n)}function Ay(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,rr.schemaHasRulesButRef)(s,l))){o.block(()=>Fy(t,"$ref",l.all.$ref.definition));return}c.jtd||Oz(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,Ed.shouldUseGroup)(s,m)&&(m.type?(o.if((0,Ji.checkDataType)(m.type,i,c.strictNumbers)),Oy(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,Ji.reportTypeError)(t)),o.endIf()):Oy(t,m),a||o.if((0,j._)`${U.default.errors} === ${n||0}`))}}function Oy(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,vz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Ed.shouldUseRule)(n,s)&&Fy(t,s.keyword,s.definition,e.type)})}function Oz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Nz(t,e),t.opts.allowUnionTypes||Mz(t,e),jz(t,t.dataTypes))}function Nz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Uy(t.dataTypes,r)||zd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Dz(t,e)}}function Mz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&zd(t,"use allowUnionTypes to allow union type keyword")}function jz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ed.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Zz(e,i))&&zd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Zz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Uy(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Dz(t,e){let r=[];for(let n of t.dataTypes)Uy(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function zd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,rr.checkStrictMode)(t,e,t.opts.strictTypes)}var Wi=class{constructor(e,r,n){if((0,is.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,rr.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",Hy(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,is.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",U.default.errors))}result(e,r,n){this.failResult((0,j.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,j.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,j._)`${r} !== undefined && (${(0,j.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?ss.reportExtraError:ss.reportError)(this,this.def.error,r)}$dataError(){(0,ss.reportError)(this,this.def.$dataError||ss.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ss.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=j.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=j.nil,r=j.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,j.or)((0,j._)`${o} === undefined`,r)),e!==j.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,j.or)(i(),a());function i(){if(n.length){if(!(r instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,Ji.checkDataTypes)(c,r,s.opts.strictNumbers,Ji.DataType.Wrong)}`}return j.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,j._)`!${c}(${r})`}return j.nil}}subschema(e,r){let n=(0,Td.getSubschema)(this.it,e);(0,Td.extendSubschemaData)(n,this.it,e),(0,Td.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Tz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=rr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=rr.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,j.Name)),!0}};kr.KeywordCxt=Wi;function Fy(t,e,r,n){let o=new Wi(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,is.funcKeywordCode)(o,r):"macro"in r?(0,is.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,is.funcKeywordCode)(o,r)}var Lz=/^\/(?:[^~]|~0|~1)*$/,qz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Hy(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return U.default.rootData;if(t[0]==="/"){if(!Lz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=U.default.rootData}else{let u=qz.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,j._)`${s}${(0,j.getProperty)((0,rr.unescapeJsonPointer)(u))}`,i=(0,j._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}kr.getData=Hy});var Ki=E(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var Rd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Pd.default=Rd});var cs=E(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var Id=os(),Cd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Id.resolveUrl)(e,r,n),this.missingSchema=(0,Id.normalizeId)((0,Id.getFullPath)(e,this.missingRef))}};Ad.default=Cd});var Xi=E(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.resolveSchema=mt.getCompilingSchema=mt.resolveRef=mt.compileSchema=mt.SchemaEnv=void 0;var St=J(),Uz=Ki(),fn=tr(),Tt=os(),By=re(),Fz=as(),Kn=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,Tt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};mt.SchemaEnv=Kn;function Nd(t){let e=Vy.call(this,t);if(e)return e;let r=(0,Tt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new St.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Uz.default,code:(0,St._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:fn.default.data,parentData:fn.default.parentData,parentDataProperty:fn.default.parentDataProperty,dataNames:[fn.default.data],dataPathArr:[St.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,St.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:St.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,St._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Fz.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(fn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${fn.default.self}`,`${fn.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:g}=u;p.evaluated={props:f instanceof St.Name?void 0:f,items:g instanceof St.Name?void 0:g,dynamicProps:f instanceof St.Name,dynamicItems:g instanceof St.Name},p.source&&(p.source.evaluated=(0,St.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)}}mt.compileSchema=Nd;function Hz(t,e,r){var n;r=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Jz.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 Kn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Bz.call(this,s)}mt.resolveRef=Hz;function Bz(t){return(0,Tt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Nd.call(this,t)}function Vy(t){for(let e of this._compilations)if(Vz(e,t))return e}mt.getCompilingSchema=Vy;function Vz(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Jz(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Gi.call(this,t,e)}function Gi(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Tt._getFullPath)(this.opts.uriResolver,r),o=(0,Tt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Od.call(this,r,t);let s=(0,Tt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Gi.call(this,t,i);return typeof a?.schema!="object"?void 0:Od.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Nd.call(this,i),s===(0,Tt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Tt.resolveUrl)(this.opts.uriResolver,o,u)),new Kn({schema:a,schemaId:c,root:t,baseId:o})}return Od.call(this,r,i)}}mt.resolveSchema=Gi;var Wz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Od(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,By.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Wz.has(a)&&u&&(e=(0,Tt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,By.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Gi.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Kn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Jy=E((R4,Kz)=>{Kz.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 qd=E((P4,e_)=>{"use strict";var Gz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),jd=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),Xz=RegExp.prototype.test.bind(/^\d*$/u),pn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Zd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Ky=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Dd=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),Yz=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),tt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)tt[e]="%"+t[e>>4]+t[e&15]}function Le(t){return t<2048?tt[192|t>>6]+tt[128|t&63]:t<65536?tt[224|t>>12]+tt[128|t>>6&63]+tt[128|t&63]:tt[240|t>>18]+tt[128|t>>12&63]+tt[128|t>>6&63]+tt[128|t&63]}function Qz(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 eR=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),tR=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),rR=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),nR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function oR(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!rR(t[e])){if(t[e]==="%"&&e+2<t.length&&pn(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function Wy(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 sR(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||!jd(c))return;s+=2;continue}if(!eR(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:Wy(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 Wy(i)}function Md(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&&tR(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(iR(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),!oR(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=sR(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function iR(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function aR(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 cR={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},uR=/[@/?#:]/g,lR=/[@/?#]/g;function Gy(t,e){let r=e?lR:uR;return r.lastIndex=0,t.replace(r,n=>cR[n])}function Xy(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(pn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Zd(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function dR(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(pn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Zd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Ky(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=Qy(o)?n:tt[o];else if(o<55296||o>57343)e+=Le(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Le(65536+(o-55296<<10)+(s-56320)),r++):e+=Le(65533)}else e+=Le(65533)}}return e}function fR(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(pn(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),Ky(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=tt[i];else if(i<55296||i>57343)r+=Le(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=Le(65536+(i-55296<<10)+(a-56320)),o++):r+=Le(65533)}else r+=Le(65533)}}return r}function Ld(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(pn(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=tt[s];else if(s<55296||s>57343)r+=Le(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Le(65536+(s-55296<<10)+(i-56320)),n++):r+=Le(65533)}else r+=Le(65533)}}return r}function Yy(t){return Ld(t,Yz)}function pR(t){return Ld(t,Dd)}function mR(t){return Ld(t,Dd)}function Qy(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 hR(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(pn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Zd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Dd(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=Qy(o)?n:tt[o];else if(o<55296||o>57343)e+=Le(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Le(65536+(o-55296<<10)+(s-56320)),r++):e+=Le(65533)}else e+=Le(65533)}}return e}function gR(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(pn(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function yR(t){let e=[];if(t.userinfo!==void 0&&(e.push(Yy(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!jd(r)){let n=Md(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=Xy(r,!0),n=Md(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=Gy(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!Xz(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}e_.exports={nonSimpleDomain:nR,recomposeAuthority:yR,reescapeHostDelimiters:Gy,normalizePercentEncoding:Xy,normalizePathEncoding:dR,serializePathEncoding:fR,normalizeQueryFragmentEncoding:hR,encodeUserinfo:Yy,encodeQuery:pR,encodeFragment:mR,escapePreservingEscapes:gR,removeDotSegments:aR,isIPv4:jd,isUUID:Gz,normalizeIPv6:Md,stringArrayToHexStripped:Qz}});var s_=E((I4,o_)=>{"use strict";var{isUUID:_R}=qd(),vR=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,xR=["http","https","ws","wss","urn","urn:uuid"];function bR(t){return xR.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 t_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function r_(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 wR(t){return t.secure=Ud(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function $R(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 kR(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(vR);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=Fd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function SR(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=Fd(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 TR(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!_R(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function ER(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var n_={scheme:"http",domainHost:!0,parse:t_,serialize:r_},zR={scheme:"https",domainHost:n_.domainHost,parse:t_,serialize:r_},Yi={scheme:"ws",domainHost:!0,parse:wR,serialize:$R},RR={scheme:"wss",domainHost:Yi.domainHost,parse:Yi.parse,serialize:Yi.serialize},PR={scheme:"urn",parse:kR,serialize:SR,skipNormalize:!0},IR={scheme:"urn:uuid",parse:TR,serialize:ER,skipNormalize:!0},Qi={http:n_,https:zR,ws:Yi,wss:RR,urn:PR,"urn:uuid":IR};Object.setPrototypeOf(Qi,null);function Fd(t){return t&&(Qi[t]||Qi[t.toLowerCase()])||void 0}o_.exports={wsIsSecure:Ud,SCHEMES:Qi,isValidSchemeName:bR,getSchemeHandler:Fd}});var __=E((C4,ra)=>{"use strict";var{normalizeIPv6:l_,removeDotSegments:ls,recomposeAuthority:CR,normalizePercentEncoding:Hd,normalizePathEncoding:AR,serializePathEncoding:i_,normalizeQueryFragmentEncoding:a_,encodeQuery:OR,encodeFragment:NR,reescapeHostDelimiters:MR,isIPv4:d_,nonSimpleDomain:jR}=qd(),{SCHEMES:f_,getSchemeHandler:Bd}=s_(),p_=/^[A-Za-z][A-Za-z0-9+.-]*$/u,m_="URI scheme is malformed.";function c_(t){let e=unescape(String(t));if(!p_.test(e))throw new TypeError(m_);return e}function ZR(t,e){return typeof t=="string"?t=VR(t,e):typeof t=="object"&&(t=ta(mn(t,e),e)),t}function DR(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}=ea(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:m,malformedSchemeSpecific:p,malformedHost:f,malformedScheme:g}=ea(e,n);if(s||d||i||m||a||p||c||f||u||g)throw new Error(o.error||l.error||"URI is malformed.");let h=h_(o,l,n,!0),_=Bd(r&&r.scheme||h.scheme),v=h.host,y=v!==void 0&&v!==""&&(d_(v)||l_(v).isIPV6);g_(h,r||{},_,y);let x=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(h.error&&!x)throw new Error(h.error);return n.skipEscape=!0,mn(h,n)}function h_(t,e,r,n){let o={};return n||(t=ta(mn(t,r),r),e=ta(mn(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=ls(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=ls(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ls(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=ls(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 LR(t,e,r){let n=u_(t,r),o=u_(e,r);return n!==void 0&&o!==void 0&&n===o}function mn(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=c_(r.scheme));let s=Bd(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=Hd(r.path):r.path=i_(r.path,a)),n.reference!=="suffix"&&r.scheme&&(r.scheme=c_(r.scheme),o.push(r.scheme,":"));let c=CR(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=ls(u)),a&&(u=i_(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return r.query!==void 0&&o.push("?",OR(r.query)),r.fragment!==void 0&&o.push("#",NR(r.fragment)),o.join("")}var qR=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,UR=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,FR=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function HR(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 us(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 Vd(t){return t[0]==="["&&t[t.length-1]==="]"}function BR(t){let e=t[4];return us(t[3])||e!==void 0&&!Vd(e)&&us(e)||us(t[6])||us(t[7])||us(t[8])}function g_(t,e,r,n){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!Vd(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&jR(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 ea(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(UR);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let m=t.match(FR);if(m!==null){let f=m[1],g=f.replace(/[\t\n\r]/g,"");g.length>=2&&(g.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==g.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let p=t.match(qR);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 h=unescape(n.scheme);p_.test(h)?n.scheme=h.toLowerCase():(n.error=n.error||m_,u=!0)}s=BR(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let f=HR(n,p);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(d_(n.host)===!1){let _=Vd(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=l_(n.host);l=y.isIPV6||y.isIPVFuture===!0,c=v&&(!_||y.error===!0),n.host=l?y.host:y.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 g=Bd(r.scheme||n.scheme);if(c||(a=g_(n,r,g,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let h=l?n.host:Hd(n.host,!0);l||(h=Hd(h.toLowerCase())),n.host=MR(h,l)}(!g||g&&!g.skipNormalize)&&(n.path&&(n.path=AR(n.path)),n.query&&(n.query=a_(n.query)),n.fragment&&(n.fragment=a_(n.fragment))),g&&g.parse&&(g.parse(n,r),g===f_.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 ta(t,e){return ea(t,e).parsed}function VR(t,e){return y_(t,e).normalized}function y_(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=ea(t,e);return{normalized:n||o||s||i||a?t:mn(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function u_(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:mn(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=y_(r,e);return o||s||i||a||c?void 0:n}var Jd={SCHEMES:f_,normalize:ZR,resolve:DR,resolveComponent:h_,equal:LR,serialize:mn,parse:ta};ra.exports=Jd;ra.exports.default=Jd;ra.exports.fastUri=Jd});var x_=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var v_=__();v_.code='require("ajv/dist/runtime/uri").default';Wd.default=v_});var z_=E(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=void 0;var JR=as();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return JR.KeywordCxt}});var Gn=J();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Gn._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Gn.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Gn.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Gn.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Gn.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Gn.CodeGen}});var WR=Ki(),S_=cs(),KR=gd(),ds=Xi(),GR=J(),fs=os(),na=ns(),Gd=re(),b_=Jy(),XR=x_(),T_=(t,e)=>new RegExp(t,e);T_.code="new RegExp";var YR=["removeAdditional","useDefaults","coerceTypes"],QR=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),eP={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."},tP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},w_=200;function rP(t){var e,r,n,o,s,i,a,c,u,l,d,m,p,f,g,h,_,v,y,x,$,O,C,ae,ce;let Ee=t.strict,F=(e=t.code)===null||e===void 0?void 0:e.optimize,_e=F===!0||F===void 0?1:F||0,Pt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:T_,Or=(o=t.uriResolver)!==null&&o!==void 0?o:XR.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ee)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Ee)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Ee)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:Ee)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:Ee)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:_e,regExp:Pt}:{optimize:_e,regExp:Pt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:w_,loopEnum:(h=t.loopEnum)!==null&&h!==void 0?h:w_,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(y=t.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(O=t.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(C=t.validateFormats)!==null&&C!==void 0?C:!0,unicodeRegExp:(ae=t.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(ce=t.int32range)!==null&&ce!==void 0?ce:!0,uriResolver:Or}}var ps=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,...rP(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new GR.ValueScope({scope:{},prefixes:QR,es5:r,lines:n}),this.logger=cP(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,KR.getRules)(),$_.call(this,eP,e,"NOT SUPPORTED"),$_.call(this,tP,e,"DEPRECATED","warn"),this._metaOpts=iP.call(this),e.formats&&oP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&sP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),nP.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=b_;n==="id"&&(o={...b_},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 S_.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,fs.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=k_.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ds.SchemaEnv({schema:{},schemaId:n});if(r=ds.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=k_.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,fs.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(lP.call(this,n,r),!r)return(0,Gd.eachItem)(n,s=>Kd.call(this,s)),this;fP.call(this,r);let o={...r,type:(0,na.getJSONTypes)(r.type),schemaType:(0,na.getJSONTypes)(r.schemaType)};return(0,Gd.eachItem)(n,o.type.length===0?s=>Kd.call(this,s,o):s=>o.type.forEach(i=>Kd.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]=E_(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,fs.normalizeId)(i||n);let u=fs.getSchemaRefs.call(this,e,n);return c=new ds.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):ds.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{ds.compileSchema.call(this,e)}finally{this.opts=r}}};ps.ValidationError=WR.default;ps.MissingRefError=S_.default;Ae.default=ps;function $_(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 k_(t){return t=(0,fs.normalizeId)(t),this.schemas[t]||this.refs[t]}function nP(){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 oP(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function sP(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 iP(){let t={...this.opts};for(let e of YR)delete t[e];return t}var aP={log(){},warn(){},error(){}};function cP(t){if(t===!1)return aP;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 uP=/^[a-z_$][a-z0-9_$:-]*$/i;function lP(t,e){let{RULES:r}=this;if((0,Gd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!uP.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 Kd(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,na.getJSONTypes)(e.type),schemaType:(0,na.getJSONTypes)(e.schemaType)}};e.before?dP.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 dP(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 fP(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=E_(e)),t.validateSchema=this.compile(e,!0))}var pP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function E_(t){return{anyOf:[t,pP]}}});var R_=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var mP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xd.default=mP});var A_=E(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.callRef=hn.getValidate=void 0;var hP=cs(),P_=pt(),rt=J(),Xn=tr(),I_=Xi(),oa=re(),gP={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=I_.resolveRef.call(c,u,o,r);if(l===void 0)throw new hP.default(n.opts.uriResolver,o,r);if(l instanceof I_.SchemaEnv)return m(l);return p(l);function d(){if(s===u)return sa(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return sa(t,(0,rt._)`${f}.validate`,u,u.$async)}function m(f){let g=C_(t,f);sa(t,g,f,f.$async)}function p(f){let g=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,rt.stringify)(f)}:{ref:f}),h=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:rt.nil,topSchemaRef:g,errSchemaPath:r},h);t.mergeEvaluated(_),t.ok(h)}}};function C_(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,rt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}hn.getValidate=C_;function sa(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Xn.default.this:rt.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,rt._)`await ${(0,P_.callValidateCode)(t,e,u)}`),p(e),i||o.assign(f,!0)},g=>{o.if((0,rt._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),m(g),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,P_.callValidateCode)(t,e,u),()=>p(e),()=>m(e))}function m(f){let g=(0,rt._)`${f}.errors`;o.assign(Xn.default.vErrors,(0,rt._)`${Xn.default.vErrors} === null ? ${g} : ${Xn.default.vErrors}.concat(${g})`),o.assign(Xn.default.errors,(0,rt._)`${Xn.default.vErrors}.length`)}function p(f){var g;if(!s.opts.unevaluated)return;let h=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(h&&!h.dynamicProps)h.props!==void 0&&(s.props=oa.mergeEvaluated.props(o,h.props,s.props));else{let _=o.var("props",(0,rt._)`${f}.evaluated.props`);s.props=oa.mergeEvaluated.props(o,_,s.props,rt.Name)}if(s.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(s.items=oa.mergeEvaluated.items(o,h.items,s.items));else{let _=o.var("items",(0,rt._)`${f}.evaluated.items`);s.items=oa.mergeEvaluated.items(o,_,s.items,rt.Name)}}}hn.callRef=sa;hn.default=gP});var O_=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var yP=R_(),_P=A_(),vP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",yP.default,_P.default];Yd.default=vP});var N_=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var ia=J(),Sr=ia.operators,aa={maximum:{okStr:"<=",ok:Sr.LTE,fail:Sr.GT},minimum:{okStr:">=",ok:Sr.GTE,fail:Sr.LT},exclusiveMaximum:{okStr:"<",ok:Sr.LT,fail:Sr.GTE},exclusiveMinimum:{okStr:">",ok:Sr.GT,fail:Sr.LTE}},xP={message:({keyword:t,schemaCode:e})=>(0,ia.str)`must be ${aa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ia._)`{comparison: ${aa[t].okStr}, limit: ${e}}`},bP={keyword:Object.keys(aa),type:"number",schemaType:"number",$data:!0,error:xP,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ia._)`${r} ${aa[e].fail} ${n} || isNaN(${r})`)}};Qd.default=bP});var M_=E(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var ms=J(),wP={message:({schemaCode:t})=>(0,ms.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ms._)`{multipleOf: ${t}}`},$P={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:wP,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ms._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ms._)`${i} !== parseInt(${i})`;t.fail$data((0,ms._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};ef.default=$P});var Z_=E(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});function j_(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}tf.default=j_;j_.code='require("ajv/dist/runtime/ucs2length").default'});var D_=E(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var gn=J(),kP=re(),SP=Z_(),TP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,gn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,gn._)`{limit: ${t}}`},EP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:TP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?gn.operators.GT:gn.operators.LT,i=o.opts.unicode===!1?(0,gn._)`${r}.length`:(0,gn._)`${(0,kP.useFunc)(t.gen,SP.default)}(${r})`;t.fail$data((0,gn._)`${i} ${s} ${n}`)}};rf.default=EP});var L_=E(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var zP=pt(),RP=re(),Yn=J(),PP={message:({schemaCode:t})=>(0,Yn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Yn._)`{pattern: ${t}}`},IP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:PP,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,Yn._)`new RegExp`:(0,RP.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Yn._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Yn._)`!${l}`)}else{let c=(0,zP.usePattern)(t,o);t.fail$data((0,Yn._)`!${c}.test(${r})`)}}};nf.default=IP});var q_=E(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var hs=J(),CP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,hs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,hs._)`{limit: ${t}}`},AP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:CP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?hs.operators.GT:hs.operators.LT;t.fail$data((0,hs._)`Object.keys(${r}).length ${o} ${n}`)}};of.default=AP});var U_=E(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var gs=pt(),ys=J(),OP=re(),NP={message:({params:{missingProperty:t}})=>(0,ys.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ys._)`{missingProperty: ${t}}`},MP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:NP,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 g of r)if(p?.[g]===void 0&&!f.has(g)){let h=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${g}" is not defined at "${h}" (strictRequired)`;(0,OP.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ys.nil,d);else for(let p of r)(0,gs.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,gs.checkMissingProp)(t,r,p)),(0,gs.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,gs.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function m(p,f){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,gs.propertyInData)(e,o,p,a.ownProperties)),e.if((0,ys.not)(f),()=>{t.error(),e.break()})},ys.nil)}}};sf.default=MP});var F_=E(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var _s=J(),jP={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,_s.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,_s._)`{limit: ${t}}`},ZP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:jP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?_s.operators.GT:_s.operators.LT;t.fail$data((0,_s._)`${r}.length ${o} ${n}`)}};af.default=ZP});var ca=E(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var H_=kd();H_.code='require("ajv/dist/runtime/equal").default';cf.default=H_});var B_=E(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var uf=ns(),Oe=J(),DP=re(),LP=ca(),qP={message:({params:{i:t,j:e}})=>(0,Oe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Oe._)`{i: ${t}, j: ${e}}`},UP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:qP,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,uf.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Oe._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Oe._)`${r}.length`),g=e.let("j");t.setParams({i:f,j:g}),e.assign(c,!0),e.if((0,Oe._)`${f} > 1`,()=>(d()?m:p)(f,g))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function m(f,g){let h=e.name("item"),_=(0,uf.checkDataTypes)(u,h,a.opts.strictNumbers,uf.DataType.Wrong),v=e.const("indices",(0,Oe._)`{}`);e.for((0,Oe._)`;${f}--;`,()=>{e.let(h,(0,Oe._)`${r}[${f}]`),e.if(_,(0,Oe._)`continue`),u.length>1&&e.if((0,Oe._)`typeof ${h} == "string"`,(0,Oe._)`${h} += "_"`),e.if((0,Oe._)`typeof ${v}[${h}] == "number"`,()=>{e.assign(g,(0,Oe._)`${v}[${h}]`),t.error(),e.assign(c,!1).break()}).code((0,Oe._)`${v}[${h}] = ${f}`)})}function p(f,g){let h=(0,DP.useFunc)(e,LP.default),_=e.name("outer");e.label(_).for((0,Oe._)`;${f}--;`,()=>e.for((0,Oe._)`${g} = ${f}; ${g}--;`,()=>e.if((0,Oe._)`${h}(${r}[${f}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};lf.default=UP});var V_=E(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var df=J(),FP=re(),HP=ca(),BP={message:"must be equal to constant",params:({schemaCode:t})=>(0,df._)`{allowedValue: ${t}}`},VP={keyword:"const",$data:!0,error:BP,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,df._)`!${(0,FP.useFunc)(e,HP.default)}(${r}, ${o})`):t.fail((0,df._)`${s} !== ${r}`)}};ff.default=VP});var J_=E(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var vs=J(),JP=re(),WP=ca(),KP={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,vs._)`{allowedValues: ${t}}`},GP={keyword:"enum",schemaType:"array",$data:!0,error:KP,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,JP.useFunc)(e,WP.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,vs.or)(...o.map((f,g)=>m(p,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,p=>e.if((0,vs._)`${u()}(${r}, ${p})`,()=>e.assign(l,!0).break()))}function m(p,f){let g=o[f];return typeof g=="object"&&g!==null?(0,vs._)`${u()}(${r}, ${p}[${f}])`:(0,vs._)`${r} === ${g}`}}};pf.default=GP});var W_=E(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var XP=N_(),YP=M_(),QP=D_(),e1=L_(),t1=q_(),r1=U_(),n1=F_(),o1=B_(),s1=V_(),i1=J_(),a1=[XP.default,YP.default,QP.default,e1.default,t1.default,r1.default,n1.default,o1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},s1.default,i1.default];mf.default=a1});var gf=E(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.validateAdditionalItems=void 0;var yn=J(),hf=re(),c1={message:({params:{len:t}})=>(0,yn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,yn._)`{limit: ${t}}`},u1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:c1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,hf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}K_(t,n)}};function K_(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,yn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,yn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,hf.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,yn._)`${a} <= ${e.length}`);r.if((0,yn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:hf.Type.Num},u),i.allErrors||r.if((0,yn.not)(u),()=>r.break())})}}xs.validateAdditionalItems=K_;xs.default=u1});var yf=E(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.validateTuple=void 0;var G_=J(),ua=re(),l1=pt(),d1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return X_(t,"additionalItems",e);r.items=!0,!(0,ua.alwaysValidSchema)(r,e)&&t.ok((0,l1.validateArray)(t))}};function X_(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=ua.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,G_._)`${s}.length`);r.forEach((d,m)=>{(0,ua.alwaysValidSchema)(a,d)||(n.if((0,G_._)`${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,g=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(m.strictTuples&&!g){let h=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,ua.checkStrictMode)(a,h,m.strictTuples)}}}bs.validateTuple=X_;bs.default=d1});var Y_=E(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var f1=yf(),p1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,f1.validateTuple)(t,"items")};_f.default=p1});var e0=E(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var Q_=J(),m1=re(),h1=pt(),g1=gf(),y1={message:({params:{len:t}})=>(0,Q_.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Q_._)`{limit: ${t}}`},_1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:y1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,m1.alwaysValidSchema)(n,e)&&(o?(0,g1.validateAdditionalItems)(t,o):t.ok((0,h1.validateArray)(t)))}};vf.default=_1});var t0=E(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var ht=J(),la=re(),v1={message:({params:{min:t,max:e}})=>e===void 0?(0,ht.str)`must contain at least ${t} valid item(s)`:(0,ht.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ht._)`{minContains: ${t}}`:(0,ht._)`{minContains: ${t}, maxContains: ${e}}`},x1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:v1,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,ht._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,la.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,la.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,la.alwaysValidSchema)(s,r)){let g=(0,ht._)`${l} >= ${i}`;a!==void 0&&(g=(0,ht._)`${g} && ${l} <= ${a}`),t.pass(g);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,ht._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let g=e.name("_valid"),h=e.let("count",0);p(g,()=>e.if(g,()=>f(h)))}function p(g,h){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:la.Type.Num,compositeRule:!0},g),h()})}function f(g){e.code((0,ht._)`${g}++`),a===void 0?e.if((0,ht._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ht._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ht._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};xf.default=x1});var o0=E(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.validateSchemaDeps=Dt.validatePropertyDeps=Dt.error=void 0;var bf=J(),b1=re(),ws=pt();Dt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,bf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,bf._)`{property: ${t},
|
|
35
35
|
missingProperty: ${n},
|
|
36
36
|
depsCount: ${e},
|
|
37
|
-
deps: ${r}}`};var y1={keyword:"dependencies",type:"object",schemaType:"object",error:Zt.error,code(t){let[e,r]=_1(t);Y_(t,e),Q_(t,r)}};function _1({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 Y_(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,xs.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,xs.checkReportMissingProp)(t,u)}):(r.if((0,_f._)`${c} && (${(0,xs.checkMissingProp)(t,a,s)})`),(0,xs.reportMissingProp)(t,s),r.else())}}Zt.validatePropertyDeps=Y_;function Q_(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,g1.alwaysValidSchema)(s,e[a])||(r.if((0,xs.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))}Zt.validateSchemaDeps=Q_;Zt.default=y1});var r0=E(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var t0=J(),v1=re(),x1={message:"property name must be valid",params:({params:t})=>(0,t0._)`{propertyName: ${t.propertyName}}`},b1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:x1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,v1.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,t0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};vf.default=b1});var bf=E(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var ua=ft(),Tt=J(),w1=er(),la=re(),$1={message:"must NOT have additional properties",params:({params:t})=>(0,Tt._)`{additionalProperty: ${t.additionalProperty}}`},k1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:$1,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,la.alwaysValidSchema)(i,r))return;let u=(0,ua.allSchemaProperties)(n.properties),l=(0,ua.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Tt._)`${s} === ${w1.default.errors}`);function d(){e.forIn("key",o,h=>{!u.length&&!l.length?f(h):e.if(m(h),()=>f(h))})}function m(h){let _;if(u.length>8){let v=(0,la.schemaRefOrVal)(i,n.properties,"properties");_=(0,ua.isOwnProperty)(e,v,h)}else u.length?_=(0,Tt.or)(...u.map(v=>(0,Tt._)`${h} === ${v}`)):_=Tt.nil;return l.length&&(_=(0,Tt.or)(_,...l.map(v=>(0,Tt._)`${(0,ua.usePattern)(t,v)}.test(${h})`))),(0,Tt.not)(_)}function p(h){e.code((0,Tt._)`delete ${o}[${h}]`)}function f(h){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(h);return}if(r===!1){t.setParams({additionalProperty:h}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,la.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(h,_,!1),e.if((0,Tt.not)(_),()=>{t.reset(),p(h)})):(g(h,_),a||e.if((0,Tt.not)(_),()=>e.break()))}}function g(h,_,v){let y={keyword:"additionalProperties",dataProp:h,dataPropType:la.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};xf.default=k1});var s0=E($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var S1=ss(),n0=ft(),wf=re(),o0=bf(),T1={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&&o0.default.code(new S1.KeywordCxt(s,o0.default,"additionalProperties"));let i=(0,n0.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=wf.mergeEvaluated.props(e,(0,wf.toHash)(i),s.props));let a=i.filter(d=>!(0,wf.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,n0.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)}}};$f.default=T1});var u0=E(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var i0=ft(),da=J(),a0=re(),c0=re(),E1={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,i0.allSchemaProperties)(r),c=a.filter(g=>(0,a0.alwaysValidSchema)(s,r[g]));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 da.Name)&&(s.props=(0,c0.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let g of a)u&&p(g),s.allErrors?f(g):(e.var(l,!0),f(g),e.if(l))}function p(g){for(let h in u)new RegExp(g).test(h)&&(0,a0.checkStrictMode)(s,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){e.forIn("key",n,h=>{e.if((0,da._)`${(0,i0.usePattern)(t,g)}.test(${h})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:c0.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,da._)`${d}[${h}]`,!0):!_&&!s.allErrors&&e.if((0,da.not)(l),()=>e.break())})})}}};kf.default=E1});var l0=E(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var z1=re(),R1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,z1.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"}};Sf.default=R1});var d0=E(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var P1=ft(),I1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:P1.validateUnion,error:{message:"must match a schema in anyOf"}};Tf.default=I1});var f0=E(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var fa=J(),C1=re(),A1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,fa._)`{passingSchemas: ${t.passing}}`},O1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:A1,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,C1.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,fa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,fa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,fa.Name)})})}}};Ef.default=O1});var p0=E(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var N1=re(),M1={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,N1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};zf.default=M1});var g0=E(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var pa=J(),h0=re(),j1={message:({params:t})=>(0,pa.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,pa._)`{failingKeyword: ${t.ifClause}}`},Z1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:j1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,h0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=m0(n,"then"),s=m0(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,pa.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,pa._)`${l}`):t.setParams({ifClause:l})}}}};function m0(t,e){let r=t.schema[e];return r!==void 0&&!(0,h0.alwaysValidSchema)(t,r)}Rf.default=Z1});var y0=E(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var D1=re(),L1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,D1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Pf.default=L1});var _0=E(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var q1=pf(),U1=W_(),F1=mf(),H1=G_(),B1=X_(),V1=e0(),J1=r0(),W1=bf(),K1=s0(),G1=u0(),X1=l0(),Y1=d0(),Q1=f0(),eI=p0(),tI=g0(),rI=y0();function nI(t=!1){let e=[X1.default,Y1.default,Q1.default,eI.default,tI.default,rI.default,J1.default,W1.default,V1.default,K1.default,G1.default];return t?e.push(U1.default,H1.default):e.push(q1.default,F1.default),e.push(B1.default),e}If.default=nI});var v0=E(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var ke=J(),oI={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},sI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:oI,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}),g=r.const("fDef",(0,ke._)`${f}[${i}]`),h=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,ke._)`${g}.type || "string"`).assign(_,(0,ke._)`${g}.validate`),()=>r.assign(h,(0,ke._)`"string"`).assign(_,g)),t.fail$data((0,ke.or)(v(),y()));function v(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function y(){let x=l.$async?(0,ke._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,$=(0,ke._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${h} === ${e} && !${$}`}}function p(){let f=d.formats[s];if(!f){v();return}if(f===!0)return;let[g,h,_]=y(f);g===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 y($){let O=$ instanceof RegExp?(0,ke.regexpCode)($):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,C=r.scopeValue("formats",{key:s,ref:$,code:O});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,ke._)`${C}.validate`]:["string",$,C]}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 h=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};Cf.default=sI});var x0=E(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var iI=v0(),aI=[iI.default];Af.default=aI});var b0=E(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.contentVocabulary=Yn.metadataVocabulary=void 0;Yn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Yn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var $0=E(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var cI=P_(),uI=H_(),lI=_0(),dI=x0(),w0=b0(),fI=[cI.default,uI.default,(0,lI.default)(),dI.default,w0.metadataVocabulary,w0.contentVocabulary];Of.default=fI});var S0=E(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.DiscrError=void 0;var k0;(function(t){t.Tag="tag",t.Mapping="mapping"})(k0||(ma.DiscrError=k0={}))});var E0=E(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Qn=J(),Nf=S0(),T0=Ki(),pI=is(),mI=re(),hI={message:({params:{discrError:t,tagName:e}})=>t===Nf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Qn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},gI={keyword:"discriminator",type:"object",schemaType:"object",error:hI,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,Qn._)`${r}${(0,Qn.getProperty)(a)}`);e.if((0,Qn._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Nf.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,Qn._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:Nf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(g,Qn.Name),f}function m(){var p;let f={},g=_(o),h=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,mI.schemaHasRulesButRef)($,s.self.RULES)){let C=$.$ref;if($=T0.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,C),$ instanceof T0.SchemaEnv&&($=$.schema),$===void 0)throw new pI.default(s.opts.uriResolver,s.baseId,C)}let O=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);h=h&&(g||_($)),v(O,x)}if(!h)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)y(x.const,$);else if(x.enum)for(let O of x.enum)y(O,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function y(x,$){if(typeof x!="string"||x in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[x]=$}}}};Mf.default=gI});var z0=E((dL,yI)=>{yI.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 Zf=E((ye,jf)=>{"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 _I=k_(),vI=$0(),xI=E0(),R0=z0(),bI=["/properties"],ha="http://json-schema.org/draft-07/schema",eo=class extends _I.default{_addVocabularies(){super._addVocabularies(),vI.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(xI.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(R0,bI):R0;this.addMetaSchema(e,ha,!1),this.refs["http://json-schema.org/schema"]=ha}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ha)?ha:void 0)}};ye.Ajv=eo;jf.exports=ye=eo;jf.exports.Ajv=eo;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=eo;var wI=ss();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return wI.KeywordCxt}});var to=J();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return to._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return to.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return to.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return to.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return to.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return to.CodeGen}});var $I=Ji();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return $I.default}});var kI=is();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return kI.default}})});var j0=E(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.formatNames=Lt.fastFormats=Lt.fullFormats=void 0;function Dt(t,e){return{validate:t,compare:e}}Lt.fullFormats={date:Dt(A0,Uf),time:Dt(Lf(!0),Ff),"date-time":Dt(P0(!0),N0),"iso-time":Dt(Lf(),O0),"iso-date-time":Dt(P0(),M0),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:PI,"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:jI,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:II,int32:{type:"number",validate:OI},int64:{type:"number",validate:NI},float:{type:"number",validate:C0},double:{type:"number",validate:C0},password:!0,binary:!0};Lt.fastFormats={...Lt.fullFormats,date:Dt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Uf),time:Dt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ff),"date-time":Dt(/^\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,N0),"iso-time":Dt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,O0),"iso-date-time":Dt(/^\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,M0),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};Lt.formatNames=Object.keys(Lt.fullFormats);function SI(t){return t%4===0&&(t%100!==0||t%400===0)}var TI=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,EI=[0,31,28,31,30,31,30,31,31,30,31,30,31];function A0(t){let e=TI.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&&SI(r)?29:EI[n])}function Uf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Df=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Lf(t){return function(r){let n=Df.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 Ff(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 O0(t,e){if(!(t&&e))return;let r=Df.exec(t),n=Df.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 qf=/t|\s/i;function P0(t){let e=Lf(t);return function(n){let o=n.split(qf);return o.length===2&&A0(o[0])&&e(o[1])}}function N0(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function M0(t,e){if(!(t&&e))return;let[r,n]=t.split(qf),[o,s]=e.split(qf),i=Uf(r,o);if(i!==void 0)return i||Ff(n,s)}var zI=/\/|:/,RI=/^(?:[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 PI(t){return zI.test(t)&&RI.test(t)}var I0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function II(t){return I0.lastIndex=0,I0.test(t)}var CI=-(2**31),AI=2**31-1;function OI(t){return Number.isInteger(t)&&t<=AI&&t>=CI}function NI(t){return Number.isInteger(t)}function C0(){return!0}var MI=/[^\\]\\Z/;function jI(t){if(MI.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Z0=E(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.formatLimitDefinition=void 0;var ZI=Zf(),Et=J(),Sr=Et.operators,ga={formatMaximum:{okStr:"<=",ok:Sr.LTE,fail:Sr.GT},formatMinimum:{okStr:">=",ok:Sr.GTE,fail:Sr.LT},formatExclusiveMaximum:{okStr:"<",ok:Sr.LT,fail:Sr.GTE},formatExclusiveMinimum:{okStr:">",ok:Sr.GT,fail:Sr.LTE}},DI={message:({keyword:t,schemaCode:e})=>(0,Et.str)`should be ${ga[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Et._)`{comparison: ${ga[t].okStr}, limit: ${e}}`};ro.formatLimitDefinition={keyword:Object.keys(ga),type:"string",schemaType:"string",$data:!0,error:DI,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 ZI.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,Et._)`${m}[${c.schemaCode}]`);t.fail$data((0,Et.or)((0,Et._)`typeof ${p} != "object"`,(0,Et._)`${p} instanceof RegExp`,(0,Et._)`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,Et._)`${i.code.formats}${(0,Et.getProperty)(m)}`:void 0});t.fail$data(d(f))}function d(m){return(0,Et._)`${m}.compare(${r}, ${n}) ${ga[o].fail} 0`}},dependencies:["format"]};var LI=t=>(t.addKeyword(ro.formatLimitDefinition),t);ro.default=LI});var U0=E((bs,q0)=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var no=j0(),qI=Z0(),Hf=J(),D0=new Hf.Name("fullFormats"),UI=new Hf.Name("fastFormats"),Bf=(t,e={keywords:!0})=>{if(Array.isArray(e))return L0(t,e,no.fullFormats,D0),t;let[r,n]=e.mode==="fast"?[no.fastFormats,UI]:[no.fullFormats,D0],o=e.formats||no.formatNames;return L0(t,o,r,n),e.keywords&&(0,qI.default)(t),t};Bf.get=(t,e="full")=>{let n=(e==="fast"?no.fastFormats:no.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function L0(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Hf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}q0.exports=bs=Bf;Object.defineProperty(bs,"__esModule",{value:!0});bs.default=Bf});var Uv={};yo(Uv,{findEmbeddingModel:()=>qv,ollamaUrl:()=>dp,semanticRerank:()=>bA});import{createHash as lA}from"node:crypto";import{existsSync as dA,mkdirSync as fA,readFileSync as pA,writeFileSync as mA}from"node:fs";import{homedir as hA}from"node:os";import{join as lp}from"node:path";function dp(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 Lv(t,e,r=6e4){let n=await fetch(dp()+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 qv(t){let r=((await Lv("/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=>gA.test(n))}function Oa(){return lp(process.env.XDG_CACHE_HOME??lp(hA(),".cache"),"context-doctor","embeddings.json")}function yA(){try{return dA(Oa())?JSON.parse(pA(Oa(),"utf8")):{}}catch{return{}}}function _A(t){try{let e=Object.keys(t);if(e.length>Dv)for(let r of e.slice(0,e.length-Dv))delete t[r];fA(lp(Oa(),".."),{recursive:!0}),mA(Oa(),JSON.stringify(t))}catch{}}async function vA(t,e){let r=[];for(let n=0;n<e.length;n+=Zv){let o=await Lv("/api/embed",{model:t,input:e.slice(n,n+Zv),truncate:!0});r.push(...o.embeddings)}return r}function xA(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 bA(t,e,r={}){let n;try{n=await qv(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${dp()} (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=yA(),s=f=>lA("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 vA(n,[e,...a]);u=f[0],a.forEach((g,h)=>o[s(g)]=f[h+1]),c=i.map(g=>o[s(g)])}catch(f){return{used:!1,model:n,note:`semantic ranking off: ${n} failed (${f.message}); keyword ranking only`}}a.length&&_A(o);let l=60,d=new Map([...t].filter(f=>f.score>0).sort((f,g)=>g.score-f.score).map((f,g)=>[f,g])),m=t.map((f,g)=>({c:f,s:xA(u,c[g])})).sort((f,g)=>g.s-f.s),p=new Map(m.map((f,g)=>[f.c,g]));for(let f of t){let g=d.get(f);f.score=(g===void 0?0:1/(l+g))+1/(l+p.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var gA,Zv,Dv,Fv=G(()=>{"use strict";gA=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,Zv=64,Dv=5e4});var Mx,jx=G(()=>{Mx="x-hono-already-sent"});var Zx,Dx=G(()=>{Zx=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 mo,constants as eN}from"node:http2";import{Readable as Lx}from"node:stream";async function $N(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Qx(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 Bx(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:Qx(t.getReader(),e)}var Ut,tN,rN,nN,oN,sN,iN,ho,Jx,Wx,aN,cN,Ep,zp,Kx,Op,qx,Ja,Ux,uN,Cr,or,go,Rs,Gx,Xx,Es,Rp,Pp,Ir,Va,ir,Fx,zs,Wa,Ps,lN,dN,fN,pN,mN,hN,gN,Np,yN,Hx,_N,Ht,vN,Pr,Ip,po,sr,Ka,Ft,xN,bN,wN,Cp,Ga,Vx,kN,SN,eb,TN,EN,zN,tb,Xa,Ap,rb,nb,RN,Mp,PN,IN,CN,AN,ON,H9,ob=G(()=>{jx();Dx();Ut=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},tN=/^\/[!#$&-;=?-\[\]_a-z~]*$/,rN=/\/\.\.?(?:[/?#]|$)/,nN=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,oN=(t,e,r)=>{let n=`${t}://${e}${r}`;if(nN.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Ut("Invalid URL");return!tN.test(r)||rN.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 Ut("Invalid host header");return o.href}},sN=t=>t instanceof Ut?t:new Ut(t.message,{cause:t}),iN=global.Request,ho=class extends iN{constructor(t,e){if(typeof t=="object"&&Cr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[ir]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[Cr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Jx=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)},Wx=Symbol("wrapBodyStream"),aN=new Set(["latin1","binary","hex","base64","base64url"]),cN=t=>t===null||aN.has(t),Ep=Symbol("bodyBufferedBeforeDisconnect"),zp=Symbol("bodyBufferedLengthBeforeDisconnect"),Kx=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Op=t=>!(t instanceof mo)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&cN(t.readableEncoding),qx=t=>{if(t.readableDidRead||!Op(t))return;let e=t;e[zp]??=t.readableLength},Ja=(t,e)=>{if(t.readableDidRead&&!e||!Op(t))return;let r=t;if(r[Ep]!==void 0)return r[Ep];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[zp]!==void 0&&t.readableLength!==r[zp])n=Wa();else{let s=e??[],i=t.read();i!==null&&s.push(Kx(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=Wa())}}return r[Ep]=n,n},Ux=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},uN=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new ho(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[Wx]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=Ja(n);if(l!==void 0){Ux(a,l);return}}i||=Lx.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=Ja(n);i!==void 0?s.body=new ReadableStream({start(a){Ux(a,i)}}):s.body=Lx.toWeb(n)}return new ho(e,s)},Cr=Symbol("getRequestCache"),or=Symbol("requestCache"),go=Symbol("incomingKey"),Rs=Symbol("urlKey"),Gx=Symbol("methodKey"),Xx=Symbol("headersKey"),Es=Symbol("abortControllerKey"),Rp=Symbol("getAbortController"),Pp=Symbol("abortRequest"),Ir=Symbol("bodyBuffer"),Va=Symbol("bodyReadPromise"),ir=Symbol("bodyConsumedDirectly"),Fx=Symbol("bodyLockReader"),zs=Symbol("abortReason"),Wa=()=>new TypeError("Body is unusable"),Ps=()=>Promise.reject(Wa()),lN=new TextDecoder,dN=t=>{if(t[ir])return Ps();t[ir]=!0},fN=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),pN=t=>(t[Xx]||=Jx(t[go])).get("content-type")||"",mN=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,hN=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}},gN=t=>{if(!mN.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.`)},Np=(t,e,r)=>{if(t[ir])return Ps();let n=t.method;if(n==="GET"||n==="HEAD")return t[Cr]()[e]();let o=gN(n);if(o)return Promise.reject(o);if(t[or]&&n!=="TRACE")return t[or][e]();let s=dN(t);if(s)return s;let i=yN(t);if(i){let a=Promise.resolve(r(i,t));return t[Ir]=void 0,a}return _N(t).then(a=>{let c=r(a,t);return t[Ir]=void 0,c})},yN=t=>{let e=t[go];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},Hx=(t,e)=>{if(e.errored)return e.errored;let r=t[zs];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},_N=t=>{if(t[Ir])return Promise.resolve(t[Ir]);if(t[Va])return t[Va];let e=t[go];if(e.readableDidRead)return Ps();let r=Ja(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[Ir]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=g=>{a||(a=!0,f(),g())},u=g=>{let h=e.errored??g;return!Op(e)||h&&h.code!=="ECONNRESET"?!1:(c(()=>{let _=Ja(e,i);_ instanceof Error?s(_):_===void 0?s(g??Hx(t,e)):(t[Ir]=_,o(_))}),!0)},l=g=>{i.push(Kx(g,e.readableEncoding))},d=()=>{c(()=>{let g=i.length===1?i[0]:Buffer.concat(i);t[Ir]=g,o(g)})},m=g=>{u(g)||c(()=>{s(g)})},p=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(Hx(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",m),e.off("close",p),t[Va]=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[Va]=n,n},Ht={get method(){return this[Gx]},get url(){return this[Rs]},get headers(){return this[Xx]||=Jx(this[go])},[Pp](t){this[zs]===void 0&&(this[zs]=t);let e=this[Es];e&&!e.signal.aborted&&e.abort(t)},[Rp](){return this[Es]||=new AbortController,this[zs]!==void 0&&!this[Es].signal.aborted&&this[Es].abort(this[zs]),this[Es]},[Cr](){let t=this[Rp]();if(this[or])return this[or];let e=this.method;if(this[ir]&&!(e==="GET"||e==="HEAD")){this[Ir]=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 ho(this[Rs],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[or]=n}return this[or]=uN(this.method,this[Rs],this.headers,this[go],t)},get body(){if(!this[ir])return this[Cr]().body;let t=this[Cr]();return!this[Fx]&&t.body&&(this[Fx]=t.body.getReader()),t.body},get bodyUsed(){return this[ir]?!0:this[or]?this[or].bodyUsed:!1}};Object.defineProperty(Ht,"signal",{get(){return this[Rp]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(Ht,t,{get(){return this[Cr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(Ht,t,{value:function(){if(this[ir]){if(t==="clone")throw Wa();return Ps()}return this[Cr]()[t]()}})});Object.defineProperty(Ht,"text",{value:function(){return Np(this,"text",t=>lN.decode(t))}});Object.defineProperty(Ht,"arrayBuffer",{value:function(){return Np(this,"arrayBuffer",t=>fN(t))}});Object.defineProperty(Ht,"blob",{value:function(){return Np(this,"blob",(t,e)=>{let r=pN(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(Ht,"json",{value:function(){return this[ir]?Ps():this.text().then(JSON.parse)}});Object.defineProperty(Ht,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[or]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Ht,ho.prototype);vN=(t,e)=>{let r=Object.create(Ht);r[go]=t,r[Gx]=hN(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof mo)throw new Ut("Absolute URL for :path is not allowed in HTTP/2");try{r[Rs]=new URL(n).href}catch(i){throw new Ut("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof mo?t.authority:t.headers.host)||e;if(!o)throw new Ut("Missing host header");let s;if(t instanceof mo){if(s=t.scheme,!(s==="http"||s==="https"))throw new Ut("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[Rs]=oN(s,o,n)}catch(i){throw i instanceof Ut?i:new Ut("Invalid URL",{cause:i})}return r},Pr="text/plain; charset=UTF-8",Ip=Symbol("responseCache"),po=Symbol("getResponseCache"),sr=Symbol("cache"),Ka=global.Response,Ft=class Yx{#e;#t;[po](){let e=this[sr],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[sr],this[Ip]||=new Ka(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 Ka){let o=r[Ip];if(o){this.#t=o,this[po]();return}this.#t=r instanceof Yx?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[sr]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[sr];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Pr}))),e[2]):this[po]().headers}get status(){return this[sr]?.[0]??this[po]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Ft.prototype,t,{get(){return this[po]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Ft.prototype,t,{value:function(){return this[po]()[t]()}})});Object.defineProperty(Ft.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[Ip]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Ft,Ka);Object.setPrototypeOf(Ft.prototype,Ka.prototype);xN=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,bN=t=>t instanceof URL?t.href:xN.test(t)?t:new URL(t).href,wN=new Set([301,302,303,307,308]);Object.defineProperty(Ft,"redirect",{value:function(e,r=302){if(!wN.has(r))throw new RangeError("Invalid status code");return new Ft(null,{status:r,headers:{location:bN(e)}})},writable:!0,configurable:!0});Object.defineProperty(Ft,"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 Ft(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});Cp=(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},Ga=Symbol("outgoingEnded"),Vx=Symbol("incomingDraining"),kN=500,SN=64*1024*1024,eb=t=>{let e=t;if(t.destroyed||e[Vx])return;if(e[Vx]=!0,t instanceof mo){try{t.stream?.close?.(eN.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,kN);s.unref?.();let i=a=>{r+=a.length,r>SN&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},TN=(t,e,r,n)=>()=>{e.errored?(qx(e),t[Pp](e.errored.toString())):r.writableFinished||(qx(e),t[Pp]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{eb(e)})})},EN=t=>{if(!(sr in t))return!1;let e=t[sr][1];return e===null||typeof e=="string"||e instanceof Uint8Array},zN=()=>new Response(null,{status:400}),tb=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Xa=(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))},Ap=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},rb=async(t,e)=>{let[r,n,o]=t[sr];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(e.writeHead(r,{"Content-Type":Pr,"Content-Length":Buffer.byteLength(n)}),e.end(n)):n instanceof Uint8Array?(e.writeHead(r,{"Content-Type":Pr,"Content-Length":n.byteLength}),e.end(n)):n instanceof Blob?(e.writeHead(r,{"Content-Type":Pr,"Content-Length":n.size}),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":Pr}),Ap(e),await Bx(n,e)?.catch(i=>Xa(i,e))),e[Ga]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=Cp(o,n===null?void 0:Pr);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Cp(i,n===null?void 0:Pr)}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())):(Ap(e),await Bx(n,e)?.catch(i=>Xa(i,e))),e[Ga]?.()},nb=t=>typeof t.then=="function",RN=async(t,e,r={})=>{if(nb(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(tb);if(sr in t)return rb(t,e);let n=Cp(t.headers,t.body===null?void 0:Pr);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 $N(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&&Ap(e),await Qx(o,e,a))}else n[Mx]||(e.writeHead(t.status,n),e.end());e[Ga]?.()},Mp=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==ho&&(Object.defineProperty(global,"Request",{value:ho}),Object.defineProperty(global,"Response",{value:Ft})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",TN(i,n,o,a)))};try{if(i=vN(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[Wx]=!0,n instanceof mo&&(o[Ga]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!nb(s)&&EN(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||eb(n)}),rb(s,o);u()}catch(l){if(s)return Xa(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:sN(l)),!s)return}else i?s=tb(l):s=zN()}try{return await RN(s,o,e)}catch(l){return Xa(l,o)}}},PN=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??""}},IN=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}},CN=()=>Symbol("connection"),AN=Symbol("CONNECTION_SYMBOL_KEY"),ON=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),H9=Zx(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[ON];if(!o||!n.incoming)return new Response(null,{status:500});let s=CN();return n[AN]=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(g){(r?.onError??console.error)(g)}};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 PN("close",{code:d,reason:m.toString()}),u)}catch(p){(r?.onError??console.error)(p)}}),i.on("error",d=>{try{e?.onError?.(new IN("error",{error:d}),u)}catch(m){(r?.onError??console.error)(m)}})})(),new Response})});var cb=E(jp=>{"use strict";var sb=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,NN=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,ib=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,MN=/\\([\u000b\u0020-\u00ff])/g,jN=/([\\"])/g,ab=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;jp.format=ZN;jp.parse=DN;function ZN(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!ab.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],!ib.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+qN(e[o])}return n}function DN(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?LN(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(!ab.test(n))throw new TypeError("invalid media type");var o=new UN(n.toLowerCase());if(r!==-1){var s,i,a;for(sb.lastIndex=r;i=sb.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(MN,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function LN(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 qN(t){var e=String(t);if(ib.test(e))return e;if(e.length>0&&!NN.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(jN,"\\$1")+'"'}function UN(t){this.parameters=Object.create(null),this.type=t}});function FN(t){if(t)try{return ub.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function lb(t){return t==="application/json"?!0:FN(t)==="application/json"}var ub,db=G(()=>{ub=tc(cb(),1)});function fb(t){return`Payload Too Large: Request body must not exceed ${t} bytes`}function pb(t){if(t===void 0)return 4194304;if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(t)}`);return t}async function mb(t,e=4194304){if(Number(t.headers.get("content-length"))>e)return{tooLarge:!0};if(t.body===null)return{tooLarge:!1,text:""};let r=t.body.getReader(),n=new TextDecoder,o=0,s="";try{for(;;){let{done:i,value:a}=await r.read();if(i)break;if(o+=a.byteLength,o>e)return{tooLarge:!0};s+=n.decode(a,{stream:!0})}}finally{r.releaseLock()}return{tooLarge:!1,text:s+n.decode()}}var hb=G(()=>{});function gb(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var yb=G(()=>{});var Ya,_b=G(()=>{db();hb();yb();gr();Ya=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,this._maxRequestBodySize=pb(e.maxRequestBodySize)}startKeepAlive(e,r){if(this._closed)return;let n=gb(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
|
|
37
|
+
deps: ${r}}`};var w1={keyword:"dependencies",type:"object",schemaType:"object",error:Dt.error,code(t){let[e,r]=$1(t);r0(t,e),n0(t,r)}};function $1({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 r0(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,ws.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,ws.checkReportMissingProp)(t,u)}):(r.if((0,bf._)`${c} && (${(0,ws.checkMissingProp)(t,a,s)})`),(0,ws.reportMissingProp)(t,s),r.else())}}Dt.validatePropertyDeps=r0;function n0(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,b1.alwaysValidSchema)(s,e[a])||(r.if((0,ws.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))}Dt.validateSchemaDeps=n0;Dt.default=w1});var i0=E(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var s0=J(),k1=re(),S1={message:"property name must be valid",params:({params:t})=>(0,s0._)`{propertyName: ${t.propertyName}}`},T1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:S1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,k1.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,s0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};wf.default=T1});var kf=E($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var da=pt(),Et=J(),E1=tr(),fa=re(),z1={message:"must NOT have additional properties",params:({params:t})=>(0,Et._)`{additionalProperty: ${t.additionalProperty}}`},R1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:z1,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,fa.alwaysValidSchema)(i,r))return;let u=(0,da.allSchemaProperties)(n.properties),l=(0,da.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Et._)`${s} === ${E1.default.errors}`);function d(){e.forIn("key",o,h=>{!u.length&&!l.length?f(h):e.if(m(h),()=>f(h))})}function m(h){let _;if(u.length>8){let v=(0,fa.schemaRefOrVal)(i,n.properties,"properties");_=(0,da.isOwnProperty)(e,v,h)}else u.length?_=(0,Et.or)(...u.map(v=>(0,Et._)`${h} === ${v}`)):_=Et.nil;return l.length&&(_=(0,Et.or)(_,...l.map(v=>(0,Et._)`${(0,da.usePattern)(t,v)}.test(${h})`))),(0,Et.not)(_)}function p(h){e.code((0,Et._)`delete ${o}[${h}]`)}function f(h){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(h);return}if(r===!1){t.setParams({additionalProperty:h}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,fa.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(h,_,!1),e.if((0,Et.not)(_),()=>{t.reset(),p(h)})):(g(h,_),a||e.if((0,Et.not)(_),()=>e.break()))}}function g(h,_,v){let y={keyword:"additionalProperties",dataProp:h,dataPropType:fa.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};$f.default=R1});var u0=E(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var P1=as(),a0=pt(),Sf=re(),c0=kf(),I1={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&&c0.default.code(new P1.KeywordCxt(s,c0.default,"additionalProperties"));let i=(0,a0.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Sf.mergeEvaluated.props(e,(0,Sf.toHash)(i),s.props));let a=i.filter(d=>!(0,Sf.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,a0.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)}}};Tf.default=I1});var p0=E(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var l0=pt(),pa=J(),d0=re(),f0=re(),C1={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,l0.allSchemaProperties)(r),c=a.filter(g=>(0,d0.alwaysValidSchema)(s,r[g]));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 pa.Name)&&(s.props=(0,f0.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let g of a)u&&p(g),s.allErrors?f(g):(e.var(l,!0),f(g),e.if(l))}function p(g){for(let h in u)new RegExp(g).test(h)&&(0,d0.checkStrictMode)(s,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){e.forIn("key",n,h=>{e.if((0,pa._)`${(0,l0.usePattern)(t,g)}.test(${h})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:f0.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,pa._)`${d}[${h}]`,!0):!_&&!s.allErrors&&e.if((0,pa.not)(l),()=>e.break())})})}}};Ef.default=C1});var m0=E(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var A1=re(),O1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,A1.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"}};zf.default=O1});var h0=E(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var N1=pt(),M1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:N1.validateUnion,error:{message:"must match a schema in anyOf"}};Rf.default=M1});var g0=E(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var ma=J(),j1=re(),Z1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ma._)`{passingSchemas: ${t.passing}}`},D1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Z1,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,j1.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,ma._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ma._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,ma.Name)})})}}};Pf.default=D1});var y0=E(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var L1=re(),q1={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,L1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};If.default=q1});var x0=E(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var ha=J(),v0=re(),U1={message:({params:t})=>(0,ha.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ha._)`{failingKeyword: ${t.ifClause}}`},F1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:U1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,v0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=_0(n,"then"),s=_0(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,ha.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,ha._)`${l}`):t.setParams({ifClause:l})}}}};function _0(t,e){let r=t.schema[e];return r!==void 0&&!(0,v0.alwaysValidSchema)(t,r)}Cf.default=F1});var b0=E(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var H1=re(),B1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,H1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Af.default=B1});var w0=E(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var V1=gf(),J1=Y_(),W1=yf(),K1=e0(),G1=t0(),X1=o0(),Y1=i0(),Q1=kf(),eI=u0(),tI=p0(),rI=m0(),nI=h0(),oI=g0(),sI=y0(),iI=x0(),aI=b0();function cI(t=!1){let e=[rI.default,nI.default,oI.default,sI.default,iI.default,aI.default,Y1.default,Q1.default,X1.default,eI.default,tI.default];return t?e.push(J1.default,K1.default):e.push(V1.default,W1.default),e.push(G1.default),e}Of.default=cI});var $0=E(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var ke=J(),uI={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},lI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:uI,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}),g=r.const("fDef",(0,ke._)`${f}[${i}]`),h=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,ke._)`${g}.type || "string"`).assign(_,(0,ke._)`${g}.validate`),()=>r.assign(h,(0,ke._)`"string"`).assign(_,g)),t.fail$data((0,ke.or)(v(),y()));function v(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function y(){let x=l.$async?(0,ke._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,$=(0,ke._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${h} === ${e} && !${$}`}}function p(){let f=d.formats[s];if(!f){v();return}if(f===!0)return;let[g,h,_]=y(f);g===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 y($){let O=$ instanceof RegExp?(0,ke.regexpCode)($):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,C=r.scopeValue("formats",{key:s,ref:$,code:O});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,ke._)`${C}.validate`]:["string",$,C]}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 h=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};Nf.default=lI});var k0=E(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var dI=$0(),fI=[dI.default];Mf.default=fI});var S0=E(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.contentVocabulary=Qn.metadataVocabulary=void 0;Qn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Qn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var E0=E(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var pI=O_(),mI=W_(),hI=w0(),gI=k0(),T0=S0(),yI=[pI.default,mI.default,(0,hI.default)(),gI.default,T0.metadataVocabulary,T0.contentVocabulary];jf.default=yI});var R0=E(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.DiscrError=void 0;var z0;(function(t){t.Tag="tag",t.Mapping="mapping"})(z0||(ga.DiscrError=z0={}))});var I0=E(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var eo=J(),Zf=R0(),P0=Xi(),_I=cs(),vI=re(),xI={message:({params:{discrError:t,tagName:e}})=>t===Zf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,eo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},bI={keyword:"discriminator",type:"object",schemaType:"object",error:xI,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,eo._)`${r}${(0,eo.getProperty)(a)}`);e.if((0,eo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Zf.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,eo._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:Zf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(g,eo.Name),f}function m(){var p;let f={},g=_(o),h=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,vI.schemaHasRulesButRef)($,s.self.RULES)){let C=$.$ref;if($=P0.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,C),$ instanceof P0.SchemaEnv&&($=$.schema),$===void 0)throw new _I.default(s.opts.uriResolver,s.baseId,C)}let O=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);h=h&&(g||_($)),v(O,x)}if(!h)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)y(x.const,$);else if(x.enum)for(let O of x.enum)y(O,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function y(x,$){if(typeof x!="string"||x in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[x]=$}}}};Df.default=bI});var C0=E((xL,wI)=>{wI.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 qf=E((ye,Lf)=>{"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 $I=z_(),kI=E0(),SI=I0(),A0=C0(),TI=["/properties"],ya="http://json-schema.org/draft-07/schema",to=class extends $I.default{_addVocabularies(){super._addVocabularies(),kI.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(SI.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(A0,TI):A0;this.addMetaSchema(e,ya,!1),this.refs["http://json-schema.org/schema"]=ya}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ya)?ya:void 0)}};ye.Ajv=to;Lf.exports=ye=to;Lf.exports.Ajv=to;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=to;var EI=as();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return EI.KeywordCxt}});var ro=J();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return ro._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return ro.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return ro.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return ro.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return ro.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return ro.CodeGen}});var zI=Ki();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return zI.default}});var RI=cs();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return RI.default}})});var q0=E(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.formatNames=qt.fastFormats=qt.fullFormats=void 0;function Lt(t,e){return{validate:t,compare:e}}qt.fullFormats={date:Lt(j0,Bf),time:Lt(Ff(!0),Vf),"date-time":Lt(O0(!0),D0),"iso-time":Lt(Ff(),Z0),"iso-date-time":Lt(O0(),L0),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:NI,"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:UI,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:MI,int32:{type:"number",validate:DI},int64:{type:"number",validate:LI},float:{type:"number",validate:M0},double:{type:"number",validate:M0},password:!0,binary:!0};qt.fastFormats={...qt.fullFormats,date:Lt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Bf),time:Lt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Vf),"date-time":Lt(/^\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,D0),"iso-time":Lt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Z0),"iso-date-time":Lt(/^\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,L0),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};qt.formatNames=Object.keys(qt.fullFormats);function PI(t){return t%4===0&&(t%100!==0||t%400===0)}var II=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,CI=[0,31,28,31,30,31,30,31,31,30,31,30,31];function j0(t){let e=II.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&&PI(r)?29:CI[n])}function Bf(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 Ff(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,m=o-u*c-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&i<61}}function Vf(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 Z0(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 Hf=/t|\s/i;function O0(t){let e=Ff(t);return function(n){let o=n.split(Hf);return o.length===2&&j0(o[0])&&e(o[1])}}function D0(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function L0(t,e){if(!(t&&e))return;let[r,n]=t.split(Hf),[o,s]=e.split(Hf),i=Bf(r,o);if(i!==void 0)return i||Vf(n,s)}var AI=/\/|:/,OI=/^(?:[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 NI(t){return AI.test(t)&&OI.test(t)}var N0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function MI(t){return N0.lastIndex=0,N0.test(t)}var jI=-(2**31),ZI=2**31-1;function DI(t){return Number.isInteger(t)&&t<=ZI&&t>=jI}function LI(t){return Number.isInteger(t)}function M0(){return!0}var qI=/[^\\]\\Z/;function UI(t){if(qI.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var U0=E(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.formatLimitDefinition=void 0;var FI=qf(),zt=J(),Tr=zt.operators,_a={formatMaximum:{okStr:"<=",ok:Tr.LTE,fail:Tr.GT},formatMinimum:{okStr:">=",ok:Tr.GTE,fail:Tr.LT},formatExclusiveMaximum:{okStr:"<",ok:Tr.LT,fail:Tr.GTE},formatExclusiveMinimum:{okStr:">",ok:Tr.GT,fail:Tr.LTE}},HI={message:({keyword:t,schemaCode:e})=>(0,zt.str)`should be ${_a[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,zt._)`{comparison: ${_a[t].okStr}, limit: ${e}}`};no.formatLimitDefinition={keyword:Object.keys(_a),type:"string",schemaType:"string",$data:!0,error:HI,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 FI.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,zt._)`${m}[${c.schemaCode}]`);t.fail$data((0,zt.or)((0,zt._)`typeof ${p} != "object"`,(0,zt._)`${p} instanceof RegExp`,(0,zt._)`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,zt._)`${i.code.formats}${(0,zt.getProperty)(m)}`:void 0});t.fail$data(d(f))}function d(m){return(0,zt._)`${m}.compare(${r}, ${n}) ${_a[o].fail} 0`}},dependencies:["format"]};var BI=t=>(t.addKeyword(no.formatLimitDefinition),t);no.default=BI});var V0=E(($s,B0)=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var oo=q0(),VI=U0(),Jf=J(),F0=new Jf.Name("fullFormats"),JI=new Jf.Name("fastFormats"),Wf=(t,e={keywords:!0})=>{if(Array.isArray(e))return H0(t,e,oo.fullFormats,F0),t;let[r,n]=e.mode==="fast"?[oo.fastFormats,JI]:[oo.fullFormats,F0],o=e.formats||oo.formatNames;return H0(t,o,r,n),e.keywords&&(0,VI.default)(t),t};Wf.get=(t,e="full")=>{let n=(e==="fast"?oo.fastFormats:oo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function H0(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Jf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}B0.exports=$s=Wf;Object.defineProperty($s,"__esModule",{value:!0});$s.default=Wf});var Vv={};vo(Vv,{findEmbeddingModel:()=>Bv,ollamaUrl:()=>hp,semanticRerank:()=>zA});import{createHash as yA}from"node:crypto";import{existsSync as _A,mkdirSync as vA,readFileSync as xA,writeFileSync as bA}from"node:fs";import{homedir as wA}from"node:os";import{join as mp}from"node:path";function hp(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 Hv(t,e,r=6e4){let n=await fetch(hp()+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 Bv(t){let r=((await Hv("/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=>$A.test(n))}function Ma(){return mp(process.env.XDG_CACHE_HOME??mp(wA(),".cache"),"context-doctor","embeddings.json")}function kA(){try{return _A(Ma())?JSON.parse(xA(Ma(),"utf8")):{}}catch{return{}}}function SA(t){try{let e=Object.keys(t);if(e.length>Fv)for(let r of e.slice(0,e.length-Fv))delete t[r];vA(mp(Ma(),".."),{recursive:!0}),bA(Ma(),JSON.stringify(t))}catch{}}async function TA(t,e){let r=[];for(let n=0;n<e.length;n+=Uv){let o=await Hv("/api/embed",{model:t,input:e.slice(n,n+Uv),truncate:!0});r.push(...o.embeddings)}return r}function EA(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 zA(t,e,r={}){let n;try{n=await Bv(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${hp()} (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=kA(),s=f=>yA("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 TA(n,[e,...a]);u=f[0],a.forEach((g,h)=>o[s(g)]=f[h+1]),c=i.map(g=>o[s(g)])}catch(f){return{used:!1,model:n,note:`semantic ranking off: ${n} failed (${f.message}); keyword ranking only`}}a.length&&SA(o);let l=60,d=new Map([...t].filter(f=>f.score>0).sort((f,g)=>g.score-f.score).map((f,g)=>[f,g])),m=t.map((f,g)=>({c:f,s:EA(u,c[g])})).sort((f,g)=>g.s-f.s),p=new Map(m.map((f,g)=>[f.c,g]));for(let f of t){let g=d.get(f);f.score=(g===void 0?0:1/(l+g))+1/(l+p.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var $A,Uv,Fv,Jv=G(()=>{"use strict";$A=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,Uv=64,Fv=5e4});var qx,Ux=G(()=>{qx="x-hono-already-sent"});var Fx,Hx=G(()=>{Fx=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 go,constants as uN}from"node:http2";import{Readable as Bx}from"node:stream";async function CN(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function ob(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 Gx(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:ob(t.getReader(),e)}var Ft,lN,dN,fN,pN,mN,hN,yo,Yx,Qx,gN,yN,Ip,Cp,eb,Zp,Vx,Ga,Jx,_N,Ar,sr,_o,Is,tb,rb,Rs,Ap,Op,Cr,Ka,ar,Wx,Ps,Xa,Cs,vN,xN,bN,wN,$N,kN,SN,Dp,TN,Kx,EN,Bt,zN,Ir,Np,ho,ir,Ya,Ht,RN,PN,IN,Mp,Qa,Xx,AN,ON,sb,NN,MN,jN,ib,ec,jp,ab,cb,ZN,Lp,DN,LN,qN,UN,FN,sU,ub=G(()=>{Ux();Hx();Ft=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},lN=/^\/[!#$&-;=?-\[\]_a-z~]*$/,dN=/\/\.\.?(?:[/?#]|$)/,fN=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,pN=(t,e,r)=>{let n=`${t}://${e}${r}`;if(fN.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Ft("Invalid URL");return!lN.test(r)||dN.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 Ft("Invalid host header");return o.href}},mN=t=>t instanceof Ft?t:new Ft(t.message,{cause:t}),hN=global.Request,yo=class extends hN{constructor(t,e){if(typeof t=="object"&&Ar in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[ar]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[Ar]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Yx=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)},Qx=Symbol("wrapBodyStream"),gN=new Set(["latin1","binary","hex","base64","base64url"]),yN=t=>t===null||gN.has(t),Ip=Symbol("bodyBufferedBeforeDisconnect"),Cp=Symbol("bodyBufferedLengthBeforeDisconnect"),eb=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Zp=t=>!(t instanceof go)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&yN(t.readableEncoding),Vx=t=>{if(t.readableDidRead||!Zp(t))return;let e=t;e[Cp]??=t.readableLength},Ga=(t,e)=>{if(t.readableDidRead&&!e||!Zp(t))return;let r=t;if(r[Ip]!==void 0)return r[Ip];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Cp]!==void 0&&t.readableLength!==r[Cp])n=Xa();else{let s=e??[],i=t.read();i!==null&&s.push(eb(i,t.readableEncoding));let a=s.length===1?s[0]:Buffer.concat(s);n=a;let c=t.headers["content-length"];if(typeof c=="string"&&/^\d+$/.test(c)){let u=Number(c);Number.isSafeInteger(u)&&a.length!==u&&(n=Xa())}}return r[Ip]=n,n},Jx=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},_N=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new yo(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[Qx]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=Ga(n);if(l!==void 0){Jx(a,l);return}}i||=Bx.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=Ga(n);i!==void 0?s.body=new ReadableStream({start(a){Jx(a,i)}}):s.body=Bx.toWeb(n)}return new yo(e,s)},Ar=Symbol("getRequestCache"),sr=Symbol("requestCache"),_o=Symbol("incomingKey"),Is=Symbol("urlKey"),tb=Symbol("methodKey"),rb=Symbol("headersKey"),Rs=Symbol("abortControllerKey"),Ap=Symbol("getAbortController"),Op=Symbol("abortRequest"),Cr=Symbol("bodyBuffer"),Ka=Symbol("bodyReadPromise"),ar=Symbol("bodyConsumedDirectly"),Wx=Symbol("bodyLockReader"),Ps=Symbol("abortReason"),Xa=()=>new TypeError("Body is unusable"),Cs=()=>Promise.reject(Xa()),vN=new TextDecoder,xN=t=>{if(t[ar])return Cs();t[ar]=!0},bN=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),wN=t=>(t[rb]||=Yx(t[_o])).get("content-type")||"",$N=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,kN=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}},SN=t=>{if(!$N.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.`)},Dp=(t,e,r)=>{if(t[ar])return Cs();let n=t.method;if(n==="GET"||n==="HEAD")return t[Ar]()[e]();let o=SN(n);if(o)return Promise.reject(o);if(t[sr]&&n!=="TRACE")return t[sr][e]();let s=xN(t);if(s)return s;let i=TN(t);if(i){let a=Promise.resolve(r(i,t));return t[Cr]=void 0,a}return EN(t).then(a=>{let c=r(a,t);return t[Cr]=void 0,c})},TN=t=>{let e=t[_o];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},Kx=(t,e)=>{if(e.errored)return e.errored;let r=t[Ps];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},EN=t=>{if(t[Cr])return Promise.resolve(t[Cr]);if(t[Ka])return t[Ka];let e=t[_o];if(e.readableDidRead)return Cs();let r=Ga(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[Cr]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=g=>{a||(a=!0,f(),g())},u=g=>{let h=e.errored??g;return!Zp(e)||h&&h.code!=="ECONNRESET"?!1:(c(()=>{let _=Ga(e,i);_ instanceof Error?s(_):_===void 0?s(g??Kx(t,e)):(t[Cr]=_,o(_))}),!0)},l=g=>{i.push(eb(g,e.readableEncoding))},d=()=>{c(()=>{let g=i.length===1?i[0]:Buffer.concat(i);t[Cr]=g,o(g)})},m=g=>{u(g)||c(()=>{s(g)})},p=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(Kx(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",m),e.off("close",p),t[Ka]=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[Ka]=n,n},Bt={get method(){return this[tb]},get url(){return this[Is]},get headers(){return this[rb]||=Yx(this[_o])},[Op](t){this[Ps]===void 0&&(this[Ps]=t);let e=this[Rs];e&&!e.signal.aborted&&e.abort(t)},[Ap](){return this[Rs]||=new AbortController,this[Ps]!==void 0&&!this[Rs].signal.aborted&&this[Rs].abort(this[Ps]),this[Rs]},[Ar](){let t=this[Ap]();if(this[sr])return this[sr];let e=this.method;if(this[ar]&&!(e==="GET"||e==="HEAD")){this[Cr]=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 yo(this[Is],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[sr]=n}return this[sr]=_N(this.method,this[Is],this.headers,this[_o],t)},get body(){if(!this[ar])return this[Ar]().body;let t=this[Ar]();return!this[Wx]&&t.body&&(this[Wx]=t.body.getReader()),t.body},get bodyUsed(){return this[ar]?!0:this[sr]?this[sr].bodyUsed:!1}};Object.defineProperty(Bt,"signal",{get(){return this[Ap]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(Bt,t,{get(){return this[Ar]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(Bt,t,{value:function(){if(this[ar]){if(t==="clone")throw Xa();return Cs()}return this[Ar]()[t]()}})});Object.defineProperty(Bt,"text",{value:function(){return Dp(this,"text",t=>vN.decode(t))}});Object.defineProperty(Bt,"arrayBuffer",{value:function(){return Dp(this,"arrayBuffer",t=>bN(t))}});Object.defineProperty(Bt,"blob",{value:function(){return Dp(this,"blob",(t,e)=>{let r=wN(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(Bt,"json",{value:function(){return this[ar]?Cs():this.text().then(JSON.parse)}});Object.defineProperty(Bt,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[sr]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Bt,yo.prototype);zN=(t,e)=>{let r=Object.create(Bt);r[_o]=t,r[tb]=kN(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof go)throw new Ft("Absolute URL for :path is not allowed in HTTP/2");try{r[Is]=new URL(n).href}catch(i){throw new Ft("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof go?t.authority:t.headers.host)||e;if(!o)throw new Ft("Missing host header");let s;if(t instanceof go){if(s=t.scheme,!(s==="http"||s==="https"))throw new Ft("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[Is]=pN(s,o,n)}catch(i){throw i instanceof Ft?i:new Ft("Invalid URL",{cause:i})}return r},Ir="text/plain; charset=UTF-8",Np=Symbol("responseCache"),ho=Symbol("getResponseCache"),ir=Symbol("cache"),Ya=global.Response,Ht=class nb{#e;#t;[ho](){let e=this[ir],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[ir],this[Np]||=new Ya(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 Ya){let o=r[Np];if(o){this.#t=o,this[ho]();return}this.#t=r instanceof nb?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[ir]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[ir];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Ir}))),e[2]):this[ho]().headers}get status(){return this[ir]?.[0]??this[ho]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Ht.prototype,t,{get(){return this[ho]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Ht.prototype,t,{value:function(){return this[ho]()[t]()}})});Object.defineProperty(Ht.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[Np]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Ht,Ya);Object.setPrototypeOf(Ht.prototype,Ya.prototype);RN=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,PN=t=>t instanceof URL?t.href:RN.test(t)?t:new URL(t).href,IN=new Set([301,302,303,307,308]);Object.defineProperty(Ht,"redirect",{value:function(e,r=302){if(!IN.has(r))throw new RangeError("Invalid status code");return new Ht(null,{status:r,headers:{location:PN(e)}})},writable:!0,configurable:!0});Object.defineProperty(Ht,"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 Ht(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});Mp=(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},Qa=Symbol("outgoingEnded"),Xx=Symbol("incomingDraining"),AN=500,ON=64*1024*1024,sb=t=>{let e=t;if(t.destroyed||e[Xx])return;if(e[Xx]=!0,t instanceof go){try{t.stream?.close?.(uN.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,AN);s.unref?.();let i=a=>{r+=a.length,r>ON&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},NN=(t,e,r,n)=>()=>{e.errored?(Vx(e),t[Op](e.errored.toString())):r.writableFinished||(Vx(e),t[Op]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{sb(e)})})},MN=t=>{if(!(ir in t))return!1;let e=t[ir][1];return e===null||typeof e=="string"||e instanceof Uint8Array},jN=()=>new Response(null,{status:400}),ib=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),ec=(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))},jp=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},ab=async(t,e)=>{let[r,n,o]=t[ir];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(e.writeHead(r,{"Content-Type":Ir,"Content-Length":Buffer.byteLength(n)}),e.end(n)):n instanceof Uint8Array?(e.writeHead(r,{"Content-Type":Ir,"Content-Length":n.byteLength}),e.end(n)):n instanceof Blob?(e.writeHead(r,{"Content-Type":Ir,"Content-Length":n.size}),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":Ir}),jp(e),await Gx(n,e)?.catch(i=>ec(i,e))),e[Qa]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=Mp(o,n===null?void 0:Ir);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Mp(i,n===null?void 0:Ir)}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())):(jp(e),await Gx(n,e)?.catch(i=>ec(i,e))),e[Qa]?.()},cb=t=>typeof t.then=="function",ZN=async(t,e,r={})=>{if(cb(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(ib);if(ir in t)return ab(t,e);let n=Mp(t.headers,t.body===null?void 0:Ir);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 CN(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&&jp(e),await ob(o,e,a))}else n[qx]||(e.writeHead(t.status,n),e.end());e[Qa]?.()},Lp=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==yo&&(Object.defineProperty(global,"Request",{value:yo}),Object.defineProperty(global,"Response",{value:Ht})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",NN(i,n,o,a)))};try{if(i=zN(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[Qx]=!0,n instanceof go&&(o[Qa]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!cb(s)&&MN(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||sb(n)}),ab(s,o);u()}catch(l){if(s)return ec(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:mN(l)),!s)return}else i?s=ib(l):s=jN()}try{return await ZN(s,o,e)}catch(l){return ec(l,o)}}},DN=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??""}},LN=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}},qN=()=>Symbol("connection"),UN=Symbol("CONNECTION_SYMBOL_KEY"),FN=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),sU=Fx(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[FN];if(!o||!n.incoming)return new Response(null,{status:500});let s=qN();return n[UN]=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(g){(r?.onError??console.error)(g)}};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 DN("close",{code:d,reason:m.toString()}),u)}catch(p){(r?.onError??console.error)(p)}}),i.on("error",d=>{try{e?.onError?.(new LN("error",{error:d}),u)}catch(m){(r?.onError??console.error)(m)}})})(),new Response})});var pb=E(qp=>{"use strict";var lb=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,HN=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,db=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,BN=/\\([\u000b\u0020-\u00ff])/g,VN=/([\\"])/g,fb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;qp.format=JN;qp.parse=WN;function JN(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!fb.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],!db.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+GN(e[o])}return n}function WN(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?KN(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(!fb.test(n))throw new TypeError("invalid media type");var o=new XN(n.toLowerCase());if(r!==-1){var s,i,a;for(lb.lastIndex=r;i=lb.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(BN,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function KN(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 GN(t){var e=String(t);if(db.test(e))return e;if(e.length>0&&!HN.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(VN,"\\$1")+'"'}function XN(t){this.parameters=Object.create(null),this.type=t}});function YN(t){if(t)try{return mb.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function hb(t){return t==="application/json"?!0:YN(t)==="application/json"}var mb,gb=G(()=>{mb=oc(pb(),1)});function yb(t){return`Payload Too Large: Request body must not exceed ${t} bytes`}function _b(t){if(t===void 0)return 4194304;if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(t)}`);return t}async function vb(t,e=4194304){if(Number(t.headers.get("content-length"))>e)return{tooLarge:!0};if(t.body===null)return{tooLarge:!1,text:""};let r=t.body.getReader(),n=new TextDecoder,o=0,s="";try{for(;;){let{done:i,value:a}=await r.read();if(i)break;if(o+=a.byteLength,o>e)return{tooLarge:!0};s+=n.decode(a,{stream:!0})}}finally{r.releaseLock()}return{tooLarge:!1,text:s+n.decode()}}var xb=G(()=>{});function bb(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var wb=G(()=>{});var tc,$b=G(()=>{gb();xb();wb();yr();tc=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,this._maxRequestBodySize=_b(e.maxRequestBodySize)}startKeepAlive(e,r){if(this._closed)return;let n=bb(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
|
|
39
39
|
|
|
40
40
|
`))}catch{n!==void 0&&clearInterval(n)}});return n}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(e,r,n,o){let s={code:r,message:n};return o?.data!==void 0&&(s.data=o.data),new Response(JSON.stringify({jsonrpc:"2.0",error:s,id:null}),{status:e,headers:{"Content-Type":"application/json",...o?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=e.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=e.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(e,r){if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case"POST":return this.handlePostRequest(e,r);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,r,n,o){if(!this._eventStore||o<"2025-11-25")return;let s=await this._eventStore.storeEvent(n,{}),i=`id: ${s}
|
|
41
41
|
data:
|
|
@@ -48,75 +48,75 @@ data:
|
|
|
48
48
|
`;return o&&(s+=`id: ${o}
|
|
49
49
|
`),s+=`data: ${JSON.stringify(n)}
|
|
50
50
|
|
|
51
|
-
`,e.enqueue(r.encode(s)),!0}catch(s){return this.onerror?.(s),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,r){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!lb(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{let v=await mb(e,this._maxRequestBodySize);if(v.tooLarge){let y=fb(this._maxRequestBodySize);return this.onerror?.(new Error(y)),this.createJsonErrorResponse(413,-32e3,y)}i=JSON.parse(v.text)}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}if(Array.isArray(i)&&i.length>100)return this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${100} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${100} messages`);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(El);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 y=this.validateProtocolVersion(e);if(y)return y}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!a.some(Gt)){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=>El(v)),m=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??Kh;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let y of a)Gt(y)&&this._requestToStreamMapping.set(y.id,l);for(let y of a)this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:s})});let p=new TextEncoder,f,g,h=new ReadableStream({start:v=>{f=v},cancel:()=>{g!==void 0&&clearInterval(g),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)Gt(v)&&(this._streamMapping.set(l,{controller:f,encoder:p,cleanup:()=>{g!==void 0&&clearInterval(g),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 y,x;Gt(v)&&this._eventStore&&m>="2025-11-25"&&(y=()=>{this.closeSSEStream(v.id)},x=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:y,closeStandaloneSSEStream:x})}}catch(v){this._streamMapping.get(l)?.cleanup(),this._resumableStreams.delete(l);for(let y of a)Gt(y)&&this._requestToStreamMapping.delete(y.id);throw v}return this._streamMapping.get(l)?.controller===f&&(g=this.startKeepAlive(f,p)),new Response(h,{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&&!Nn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Nn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Nn.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((Xt(e)||Mn(e))&&(n=e.id),n===void 0){if(Xt(e)||Mn(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(Xt(e)||Mn(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 vb={};yo(vb,{StreamableHTTPServerTransport:()=>Dp});var Dp,xb=G(()=>{ob();_b();Dp=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Ya(e),this._requestListener=Mp(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 Mp(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 Z={};yo(Z,{BRAND:()=>rw,DIRTY:()=>Nr,EMPTY_PATH:()=>Ob,INVALID:()=>D,NEVER:()=>Dw,OK:()=>Me,ParseStatus:()=>Re,Schema:()=>V,ZodAny:()=>ur,ZodArray:()=>Wt,ZodBigInt:()=>jr,ZodBoolean:()=>Zr,ZodBranded:()=>vo,ZodCatch:()=>Kr,ZodDate:()=>Dr,ZodDefault:()=>Wr,ZodDiscriminatedUnion:()=>Os,ZodEffects:()=>ct,ZodEnum:()=>Vr,ZodError:()=>We,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Ms,ZodIntersection:()=>Fr,ZodIssueCode:()=>k,ZodLazy:()=>Hr,ZodLiteral:()=>Br,ZodMap:()=>Sn,ZodNaN:()=>En,ZodNativeEnum:()=>Jr,ZodNever:()=>vt,ZodNull:()=>qr,ZodNullable:()=>Ct,ZodNumber:()=>Mr,ZodObject:()=>Ge,ZodOptional:()=>Ke,ZodParsedType:()=>R,ZodPipeline:()=>xo,ZodPromise:()=>lr,ZodReadonly:()=>Gr,ZodRecord:()=>Ns,ZodSchema:()=>V,ZodSet:()=>Tn,ZodString:()=>cr,ZodSymbol:()=>$n,ZodTransformer:()=>ct,ZodTuple:()=>It,ZodType:()=>V,ZodUndefined:()=>Lr,ZodUnion:()=>Ur,ZodUnknown:()=>Jt,ZodVoid:()=>kn,addIssueToContext:()=>T,any:()=>dw,array:()=>hw,bigint:()=>iw,boolean:()=>Yp,coerce:()=>Zw,custom:()=>Kp,date:()=>aw,datetimeRegex:()=>Jp,defaultErrorMap:()=>Bt,discriminatedUnion:()=>_w,effect:()=>Pw,enum:()=>Ew,function:()=>kw,getErrorMap:()=>xn,getParsedType:()=>Pt,instanceof:()=>ow,intersection:()=>vw,isAborted:()=>Cs,isAsync:()=>bn,isDirty:()=>As,isValid:()=>ar,late:()=>nw,lazy:()=>Sw,literal:()=>Tw,makeIssue:()=>_o,map:()=>ww,nan:()=>sw,nativeEnum:()=>zw,never:()=>pw,null:()=>lw,nullable:()=>Cw,number:()=>Xp,object:()=>sc,objectUtil:()=>rc,oboolean:()=>jw,onumber:()=>Mw,optional:()=>Iw,ostring:()=>Nw,pipeline:()=>Ow,preprocess:()=>Aw,promise:()=>Rw,quotelessJson:()=>Ib,record:()=>bw,set:()=>$w,setErrorMap:()=>Ab,strictObject:()=>gw,string:()=>Gp,symbol:()=>cw,transformer:()=>Pw,tuple:()=>xw,undefined:()=>uw,union:()=>yw,unknown:()=>fw,util:()=>X,void:()=>mw});var X;(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})(X||(X={}));var rc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(rc||(rc={}));var R=X.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pt=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var k=X.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"]),Ib=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),We=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,X.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()}};We.create=t=>new We(t);var Cb=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,X.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${X.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${X.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${X.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}"`:X.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,X.assertNever(t)}return{message:r}},Bt=Cb;var Up=Bt;function Ab(t){Up=t}function xn(){return Up}var _o=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}},Ob=[];function T(t,e){let r=xn(),n=_o({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Bt?void 0:Bt].filter(o=>!!o)});t.common.issues.push(n)}var Re=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 D;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 D;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}}},D=Object.freeze({status:"aborted"}),Nr=t=>({status:"dirty",value:t}),Me=t=>({status:"valid",value:t}),Cs=t=>t.status==="aborted",As=t=>t.status==="dirty",ar=t=>t.status==="valid",bn=t=>typeof Promise<"u"&&t instanceof Promise;var N;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));var at=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}},Fp=(t,e)=>{if(ar(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 We(t.common.issues);return this._error=r,this._error}}};function H(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 Pt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Re,ctx:{common:e.parent.common,data:e.data,parsedType:Pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(bn(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:Pt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Fp(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ar(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=>ar(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:Pt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(bn(o)?o:Promise.resolve(o));return Fp(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 ct({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 Ke.create(this,this._def)}nullable(){return Ct.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wt.create(this)}promise(){return lr.create(this,this._def)}or(e){return Ur.create([this,e],this._def)}and(e){return Fr.create(this,e,this._def)}transform(e){return new ct({...H(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Wr({...H(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new vo({typeName:S.ZodBranded,type:this,...H(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Kr({...H(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 xo.create(this,e)}readonly(){return Gr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Nb=/^c[^\s-]{8,}$/i,Mb=/^[0-9a-z]+$/,jb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zb=/^[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,Db=/^[a-z0-9_-]{21}$/i,Lb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,qb=/^[-+]?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)?)??$/,Ub=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",nc,Hb=/^(?:(?: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])$/,Bb=/^(?:(?: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])$/,Vb=/^(([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]))$/,Jb=/^(([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])$/,Wb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Kb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Bp="((\\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])))",Gb=new RegExp(`^${Bp}$`);function Vp(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 Xb(t){return new RegExp(`^${Vp(t)}$`)}function Jp(t){let e=`${Bp}T${Vp(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 Yb(t,e){return!!((e==="v4"||!e)&&Hb.test(t)||(e==="v6"||!e)&&Vb.test(t))}function Qb(t,e){if(!Lb.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 ew(t,e){return!!((e==="v4"||!e)&&Bb.test(t)||(e==="v6"||!e)&&Jb.test(t))}var cr=class t extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.string,received:s.parsedType}),D}let n=new Re,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(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),T(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?T(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Ub.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")nc||(nc=new RegExp(Fb,"u")),nc.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Zb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Db.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Nb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Mb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")jb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(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),T(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),T(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),T(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),T(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),T(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Jp(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Gb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Xb(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?qb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Yb(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Qb(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?ew(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Wb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Kb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):X.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,...N.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...N.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...N.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...N.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...N.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...N.errToObj(r)})}nonempty(e){return this.min(1,N.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}};cr.create=t=>new cr({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...H(t)});function tw(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 Mr=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)!==R.number){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.number,received:s.parsedType}),D}let n,o=new Re;for(let s of this._def.checks)s.kind==="int"?X.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(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),T(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),T(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?tw(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(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),T(n,{code:k.not_finite,message:s.message}),o.dirty()):X.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.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"&&X.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)}};Mr.create=t=>new Mr({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...H(t)});var jr=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)!==R.bigint)return this._getInvalidInput(e);let n,o=new Re;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),T(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),T(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),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):X.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:R.bigint,received:r.parsedType}),D}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.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:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.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}};jr.create=t=>new jr({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...H(t)});var Zr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.boolean,received:n.parsedType}),D}return Me(e.data)}};Zr.create=t=>new Zr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...H(t)});var Dr=class t extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.date,received:s.parsedType}),D}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_date}),D}let n=new Re,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(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),T(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):X.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:N.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:N.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}};Dr.create=t=>new Dr({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...H(t)});var $n=class extends V{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.symbol,received:n.parsedType}),D}return Me(e.data)}};$n.create=t=>new $n({typeName:S.ZodSymbol,...H(t)});var Lr=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.undefined,received:n.parsedType}),D}return Me(e.data)}};Lr.create=t=>new Lr({typeName:S.ZodUndefined,...H(t)});var qr=class extends V{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.null,received:n.parsedType}),D}return Me(e.data)}};qr.create=t=>new qr({typeName:S.ZodNull,...H(t)});var ur=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Me(e.data)}};ur.create=t=>new ur({typeName:S.ZodAny,...H(t)});var Jt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Me(e.data)}};Jt.create=t=>new Jt({typeName:S.ZodUnknown,...H(t)});var vt=class extends V{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:R.never,received:r.parsedType}),D}};vt.create=t=>new vt({typeName:S.ZodNever,...H(t)});var kn=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.void,received:n.parsedType}),D}return Me(e.data)}};kn.create=t=>new kn({typeName:S.ZodVoid,...H(t)});var Wt=class t extends V{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==R.array)return T(r,{code:k.invalid_type,expected:R.array,received:r.parsedType}),D;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(T(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&&(T(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&&(T(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 at(r,i,r.path,a)))).then(i=>Re.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new at(r,i,r.path,a)));return Re.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:N.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:N.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:N.toString(r)}})}nonempty(e){return this.min(1,e)}};Wt.create=(t,e)=>new Wt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...H(e)});function wn(t){if(t instanceof Ge){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ke.create(wn(n))}return new Ge({...t._def,shape:()=>e})}else return t instanceof Wt?new Wt({...t._def,type:wn(t.element)}):t instanceof Ke?Ke.create(wn(t.unwrap())):t instanceof Ct?Ct.create(wn(t.unwrap())):t instanceof It?It.create(t.items.map(e=>wn(e))):t}var Ge=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=X.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:k.invalid_type,expected:R.object,received:u.parsedType}),D}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof vt&&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 at(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof vt){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&&(T(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 at(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=>Re.mergeObjectSync(n,u)):Re.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return N.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:N.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 X.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 X.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return wn(this)}partial(e){let r={};for(let n of X.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 X.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ke;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Wp(X.objectKeys(this.shape))}};Ge.create=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strip",catchall:vt.create(),typeName:S.ZodObject,...H(e)});Ge.strictCreate=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strict",catchall:vt.create(),typeName:S.ZodObject,...H(e)});Ge.lazycreate=(t,e)=>new Ge({shape:t,unknownKeys:"strip",catchall:vt.create(),typeName:S.ZodObject,...H(e)});var Ur=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 We(a.ctx.common.issues));return T(r,{code:k.invalid_union,unionErrors:i}),D}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 We(c));return T(r,{code:k.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};Ur.create=(t,e)=>new Ur({options:t,typeName:S.ZodUnion,...H(e)});var Vt=t=>t instanceof Hr?Vt(t.schema):t instanceof ct?Vt(t.innerType()):t instanceof Br?[t.value]:t instanceof Vr?t.options:t instanceof Jr?X.objectValues(t.enum):t instanceof Wr?Vt(t._def.innerType):t instanceof Lr?[void 0]:t instanceof qr?[null]:t instanceof Ke?[void 0,...Vt(t.unwrap())]:t instanceof Ct?[null,...Vt(t.unwrap())]:t instanceof vo||t instanceof Gr?Vt(t.unwrap()):t instanceof Kr?Vt(t._def.innerType):[],Os=class t extends V{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:k.invalid_type,expected:R.object,received:r.parsedType}),D;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}):(T(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}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=Vt(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,...H(n)})}};function oc(t,e){let r=Pt(t),n=Pt(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let o=X.objectKeys(e),s=X.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=oc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.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=oc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Fr=class extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Cs(s)||Cs(i))return D;let a=oc(s.value,i.value);return a.valid?((As(s)||As(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:k.invalid_intersection_types}),D)};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}))}};Fr.create=(t,e,r)=>new Fr({left:t,right:e,typeName:S.ZodIntersection,...H(r)});var It=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:k.invalid_type,expected:R.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return T(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&n.data.length>this._def.items.length&&(T(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 at(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Re.mergeArray(r,i)):Re.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};It.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new It({items:t,typeName:S.ZodTuple,rest:null,...H(e)})};var Ns=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!==R.object)return T(n,{code:k.invalid_type,expected:R.object,received:n.parsedType}),D;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new at(n,a,n.path,a)),value:i._parse(new at(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Re.mergeObjectAsync(r,o):Re.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,...H(n)}):new t({keyType:cr.create(),valueType:e,typeName:S.ZodRecord,...H(r)})}},Sn=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!==R.map)return T(n,{code:k.invalid_type,expected:R.map,received:n.parsedType}),D;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new at(n,a,n.path,[u,"key"])),value:s._parse(new at(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 D;(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 D;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Sn.create=(t,e,r)=>new Sn({valueType:e,keyType:t,typeName:S.ZodMap,...H(r)});var Tn=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:k.invalid_type,expected:R.set,received:n.parsedType}),D;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(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&&(T(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 D;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 at(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:N.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:N.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Tn.create=(t,e)=>new Tn({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...H(e)});var Ms=class t extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return T(r,{code:k.invalid_type,expected:R.function,received:r.parsedType}),D;function n(a,c){return _o({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,xn(),Bt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return _o({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,xn(),Bt].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 lr){let a=this;return Me(async function(...c){let u=new We([]),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 Me(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new We([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new We([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:It.create(e).rest(Jt.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||It.create([]).rest(Jt.create()),returns:r||Jt.create(),typeName:S.ZodFunction,...H(n)})}},Hr=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})}};Hr.create=(t,e)=>new Hr({getter:t,typeName:S.ZodLazy,...H(e)});var Br=class extends V{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:e.data}}get value(){return this._def.value}};Br.create=(t,e)=>new Br({value:t,typeName:S.ZodLiteral,...H(e)});function Wp(t,e){return new Vr({values:t,typeName:S.ZodEnum,...H(e)})}var Vr=class t extends V{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:X.joinValues(n),received:r.parsedType,code:k.invalid_type}),D}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 T(r,{received:r.data,code:k.invalid_enum_value,options:n}),D}return Me(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Vr.create=Wp;var Jr=class extends V{_parse(e){let r=X.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=X.objectValues(r);return T(n,{expected:X.joinValues(o),received:n.parsedType,code:k.invalid_type}),D}if(this._cache||(this._cache=new Set(X.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=X.objectValues(r);return T(n,{received:n.data,code:k.invalid_enum_value,options:o}),D}return Me(e.data)}get enum(){return this._def.values}};Jr.create=(t,e)=>new Jr({values:t,typeName:S.ZodNativeEnum,...H(e)});var lr=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return T(r,{code:k.invalid_type,expected:R.promise,received:r.parsedType}),D;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Me(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};lr.create=(t,e)=>new lr({type:t,typeName:S.ZodPromise,...H(e)});var ct=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=>{T(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 D;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?D:c.status==="dirty"?Nr(c.value):r.value==="dirty"?Nr(c.value):c});{if(r.value==="aborted")return D;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?D:a.status==="dirty"?Nr(a.value):r.value==="dirty"?Nr(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"?D:(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"?D:(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(!ar(i))return D;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=>ar(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):D);X.assertNever(o)}};ct.create=(t,e,r)=>new ct({schema:t,typeName:S.ZodEffects,effect:e,...H(r)});ct.createWithPreprocess=(t,e,r)=>new ct({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...H(r)});var Ke=class extends V{_parse(e){return this._getType(e)===R.undefined?Me(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ke.create=(t,e)=>new Ke({innerType:t,typeName:S.ZodOptional,...H(e)});var Ct=class extends V{_parse(e){return this._getType(e)===R.null?Me(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ct.create=(t,e)=>new Ct({innerType:t,typeName:S.ZodNullable,...H(e)});var Wr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Wr.create=(t,e)=>new Wr({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});var Kr=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 bn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new We(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new We(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Kr.create=(t,e)=>new Kr({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});var En=class extends V{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.nan,received:n.parsedType}),D}return{status:"valid",value:e.data}}};En.create=t=>new En({typeName:S.ZodNaN,...H(t)});var rw=Symbol("zod_brand"),vo=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}},xo=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"?D:s.status==="dirty"?(r.dirty(),Nr(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"?D: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})}},Gr=class extends V{_parse(e){let r=this._def.innerType._parse(e),n=o=>(ar(o)&&(o.value=Object.freeze(o.value)),o);return bn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Gr.create=(t,e)=>new Gr({innerType:t,typeName:S.ZodReadonly,...H(e)});function Hp(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Kp(t,e={},r){return t?ur.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Hp(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Hp(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):ur.create()}var nw={object:Ge.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 ow=(t,e={message:`Input not instance of ${t.name}`})=>Kp(r=>r instanceof t,e),Gp=cr.create,Xp=Mr.create,sw=En.create,iw=jr.create,Yp=Zr.create,aw=Dr.create,cw=$n.create,uw=Lr.create,lw=qr.create,dw=ur.create,fw=Jt.create,pw=vt.create,mw=kn.create,hw=Wt.create,sc=Ge.create,gw=Ge.strictCreate,yw=Ur.create,_w=Os.create,vw=Fr.create,xw=It.create,bw=Ns.create,ww=Sn.create,$w=Tn.create,kw=Ms.create,Sw=Hr.create,Tw=Br.create,Ew=Vr.create,zw=Jr.create,Rw=lr.create,Pw=ct.create,Iw=Ke.create,Cw=Ct.create,Aw=ct.createWithPreprocess,Ow=xo.create,Nw=()=>Gp().optional(),Mw=()=>Xp().optional(),jw=()=>Yp().optional(),Zw={string:(t=>cr.create({...t,coerce:!0})),number:(t=>Mr.create({...t,coerce:!0})),boolean:(t=>Zr.create({...t,coerce:!0})),bigint:(t=>jr.create({...t,coerce:!0})),date:(t=>Dr.create({...t,coerce:!0}))};var Dw=D;Ue();Ue();Ue();Ue();var W$=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ue.init(t,e),t.def=e,t.parse=(r,n)=>xc(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Qr(t,r,n),t.parseAsync=async(r,n)=>wc(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>en(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)=>st(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var K$=w("ZodMiniObject",(t,e)=>{Ws.init(t,e),W$.init(t,e),Y.defineLazy(t,"shape",()=>e.shape)});function cl(t,e){let r={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new K$(r)}Ue();Gs();function Nt(t){return!!t._zod}function nn(t){let e=Object.values(t);if(e.length===0)return cl({});let r=e.every(Nt),n=e.every(o=>!Nt(o));if(r)return cl(t);if(n)return sc(t);throw new Error("Mixed Zod versions detected in object shape.")}function pr(t,e){return Nt(t)?Qr(t,e):t.safeParse(e)}async function oi(t,e){return Nt(t)?await en(t,e):await t.safeParseAsync(e)}function mr(t){if(!t)return;let e;if(Nt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Cn(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 nn(t)}}if(Nt(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 X$(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function si(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 ${X$(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 xh(t){return t.description}function bh(t){if(Nt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function An(t){if(Nt(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}gr();function yr(t){return t==="completed"||t==="failed"||t==="cancelled"}var fg=Symbol("Let zodToJsonSchema decide on which parser to use");var dg={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"},pg=t=>typeof t=="string"?{...dg,name:t}:{...dg,...t};var mg=t=>{let e=pg(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 Zl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,o){t[e]=r,Zl(t,e,n,o)}var Pi=(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"?Pi(e,t.currentPath):e.join("/")}}function hg(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=q(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function gg(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?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function yg(){return{type:"boolean"}}function Ii(t,e){return q(t.type._def,e)}var _g=(t,e)=>q(t.innerType._def,e);function Dl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Dl(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 $T(t,e)}}var $T=(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":ee(r,"minimum",n.value,n.message,e);break;case"max":ee(r,"maximum",n.value,n.message,e);break}return r};function vg(t,e){return{...q(t.innerType._def,e),default:t.defaultValue()}}function xg(t,e){return e.effectStrategy==="input"?q(t.schema._def,e):we(e)}function bg(t){return{type:"string",enum:Array.from(t.values)}}var kT=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function wg(t,e){let r=[q(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),q(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(kT(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 $g(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,bt={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 Ci(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ee(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":wt(r,"email",n.message,e);break;case"format:idn-email":wt(r,"idn-email",n.message,e);break;case"pattern:zod":He(r,bt.email,n.message,e);break}break;case"url":wt(r,"uri",n.message,e);break;case"uuid":wt(r,"uuid",n.message,e);break;case"regex":He(r,n.regex,n.message,e);break;case"cuid":He(r,bt.cuid,n.message,e);break;case"cuid2":He(r,bt.cuid2,n.message,e);break;case"startsWith":He(r,RegExp(`^${ql(n.value,e)}`),n.message,e);break;case"endsWith":He(r,RegExp(`${ql(n.value,e)}$`),n.message,e);break;case"datetime":wt(r,"date-time",n.message,e);break;case"date":wt(r,"date",n.message,e);break;case"time":wt(r,"time",n.message,e);break;case"duration":wt(r,"duration",n.message,e);break;case"length":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{He(r,RegExp(ql(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&wt(r,"ipv4",n.message,e),n.version!=="v4"&&wt(r,"ipv6",n.message,e);break}case"base64url":He(r,bt.base64url,n.message,e);break;case"jwt":He(r,bt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&He(r,bt.ipv4Cidr,n.message,e),n.version!=="v4"&&He(r,bt.ipv6Cidr,n.message,e);break}case"emoji":He(r,bt.emoji(),n.message,e);break;case"ulid":{He(r,bt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{wt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ee(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{He(r,bt.base64,n.message,e);break}}break}case"nanoid":He(r,bt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ql(t,e){return e.patternStrategy==="escape"?TT(t):t}var ST=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function TT(t){let e="";for(let r=0;r<t.length;r++)ST.has(t[r])||(e+="\\"),e+=t[r];return e}function wt(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}}})):ee(t,"format",e,r,n)}function He(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:kg(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",kg(e,n),r,n)}function kg(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(!hb(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{let v=await vb(e,this._maxRequestBodySize);if(v.tooLarge){let y=yb(this._maxRequestBodySize);return this.onerror?.(new Error(y)),this.createJsonErrorResponse(413,-32e3,y)}i=JSON.parse(v.text)}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}if(Array.isArray(i)&&i.length>100)return this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${100} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${100} messages`);let a;try{Array.isArray(i)?a=i.map(v=>Zo.parse(v)):a=[Zo.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(Pl);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 y=this.validateProtocolVersion(e);if(y)return y}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!a.some(Xt)){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=>Pl(v)),m=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??Qh;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let y of a)Xt(y)&&this._requestToStreamMapping.set(y.id,l);for(let y of a)this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:s})});let p=new TextEncoder,f,g,h=new ReadableStream({start:v=>{f=v},cancel:()=>{g!==void 0&&clearInterval(g),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)Xt(v)&&(this._streamMapping.set(l,{controller:f,encoder:p,cleanup:()=>{g!==void 0&&clearInterval(g),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 y,x;Xt(v)&&this._eventStore&&m>="2025-11-25"&&(y=()=>{this.closeSSEStream(v.id)},x=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:y,closeStandaloneSSEStream:x})}}catch(v){this._streamMapping.get(l)?.cleanup(),this._resumableStreams.delete(l);for(let y of a)Xt(y)&&this._requestToStreamMapping.delete(y.id);throw v}return this._streamMapping.get(l)?.controller===f&&(g=this.startKeepAlive(f,p)),new Response(h,{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&&!Mn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Mn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Mn.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((Yt(e)||jn(e))&&(n=e.id),n===void 0){if(Yt(e)||jn(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(Yt(e)||jn(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 kb={};vo(kb,{StreamableHTTPServerTransport:()=>Fp});var Fp,Sb=G(()=>{ub();$b();Fp=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new tc(e),this._requestListener=Lp(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 Lp(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 Z={};vo(Z,{BRAND:()=>aw,DIRTY:()=>Mr,EMPTY_PATH:()=>Db,INVALID:()=>D,NEVER:()=>Hw,OK:()=>Me,ParseStatus:()=>Re,Schema:()=>V,ZodAny:()=>lr,ZodArray:()=>Kt,ZodBigInt:()=>Zr,ZodBoolean:()=>Dr,ZodBranded:()=>bo,ZodCatch:()=>Gr,ZodDate:()=>Lr,ZodDefault:()=>Kr,ZodDiscriminatedUnion:()=>Ms,ZodEffects:()=>ut,ZodEnum:()=>Jr,ZodError:()=>We,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Zs,ZodIntersection:()=>Hr,ZodIssueCode:()=>k,ZodLazy:()=>Br,ZodLiteral:()=>Vr,ZodMap:()=>Tn,ZodNaN:()=>zn,ZodNativeEnum:()=>Wr,ZodNever:()=>xt,ZodNull:()=>Ur,ZodNullable:()=>At,ZodNumber:()=>jr,ZodObject:()=>Ge,ZodOptional:()=>Ke,ZodParsedType:()=>R,ZodPipeline:()=>wo,ZodPromise:()=>dr,ZodReadonly:()=>Xr,ZodRecord:()=>js,ZodSchema:()=>V,ZodSet:()=>En,ZodString:()=>ur,ZodSymbol:()=>kn,ZodTransformer:()=>ut,ZodTuple:()=>Ct,ZodType:()=>V,ZodUndefined:()=>qr,ZodUnion:()=>Fr,ZodUnknown:()=>Wt,ZodVoid:()=>Sn,addIssueToContext:()=>T,any:()=>gw,array:()=>xw,bigint:()=>dw,boolean:()=>rm,coerce:()=>Fw,custom:()=>Qp,date:()=>fw,datetimeRegex:()=>Xp,defaultErrorMap:()=>Vt,discriminatedUnion:()=>$w,effect:()=>Nw,enum:()=>Cw,function:()=>Rw,getErrorMap:()=>bn,getParsedType:()=>It,instanceof:()=>uw,intersection:()=>kw,isAborted:()=>Os,isAsync:()=>wn,isDirty:()=>Ns,isValid:()=>cr,late:()=>cw,lazy:()=>Pw,literal:()=>Iw,makeIssue:()=>xo,map:()=>Ew,nan:()=>lw,nativeEnum:()=>Aw,never:()=>_w,null:()=>hw,nullable:()=>jw,number:()=>tm,object:()=>cc,objectUtil:()=>sc,oboolean:()=>Uw,onumber:()=>qw,optional:()=>Mw,ostring:()=>Lw,pipeline:()=>Dw,preprocess:()=>Zw,promise:()=>Ow,quotelessJson:()=>Mb,record:()=>Tw,set:()=>zw,setErrorMap:()=>Zb,strictObject:()=>bw,string:()=>em,symbol:()=>pw,transformer:()=>Nw,tuple:()=>Sw,undefined:()=>mw,union:()=>ww,unknown:()=>yw,util:()=>X,void:()=>vw});var X;(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})(X||(X={}));var sc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(sc||(sc={}));var R=X.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),It=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var k=X.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"]),Mb=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),We=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,X.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()}};We.create=t=>new We(t);var jb=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,X.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${X.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${X.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${X.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}"`:X.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,X.assertNever(t)}return{message:r}},Vt=jb;var Vp=Vt;function Zb(t){Vp=t}function bn(){return Vp}var xo=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}},Db=[];function T(t,e){let r=bn(),n=xo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Vt?void 0:Vt].filter(o=>!!o)});t.common.issues.push(n)}var Re=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 D;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 D;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}}},D=Object.freeze({status:"aborted"}),Mr=t=>({status:"dirty",value:t}),Me=t=>({status:"valid",value:t}),Os=t=>t.status==="aborted",Ns=t=>t.status==="dirty",cr=t=>t.status==="valid",wn=t=>typeof Promise<"u"&&t instanceof Promise;var N;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));var ct=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}},Jp=(t,e)=>{if(cr(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 We(t.common.issues);return this._error=r,this._error}}};function H(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 It(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:It(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Re,ctx:{common:e.parent.common,data:e.data,parsedType:It(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(wn(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:It(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Jp(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:It(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return cr(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=>cr(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:It(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(wn(o)?o:Promise.resolve(o));return Jp(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 ut({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 Ke.create(this,this._def)}nullable(){return At.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return dr.create(this,this._def)}or(e){return Fr.create([this,e],this._def)}and(e){return Hr.create(this,e,this._def)}transform(e){return new ut({...H(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Kr({...H(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new bo({typeName:S.ZodBranded,type:this,...H(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Gr({...H(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 wo.create(this,e)}readonly(){return Xr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Lb=/^c[^\s-]{8,}$/i,qb=/^[0-9a-z]+$/,Ub=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fb=/^[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,Hb=/^[a-z0-9_-]{21}$/i,Bb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Vb=/^[-+]?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)?)??$/,Jb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Wb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ic,Kb=/^(?:(?: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])$/,Gb=/^(?:(?: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])$/,Xb=/^(([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]))$/,Yb=/^(([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])$/,Qb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ew=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kp="((\\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])))",tw=new RegExp(`^${Kp}$`);function Gp(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 rw(t){return new RegExp(`^${Gp(t)}$`)}function Xp(t){let e=`${Kp}T${Gp(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 nw(t,e){return!!((e==="v4"||!e)&&Kb.test(t)||(e==="v6"||!e)&&Xb.test(t))}function ow(t,e){if(!Bb.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 sw(t,e){return!!((e==="v4"||!e)&&Gb.test(t)||(e==="v6"||!e)&&Yb.test(t))}var ur=class t extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.string,received:s.parsedType}),D}let n=new Re,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(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),T(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?T(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Jb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ic||(ic=new RegExp(Wb,"u")),ic.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Fb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Hb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Lb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")qb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Ub.test(e.data)||(o=this._getOrReturnCtx(e,o),T(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),T(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),T(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),T(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),T(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),T(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Xp(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?tw.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?rw(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Vb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?nw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?ow(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?sw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Qb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?ew.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):X.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,...N.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...N.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...N.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...N.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...N.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...N.errToObj(r)})}nonempty(e){return this.min(1,N.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}};ur.create=t=>new ur({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...H(t)});function iw(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 jr=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)!==R.number){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.number,received:s.parsedType}),D}let n,o=new Re;for(let s of this._def.checks)s.kind==="int"?X.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(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),T(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),T(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?iw(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(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),T(n,{code:k.not_finite,message:s.message}),o.dirty()):X.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.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"&&X.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)}};jr.create=t=>new jr({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...H(t)});var Zr=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)!==R.bigint)return this._getInvalidInput(e);let n,o=new Re;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),T(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),T(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),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):X.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:R.bigint,received:r.parsedType}),D}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.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:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.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}};Zr.create=t=>new Zr({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...H(t)});var Dr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.boolean,received:n.parsedType}),D}return Me(e.data)}};Dr.create=t=>new Dr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...H(t)});var Lr=class t extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.date,received:s.parsedType}),D}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_date}),D}let n=new Re,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(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),T(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):X.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:N.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:N.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}};Lr.create=t=>new Lr({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...H(t)});var kn=class extends V{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.symbol,received:n.parsedType}),D}return Me(e.data)}};kn.create=t=>new kn({typeName:S.ZodSymbol,...H(t)});var qr=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.undefined,received:n.parsedType}),D}return Me(e.data)}};qr.create=t=>new qr({typeName:S.ZodUndefined,...H(t)});var Ur=class extends V{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.null,received:n.parsedType}),D}return Me(e.data)}};Ur.create=t=>new Ur({typeName:S.ZodNull,...H(t)});var lr=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Me(e.data)}};lr.create=t=>new lr({typeName:S.ZodAny,...H(t)});var Wt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Me(e.data)}};Wt.create=t=>new Wt({typeName:S.ZodUnknown,...H(t)});var xt=class extends V{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:R.never,received:r.parsedType}),D}};xt.create=t=>new xt({typeName:S.ZodNever,...H(t)});var Sn=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.void,received:n.parsedType}),D}return Me(e.data)}};Sn.create=t=>new Sn({typeName:S.ZodVoid,...H(t)});var Kt=class t extends V{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==R.array)return T(r,{code:k.invalid_type,expected:R.array,received:r.parsedType}),D;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(T(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&&(T(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&&(T(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 ct(r,i,r.path,a)))).then(i=>Re.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new ct(r,i,r.path,a)));return Re.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:N.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:N.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:N.toString(r)}})}nonempty(e){return this.min(1,e)}};Kt.create=(t,e)=>new Kt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...H(e)});function $n(t){if(t instanceof Ge){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ke.create($n(n))}return new Ge({...t._def,shape:()=>e})}else return t instanceof Kt?new Kt({...t._def,type:$n(t.element)}):t instanceof Ke?Ke.create($n(t.unwrap())):t instanceof At?At.create($n(t.unwrap())):t instanceof Ct?Ct.create(t.items.map(e=>$n(e))):t}var Ge=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=X.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:k.invalid_type,expected:R.object,received:u.parsedType}),D}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof xt&&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 ct(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof xt){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&&(T(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 ct(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=>Re.mergeObjectSync(n,u)):Re.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return N.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:N.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 X.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 X.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return $n(this)}partial(e){let r={};for(let n of X.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 X.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ke;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Yp(X.objectKeys(this.shape))}};Ge.create=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strip",catchall:xt.create(),typeName:S.ZodObject,...H(e)});Ge.strictCreate=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strict",catchall:xt.create(),typeName:S.ZodObject,...H(e)});Ge.lazycreate=(t,e)=>new Ge({shape:t,unknownKeys:"strip",catchall:xt.create(),typeName:S.ZodObject,...H(e)});var Fr=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 We(a.ctx.common.issues));return T(r,{code:k.invalid_union,unionErrors:i}),D}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 We(c));return T(r,{code:k.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};Fr.create=(t,e)=>new Fr({options:t,typeName:S.ZodUnion,...H(e)});var Jt=t=>t instanceof Br?Jt(t.schema):t instanceof ut?Jt(t.innerType()):t instanceof Vr?[t.value]:t instanceof Jr?t.options:t instanceof Wr?X.objectValues(t.enum):t instanceof Kr?Jt(t._def.innerType):t instanceof qr?[void 0]:t instanceof Ur?[null]:t instanceof Ke?[void 0,...Jt(t.unwrap())]:t instanceof At?[null,...Jt(t.unwrap())]:t instanceof bo||t instanceof Xr?Jt(t.unwrap()):t instanceof Gr?Jt(t._def.innerType):[],Ms=class t extends V{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:k.invalid_type,expected:R.object,received:r.parsedType}),D;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}):(T(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}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=Jt(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,...H(n)})}};function ac(t,e){let r=It(t),n=It(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let o=X.objectKeys(e),s=X.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=ac(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.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=ac(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Hr=class extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Os(s)||Os(i))return D;let a=ac(s.value,i.value);return a.valid?((Ns(s)||Ns(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:k.invalid_intersection_types}),D)};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}))}};Hr.create=(t,e,r)=>new Hr({left:t,right:e,typeName:S.ZodIntersection,...H(r)});var Ct=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:k.invalid_type,expected:R.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return T(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&n.data.length>this._def.items.length&&(T(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 ct(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Re.mergeArray(r,i)):Re.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ct.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:t,typeName:S.ZodTuple,rest:null,...H(e)})};var js=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!==R.object)return T(n,{code:k.invalid_type,expected:R.object,received:n.parsedType}),D;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new ct(n,a,n.path,a)),value:i._parse(new ct(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Re.mergeObjectAsync(r,o):Re.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,...H(n)}):new t({keyType:ur.create(),valueType:e,typeName:S.ZodRecord,...H(r)})}},Tn=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!==R.map)return T(n,{code:k.invalid_type,expected:R.map,received:n.parsedType}),D;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new ct(n,a,n.path,[u,"key"])),value:s._parse(new ct(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 D;(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 D;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Tn.create=(t,e,r)=>new Tn({valueType:e,keyType:t,typeName:S.ZodMap,...H(r)});var En=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:k.invalid_type,expected:R.set,received:n.parsedType}),D;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(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&&(T(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 D;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 ct(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:N.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:N.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};En.create=(t,e)=>new En({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...H(e)});var Zs=class t extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return T(r,{code:k.invalid_type,expected:R.function,received:r.parsedType}),D;function n(a,c){return xo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,bn(),Vt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return xo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,bn(),Vt].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 dr){let a=this;return Me(async function(...c){let u=new We([]),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 Me(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new We([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new We([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:Ct.create(e).rest(Wt.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||Ct.create([]).rest(Wt.create()),returns:r||Wt.create(),typeName:S.ZodFunction,...H(n)})}},Br=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})}};Br.create=(t,e)=>new Br({getter:t,typeName:S.ZodLazy,...H(e)});var Vr=class extends V{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:e.data}}get value(){return this._def.value}};Vr.create=(t,e)=>new Vr({value:t,typeName:S.ZodLiteral,...H(e)});function Yp(t,e){return new Jr({values:t,typeName:S.ZodEnum,...H(e)})}var Jr=class t extends V{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:X.joinValues(n),received:r.parsedType,code:k.invalid_type}),D}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 T(r,{received:r.data,code:k.invalid_enum_value,options:n}),D}return Me(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Jr.create=Yp;var Wr=class extends V{_parse(e){let r=X.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=X.objectValues(r);return T(n,{expected:X.joinValues(o),received:n.parsedType,code:k.invalid_type}),D}if(this._cache||(this._cache=new Set(X.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=X.objectValues(r);return T(n,{received:n.data,code:k.invalid_enum_value,options:o}),D}return Me(e.data)}get enum(){return this._def.values}};Wr.create=(t,e)=>new Wr({values:t,typeName:S.ZodNativeEnum,...H(e)});var dr=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return T(r,{code:k.invalid_type,expected:R.promise,received:r.parsedType}),D;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Me(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};dr.create=(t,e)=>new dr({type:t,typeName:S.ZodPromise,...H(e)});var ut=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=>{T(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 D;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?D:c.status==="dirty"?Mr(c.value):r.value==="dirty"?Mr(c.value):c});{if(r.value==="aborted")return D;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?D:a.status==="dirty"?Mr(a.value):r.value==="dirty"?Mr(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"?D:(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"?D:(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(!cr(i))return D;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=>cr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):D);X.assertNever(o)}};ut.create=(t,e,r)=>new ut({schema:t,typeName:S.ZodEffects,effect:e,...H(r)});ut.createWithPreprocess=(t,e,r)=>new ut({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...H(r)});var Ke=class extends V{_parse(e){return this._getType(e)===R.undefined?Me(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ke.create=(t,e)=>new Ke({innerType:t,typeName:S.ZodOptional,...H(e)});var At=class extends V{_parse(e){return this._getType(e)===R.null?Me(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};At.create=(t,e)=>new At({innerType:t,typeName:S.ZodNullable,...H(e)});var Kr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Kr.create=(t,e)=>new Kr({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});var Gr=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 wn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new We(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new We(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Gr.create=(t,e)=>new Gr({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});var zn=class extends V{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.nan,received:n.parsedType}),D}return{status:"valid",value:e.data}}};zn.create=t=>new zn({typeName:S.ZodNaN,...H(t)});var aw=Symbol("zod_brand"),bo=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}},wo=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"?D:s.status==="dirty"?(r.dirty(),Mr(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"?D: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})}},Xr=class extends V{_parse(e){let r=this._def.innerType._parse(e),n=o=>(cr(o)&&(o.value=Object.freeze(o.value)),o);return wn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Xr.create=(t,e)=>new Xr({innerType:t,typeName:S.ZodReadonly,...H(e)});function Wp(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Qp(t,e={},r){return t?lr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Wp(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Wp(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):lr.create()}var cw={object:Ge.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 uw=(t,e={message:`Input not instance of ${t.name}`})=>Qp(r=>r instanceof t,e),em=ur.create,tm=jr.create,lw=zn.create,dw=Zr.create,rm=Dr.create,fw=Lr.create,pw=kn.create,mw=qr.create,hw=Ur.create,gw=lr.create,yw=Wt.create,_w=xt.create,vw=Sn.create,xw=Kt.create,cc=Ge.create,bw=Ge.strictCreate,ww=Fr.create,$w=Ms.create,kw=Hr.create,Sw=Ct.create,Tw=js.create,Ew=Tn.create,zw=En.create,Rw=Zs.create,Pw=Br.create,Iw=Vr.create,Cw=Jr.create,Aw=Wr.create,Ow=dr.create,Nw=ut.create,Mw=Ke.create,jw=At.create,Zw=ut.createWithPreprocess,Dw=wo.create,Lw=()=>em().optional(),qw=()=>tm().optional(),Uw=()=>rm().optional(),Fw={string:(t=>ur.create({...t,coerce:!0})),number:(t=>jr.create({...t,coerce:!0})),boolean:(t=>Dr.create({...t,coerce:!0})),bigint:(t=>Zr.create({...t,coerce:!0})),date:(t=>Lr.create({...t,coerce:!0}))};var Hw=D;Ue();Ue();Ue();Ue();var Q$=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ue.init(t,e),t.def=e,t.parse=(r,n)=>$c(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>en(t,r,n),t.parseAsync=async(r,n)=>Sc(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>tn(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)=>st(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var ek=w("ZodMiniObject",(t,e)=>{Gs.init(t,e),Q$.init(t,e),Y.defineLazy(t,"shape",()=>e.shape)});function dl(t,e){let r={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new ek(r)}Ue();Ys();function Mt(t){return!!t._zod}function on(t){let e=Object.values(t);if(e.length===0)return dl({});let r=e.every(Mt),n=e.every(o=>!Mt(o));if(r)return dl(t);if(n)return cc(t);throw new Error("Mixed Zod versions detected in object shape.")}function mr(t,e){return Mt(t)?en(t,e):t.safeParse(e)}async function ii(t,e){return Mt(t)?await tn(t,e):await t.safeParseAsync(e)}function hr(t){if(!t)return;let e;if(Mt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function An(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 on(t)}}if(Mt(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 rk(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ai(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 ${rk(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 kh(t){return t.description}function Sh(t){if(Mt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function On(t){if(Mt(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}yr();function _r(t){return t==="completed"||t==="failed"||t==="cancelled"}var gg=Symbol("Let zodToJsonSchema decide on which parser to use");var hg={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"},yg=t=>typeof t=="string"?{...hg,name:t}:{...hg,...t};var _g=t=>{let e=yg(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 ql(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,o){t[e]=r,ql(t,e,n,o)}var Ci=(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"?Ci(e,t.currentPath):e.join("/")}}function vg(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=q(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function xg(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?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function bg(){return{type:"boolean"}}function Ai(t,e){return q(t.type._def,e)}var wg=(t,e)=>q(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 zT(t,e)}}var zT=(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":ee(r,"minimum",n.value,n.message,e);break;case"max":ee(r,"maximum",n.value,n.message,e);break}return r};function $g(t,e){return{...q(t.innerType._def,e),default:t.defaultValue()}}function kg(t,e){return e.effectStrategy==="input"?q(t.schema._def,e):we(e)}function Sg(t){return{type:"string",enum:Array.from(t.values)}}var RT=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Tg(t,e){let r=[q(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),q(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(RT(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 Eg(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 Fl,wt={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:()=>(Fl===void 0&&(Fl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Fl),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 Oi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ee(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":$t(r,"email",n.message,e);break;case"format:idn-email":$t(r,"idn-email",n.message,e);break;case"pattern:zod":He(r,wt.email,n.message,e);break}break;case"url":$t(r,"uri",n.message,e);break;case"uuid":$t(r,"uuid",n.message,e);break;case"regex":He(r,n.regex,n.message,e);break;case"cuid":He(r,wt.cuid,n.message,e);break;case"cuid2":He(r,wt.cuid2,n.message,e);break;case"startsWith":He(r,RegExp(`^${Hl(n.value,e)}`),n.message,e);break;case"endsWith":He(r,RegExp(`${Hl(n.value,e)}$`),n.message,e);break;case"datetime":$t(r,"date-time",n.message,e);break;case"date":$t(r,"date",n.message,e);break;case"time":$t(r,"time",n.message,e);break;case"duration":$t(r,"duration",n.message,e);break;case"length":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{He(r,RegExp(Hl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&$t(r,"ipv4",n.message,e),n.version!=="v4"&&$t(r,"ipv6",n.message,e);break}case"base64url":He(r,wt.base64url,n.message,e);break;case"jwt":He(r,wt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&He(r,wt.ipv4Cidr,n.message,e),n.version!=="v4"&&He(r,wt.ipv6Cidr,n.message,e);break}case"emoji":He(r,wt.emoji(),n.message,e);break;case"ulid":{He(r,wt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{$t(r,"binary",n.message,e);break}case"contentEncoding:base64":{ee(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{He(r,wt.base64,n.message,e);break}}break}case"nanoid":He(r,wt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Hl(t,e){return e.patternStrategy==="escape"?IT(t):t}var PT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function IT(t){let e="";for(let r=0;r<t.length;r++)PT.has(t[r])||(e+="\\"),e+=t[r];return e}function $t(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}}})):ee(t,"format",e,r,n)}function He(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:zg(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",zg(e,n),r,n)}function zg(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 Ai(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]:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:q(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}=Ci(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}=Ii(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Sg(t,e){if(e.mapStrategy==="record")return Ai(t,e);let r=q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=q(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 Tg(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 Eg(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function zg(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Bo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Pg(t,e){if(e.target==="openApi3")return Rg(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Bo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Bo[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 Rg(t,e)}var Rg=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>q(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 Ig(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:Bo[t.innerType._def.typeName],nullable:!0}:{type:[Bo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Cg(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",Zl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function Ag(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=zT(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=q(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=ET(t,e);return i!==void 0&&(n.additionalProperties=i),n}function ET(t,e){if(t.catchall._def.typeName!=="ZodNever")return q(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 zT(t){try{return t.isOptional()}catch{return!0}}var Og=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return q(t.innerType._def,e);let r=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Ng=(t,e)=>{if(e.pipeStrategy==="input")return q(t.in._def,e);if(e.pipeStrategy==="output")return q(t.out._def,e);let r=q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Mg(t,e){return q(t.type._def,e)}function jg(t,e){let n={type:"array",uniqueItems:!0,items:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Zg(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Dg(t){return{not:we(t)}}function Lg(t){return we(t)}var qg=(t,e)=>q(t.innerType._def,e);var Ug=(t,e,r)=>{switch(e){case S.ZodString:return Ci(t,r);case S.ZodNumber:return Cg(t,r);case S.ZodObject:return Ag(t,r);case S.ZodBigInt:return gg(t,r);case S.ZodBoolean:return yg();case S.ZodDate:return Dl(t,r);case S.ZodUndefined:return Dg(r);case S.ZodNull:return zg(r);case S.ZodArray:return hg(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Pg(t,r);case S.ZodIntersection:return wg(t,r);case S.ZodTuple:return Zg(t,r);case S.ZodRecord:return Ai(t,r);case S.ZodLiteral:return $g(t,r);case S.ZodEnum:return bg(t);case S.ZodNativeEnum:return Tg(t);case S.ZodNullable:return Ig(t,r);case S.ZodOptional:return Og(t,r);case S.ZodMap:return Sg(t,r);case S.ZodSet:return jg(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Mg(t,r);case S.ZodNaN:case S.ZodNever:return Eg(r);case S.ZodEffects:return xg(t,r);case S.ZodAny:return we(r);case S.ZodUnknown:return Lg(r);case S.ZodDefault:return vg(t,r);case S.ZodBranded:return Ii(t,r);case S.ZodReadonly:return qg(t,r);case S.ZodCatch:return _g(t,r);case S.ZodPipeline:return Ng(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==fg)return a}if(n&&!r){let a=RT(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=Ug(t,t.typeName,e),i=typeof s=="function"?q(s(),e):s;if(i&&PT(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var RT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Pi(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}},PT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Ul=(t,e)=>{let r=mg(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:q(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=q(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 IT(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Fl(t,e){return Nt(t)?al(t,{target:IT(e?.target),io:e?.pipeStrategy??"input"}):Ul(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Hl(t){let r=mr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=An(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Bl(t,e){let r=pr(t,e);if(!r.success)throw r.error;return r.data}var CT=6e4,Oi=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(fi,r=>{this._oncancel(r)}),this.setNotificationHandler(hi,r=>{this._onprogress(r)}),this.setRequestHandler(mi,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(gi,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(_i,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new I(A.InvalidParams,`Task not found: ${s}`);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(!yr(i.status))return await this._waitForTaskUpdate(s,n.signal,n.sessionId),await o();if(yr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s,n.sessionId),{...a,_meta:{...a._meta,[hr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(vi,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(bi,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(yr(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,n.sessionId);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),Xt(s)||Mn(s)?this._onresponse(s):Gt(s)?this._onrequest(s,i):tg(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?.[hr]?.taskId,i=o?.sessionId,a=this._taskStore,c=!0,u;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(c=!1,u=(async()=>{if(!await a.getTask(s,i))throw new I(A.InvalidParams,`Task not found: ${s}`);c=!0})()),n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:A.MethodNotFound,message:"Method not found"}};if(s&&u){let g={type:"error",message:f,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(s,g,i),()=>o?.send(f)).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):o?.send(f).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let d=Yh(e.params)?e.params.task:void 0,m=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,p={signal:l.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async f=>{if(l.signal.aborted)return;let g={relatedRequestId:e.id};s&&(g.relatedTask={taskId:s}),await this.notification(f,g)},sendRequest:async(f,g,h)=>{if(l.signal.aborted)throw new I(A.ConnectionClosed,"Request was cancelled");let _={...h,relatedRequestId:e.id};s&&!_.relatedTask&&(_.relatedTask={taskId:s});let v=_.relatedTask?.taskId??s;return v&&m&&await m.updateTaskStatus(v,"input_required"),await this.request(f,g,_)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:m,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new I(A.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,p)).then(async f=>{if(l.signal.aborted)return;let g={result:f,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)},async f=>{if(l.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:A.InternalError,message:f.message??"Internal error",...f.data!==void 0&&{data:f.data}}};s&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&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),Xt(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(Xt(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),Xt(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,jn,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},yr(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||{},[hr]: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(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let y=v instanceof I?v:new I(A.RequestTimeout,String(v));l(y)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let y=pr(r,v.result);y.success?u(y.data):l(y.error)}catch(y){l(y)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let g=n?.timeout??CT,h=()=>f(I.fromError(A.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(m,g,n?.maxTotalTimeout,h,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=y=>{let x=this._responseHandlers.get(m);x?x(y):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(y=>{this._cleanupTimeout(m),l(y)})}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},yi,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},xi,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ng,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||{},[hr]: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||{},[hr]: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||{},[hr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Hl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Bl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Hl(e);this._notificationHandlers.set(n,o=>{let s=Bl(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??this._transport?.sessionId,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"&&Gt(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,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e,n);s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new I(A.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(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=qo.parse({method:"notifications/tasks/status",params:a});await this.notification(c),yr(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(yr(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=qo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),yr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Fg(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Hg(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];Fg(i)&&Fg(s)?r[o]={...i,...s}:r[o]=s}return r}gr();var F0=tc(Zf(),1),H0=tc(U0(),1);function FI(){let t=new F0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,H0.default)(t),t}var ya=class{constructor(e){this._ajv=e??FI()}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)}}};gr();var _a=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},Ho,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},Ln,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 B0(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 V0(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 va=class extends Oi{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Fo.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 ya,this.setRequestHandler(pi,n=>this._oninitialize(n)),this.setNotificationHandler(zl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Nl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Fo.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new _a(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Hg(this._capabilities,e)}setRequestHandler(e,r){let o=mr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=An(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=pr(Dn,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=pr(jn,m);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new I(A.InvalidParams,`Invalid task creation result: ${g}`)}return f.data}let p=pr(zi,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){V0(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&B0(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:Nn.includes(r)?r:$l,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"},di)}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},Ml,r):this.request({method:"sampling/createMessage",params:e},Ho,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},Ln,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},Ln,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},jl,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"})}};gr();var W0=Symbol.for("mcp.completable");function Vf(t){return!!t&&typeof t=="object"&&W0 in t}function K0(t){return t[W0]?.complete}var J0;(function(t){t.Completable="McpCompletable"})(J0||(J0={}));var xa=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let r=[],n="",o=0,s=0;for(;o<e.length;)if(e[o]==="{"){n&&(r.push(n),n="");let i=e.indexOf("}",o);if(i===-1)throw new Error("Unclosed template expression");if(s++,s>1e4)throw new Error("Template contains too many expressions (max 10000)");let a=e.slice(o+1,i),c=this.getOperator(a),u=a.includes("*"),l=this.getNames(a),d=l[0];for(let m of l)t.validateLength(m,1e6,"Variable name");r.push({name:d,operator:c,names:l,exploded:u}),o=i+1}else n+=e[o],o++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){let r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return t.validateLength(e,1e6,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){let i=e.names.map(c=>{let u=r[c];if(u===void 0)return"";let l=Array.isArray(u)?u.map(d=>this.encodeValue(d,e.operator)).join(","):this.encodeValue(u.toString(),e.operator);return`${c}=${l}`}).filter(c=>c.length>0);return i.length===0?"":(e.operator==="?"?"?":"&")+i.join("&")}if(e.names.length>1){let i=e.names.map(a=>r[a]).filter(a=>a!==void 0);return i.length===0?"":i.map(a=>Array.isArray(a)?a[0]:a).join(",")}let n=r[e.name];if(n===void 0)return"";let s=(Array.isArray(n)?n:[n]).map(i=>this.encodeValue(i,e.operator));switch(e.operator){case"":return s.join(",");case"+":return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/");default:return s.join(",")}}expand(e){let r="",n=!1;for(let o of this.parts){if(typeof o=="string"){r+=o;continue}let s=this.expandPart(o,e);s&&((o.operator==="?"||o.operator==="&")&&n?r+=s.replace("?","&"):r+=s,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let r=[];for(let s of e.names)t.validateLength(s,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let s=0;s<e.names.length;s++){let i=e.names[s],a=s===0?"\\"+e.operator:"&";r.push({pattern:a+this.escapeRegExp(i)+"=([^&]+)",name:i})}return r}let n,o=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:o}),r}match(e){t.validateLength(e,1e6,"URI");let r="^",n=[];for(let a of this.parts)if(typeof a=="string")r+=this.escapeRegExp(a);else{let c=this.partToRegExp(a);for(let{pattern:u,name:l}of c)r+=u,n.push({name:l,exploded:a.exploded})}r+="$",t.validateLength(r,1e6,"Generated regex pattern");let o=new RegExp(r),s=e.match(o);if(!s)return null;let i={};for(let a=0;a<n.length;a++){let{name:c,exploded:u}=n[a],l=s[a+1],d=c.replace("*","");u&&l.includes(",")?i[d]=l.split(","):i[d]=l}return i}};var HI=/^[A-Za-z0-9._-]{1,128}$/;function BI(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"),!HI.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 VI(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 Jf(t){let e=BI(t);return VI(t,e.warnings),e.isValid}var ba=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)}};function JI(t,e){let r=0,n=[t];for(;n.length>0;){let o=n.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let s of o){if(++r>e)return r;s!==null&&typeof s=="object"&&n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>e)return r;let i=o[s];i!==null&&typeof i=="object"&&n.push(i)}}return r}function WI(t){if(!(t===void 0||t===1/0)){if(typeof t!="number"||Number.isNaN(t)||t<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(t)}`);return t}}var wa=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 va(e,r),this._maxToolInputElements=WI(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new ba(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Tr(Ei)),this.server.assertCanSetRequestHandler(Tr(Dn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ei,()=>({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=Cn(r.inputSchema);return o?Fl(o,{strictUnions:!0,pipeStrategy:"input"}):KI})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Cn(r.outputSchema);o&&(n.outputSchema=Fl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Dn,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(this._maxToolInputElements!==void 0&&JI(r,this._maxToolInputElements)>this._maxToolInputElements)throw new I(A.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=Cn(e.inputSchema)??e.inputSchema,i=await oi(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",c=si(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=Cn(e.outputSchema),s=await oi(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=si(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(Tr(Ri)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ri,async e=>{switch(e.params.ref.type){case"ref/prompt":return ug(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return lg(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 ws;let s=mr(n.argsSchema)?.[e.params.argument.name];if(!Vf(s))return ws;let i=K0(s);if(!i)return ws;let a=await i(e.params.argument.value,e.params.context);return X0(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 ws;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 ws;let s=await o(e.params.argument.value,e.params.context);return X0(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Tr(wi)),this.server.assertCanSetRequestHandler(Tr($i)),this.server.assertCanSetRequestHandler(Tr(ki)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(wi,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($i,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ki,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(Tr(Si)),this.server.assertCanSetRequestHandler(Tr(Ti)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Si,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?GI(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ti,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=Cn(n.argsSchema),s=await oi(o,e.params.arguments??{});if(!s.success){let c="error"in s?s.error:"Unknown error",u=si(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:nn(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=nn(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 Ke?c._def?.innerType:c;return Vf(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){Jf(e);let l={title:r,description:n,inputSchema:G0(o),outputSchema:G0(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"&&Jf(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=nn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=nn(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(Wf(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Wf(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()}},$a=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new xa(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},KI={type:"object",properties:{}};function Y0(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Q0(t){return"_def"in t||"_zod"in t||Y0(t)}function Wf(t){return typeof t!="object"||t===null||Q0(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Y0)}function G0(t){if(t){if(Wf(t))return nn(t);if(!Q0(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function GI(t){let e=mr(t);return e?Object.entries(e).map(([r,n])=>{let o=xh(n),s=bh(n);return{name:r,description:o,required:!s}}):[]}function Tr(t){let r=mr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=An(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function X0(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ws={completion:{values:[],hasMore:!1}};import tv from"node:process";gr();var XI=10*1024*1024,ka=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??XI}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
|
-
`:"")+m.text,i||=m.hasBinary,m.kind&&(a=m.kind),c??=m.toolName,m.call&&(u+=m.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
|
|
61
|
-
`):"";return{index:e,role:"assistant",kind:"assistant",text:o,hasBinary:!1}}return
|
|
62
|
-
`),o=d=>{try{return[JSON.parse(d)]}catch{return[]}},s=new Set,i=0;for(let d=n.length-1;d>=0&&s.size<
|
|
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 Ni(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]:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:q(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}=Oi(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}=Ai(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Rg(t,e){if(e.mapStrategy==="record")return Ni(t,e);let r=q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=q(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 Pg(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 Ig(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function Cg(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Jo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Og(t,e){if(e.target==="openApi3")return Ag(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Jo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Jo[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 Ag(t,e)}var Ag=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>q(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 Ng(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:Jo[t.innerType._def.typeName],nullable:!0}:{type:[Jo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Mg(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",ql(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function jg(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=AT(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=q(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=CT(t,e);return i!==void 0&&(n.additionalProperties=i),n}function CT(t,e){if(t.catchall._def.typeName!=="ZodNever")return q(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 AT(t){try{return t.isOptional()}catch{return!0}}var Zg=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return q(t.innerType._def,e);let r=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Dg=(t,e)=>{if(e.pipeStrategy==="input")return q(t.in._def,e);if(e.pipeStrategy==="output")return q(t.out._def,e);let r=q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Lg(t,e){return q(t.type._def,e)}function qg(t,e){let n={type:"array",uniqueItems:!0,items:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Ug(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Fg(t){return{not:we(t)}}function Hg(t){return we(t)}var Bg=(t,e)=>q(t.innerType._def,e);var Vg=(t,e,r)=>{switch(e){case S.ZodString:return Oi(t,r);case S.ZodNumber:return Mg(t,r);case S.ZodObject:return jg(t,r);case S.ZodBigInt:return xg(t,r);case S.ZodBoolean:return bg();case S.ZodDate:return Ul(t,r);case S.ZodUndefined:return Fg(r);case S.ZodNull:return Cg(r);case S.ZodArray:return vg(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Og(t,r);case S.ZodIntersection:return Tg(t,r);case S.ZodTuple:return Ug(t,r);case S.ZodRecord:return Ni(t,r);case S.ZodLiteral:return Eg(t,r);case S.ZodEnum:return Sg(t);case S.ZodNativeEnum:return Pg(t);case S.ZodNullable:return Ng(t,r);case S.ZodOptional:return Zg(t,r);case S.ZodMap:return Rg(t,r);case S.ZodSet:return qg(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Lg(t,r);case S.ZodNaN:case S.ZodNever:return Ig(r);case S.ZodEffects:return kg(t,r);case S.ZodAny:return we(r);case S.ZodUnknown:return Hg(r);case S.ZodDefault:return $g(t,r);case S.ZodBranded:return Ai(t,r);case S.ZodReadonly:return Bg(t,r);case S.ZodCatch:return wg(t,r);case S.ZodPipeline:return Dg(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==gg)return a}if(n&&!r){let a=OT(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=Vg(t,t.typeName,e),i=typeof s=="function"?q(s(),e):s;if(i&&NT(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var OT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ci(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}},NT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Bl=(t,e)=>{let r=_g(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:q(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=q(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 MT(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Vl(t,e){return Mt(t)?ll(t,{target:MT(e?.target),io:e?.pipeStrategy??"input"}):Bl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Jl(t){let r=hr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=On(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Wl(t,e){let r=mr(t,e);if(!r.success)throw r.error;return r.data}var jT=6e4,Mi=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(mi,r=>{this._oncancel(r)}),this.setNotificationHandler(yi,r=>{this._onprogress(r)}),this.setRequestHandler(gi,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(_i,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(xi,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new I(A.InvalidParams,`Task not found: ${s}`);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(!_r(i.status))return await this._waitForTaskUpdate(s,n.signal,n.sessionId),await o();if(_r(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s,n.sessionId),{...a,_meta:{...a._meta,[gr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(bi,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($i,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(_r(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,n.sessionId);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),Yt(s)||jn(s)?this._onresponse(s):Xt(s)?this._onrequest(s,i):sg(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?.[gr]?.taskId,i=o?.sessionId,a=this._taskStore,c=!0,u;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(c=!1,u=(async()=>{if(!await a.getTask(s,i))throw new I(A.InvalidParams,`Task not found: ${s}`);c=!0})()),n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:A.MethodNotFound,message:"Method not found"}};if(s&&u){let g={type:"error",message:f,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(s,g,i),()=>o?.send(f)).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):o?.send(f).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let d=rg(e.params)?e.params.task:void 0,m=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,p={signal:l.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async f=>{if(l.signal.aborted)return;let g={relatedRequestId:e.id};s&&(g.relatedTask={taskId:s}),await this.notification(f,g)},sendRequest:async(f,g,h)=>{if(l.signal.aborted)throw new I(A.ConnectionClosed,"Request was cancelled");let _={...h,relatedRequestId:e.id};s&&!_.relatedTask&&(_.relatedTask={taskId:s});let v=_.relatedTask?.taskId??s;return v&&m&&await m.updateTaskStatus(v,"input_required"),await this.request(f,g,_)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:m,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new I(A.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,p)).then(async f=>{if(l.signal.aborted)return;let g={result:f,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)},async f=>{if(l.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:A.InternalError,message:f.message??"Internal error",...f.data!==void 0&&{data:f.data}}};s&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&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),Yt(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(Yt(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),Yt(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,Zn,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},_r(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||{},[gr]: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(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let y=v instanceof I?v:new I(A.RequestTimeout,String(v));l(y)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let y=mr(r,v.result);y.success?u(y.data):l(y.error)}catch(y){l(y)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let g=n?.timeout??jT,h=()=>f(I.fromError(A.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(m,g,n?.maxTotalTimeout,h,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=y=>{let x=this._responseHandlers.get(m);x?x(y):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(y=>{this._cleanupTimeout(m),l(y)})}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},vi,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},wi,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ag,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||{},[gr]: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||{},[gr]: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||{},[gr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Jl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Wl(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=Jl(e);this._notificationHandlers.set(n,o=>{let s=Wl(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??this._transport?.sessionId,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"&&Xt(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,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e,n);s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new I(A.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(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=Fo.parse({method:"notifications/tasks/status",params:a});await this.notification(c),_r(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(_r(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=Fo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),_r(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Jg(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Wg(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];Jg(i)&&Jg(s)?r[o]={...i,...s}:r[o]=s}return r}yr();var J0=oc(qf(),1),W0=oc(V0(),1);function WI(){let t=new J0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,W0.default)(t),t}var va=class{constructor(e){this._ajv=e??WI()}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)}}};yr();var xa=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},Vo,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},qn,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 K0(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 G0(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 ba=class extends Mi{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 va,this.setRequestHandler(hi,n=>this._oninitialize(n)),this.setNotificationHandler(Il,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Zl,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 xa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Wg(this._capabilities,e)}setRequestHandler(e,r){let o=hr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=On(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=mr(Ln,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=mr(Zn,m);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new I(A.InvalidParams,`Invalid task creation result: ${g}`)}return f.data}let p=mr(Pi,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){G0(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&K0(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:Mn.includes(r)?r:Tl,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"},pi)}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},Dl,r):this.request({method:"sampling/createMessage",params:e},Vo,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},qn,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},qn,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},Ll,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"})}};yr();var Y0=Symbol.for("mcp.completable");function Kf(t){return!!t&&typeof t=="object"&&Y0 in t}function Q0(t){return t[Y0]?.complete}var X0;(function(t){t.Completable="McpCompletable"})(X0||(X0={}));var wa=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let r=[],n="",o=0,s=0;for(;o<e.length;)if(e[o]==="{"){n&&(r.push(n),n="");let i=e.indexOf("}",o);if(i===-1)throw new Error("Unclosed template expression");if(s++,s>1e4)throw new Error("Template contains too many expressions (max 10000)");let a=e.slice(o+1,i),c=this.getOperator(a),u=a.includes("*"),l=this.getNames(a),d=l[0];for(let m of l)t.validateLength(m,1e6,"Variable name");r.push({name:d,operator:c,names:l,exploded:u}),o=i+1}else n+=e[o],o++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){let r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return t.validateLength(e,1e6,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){let i=e.names.map(c=>{let u=r[c];if(u===void 0)return"";let l=Array.isArray(u)?u.map(d=>this.encodeValue(d,e.operator)).join(","):this.encodeValue(u.toString(),e.operator);return`${c}=${l}`}).filter(c=>c.length>0);return i.length===0?"":(e.operator==="?"?"?":"&")+i.join("&")}if(e.names.length>1){let i=e.names.map(a=>r[a]).filter(a=>a!==void 0);return i.length===0?"":i.map(a=>Array.isArray(a)?a[0]:a).join(",")}let n=r[e.name];if(n===void 0)return"";let s=(Array.isArray(n)?n:[n]).map(i=>this.encodeValue(i,e.operator));switch(e.operator){case"":return s.join(",");case"+":return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/");default:return s.join(",")}}expand(e){let r="",n=!1;for(let o of this.parts){if(typeof o=="string"){r+=o;continue}let s=this.expandPart(o,e);s&&((o.operator==="?"||o.operator==="&")&&n?r+=s.replace("?","&"):r+=s,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let r=[];for(let s of e.names)t.validateLength(s,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let s=0;s<e.names.length;s++){let i=e.names[s],a=s===0?"\\"+e.operator:"&";r.push({pattern:a+this.escapeRegExp(i)+"=([^&]+)",name:i})}return r}let n,o=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:o}),r}match(e){t.validateLength(e,1e6,"URI");let r="^",n=[];for(let a of this.parts)if(typeof a=="string")r+=this.escapeRegExp(a);else{let c=this.partToRegExp(a);for(let{pattern:u,name:l}of c)r+=u,n.push({name:l,exploded:a.exploded})}r+="$",t.validateLength(r,1e6,"Generated regex pattern");let o=new RegExp(r),s=e.match(o);if(!s)return null;let i={};for(let a=0;a<n.length;a++){let{name:c,exploded:u}=n[a],l=s[a+1],d=c.replace("*","");u&&l.includes(",")?i[d]=l.split(","):i[d]=l}return i}};var KI=/^[A-Za-z0-9._-]{1,128}$/;function GI(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"),!KI.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 XI(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 Gf(t){let e=GI(t);return XI(t,e.warnings),e.isValid}var $a=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)}};function YI(t,e){let r=0,n=[t];for(;n.length>0;){let o=n.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let s of o){if(++r>e)return r;s!==null&&typeof s=="object"&&n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>e)return r;let i=o[s];i!==null&&typeof i=="object"&&n.push(i)}}return r}function QI(t){if(!(t===void 0||t===1/0)){if(typeof t!="number"||Number.isNaN(t)||t<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(t)}`);return t}}var ka=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 ba(e,r),this._maxToolInputElements=QI(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new $a(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Er(Ri)),this.server.assertCanSetRequestHandler(Er(Ln)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ri,()=>({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=An(r.inputSchema);return o?Vl(o,{strictUnions:!0,pipeStrategy:"input"}):eC})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=An(r.outputSchema);o&&(n.outputSchema=Vl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ln,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(this._maxToolInputElements!==void 0&&YI(r,this._maxToolInputElements)>this._maxToolInputElements)throw new I(A.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=An(e.inputSchema)??e.inputSchema,i=await ii(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",c=ai(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=An(e.outputSchema),s=await ii(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ai(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(Er(Ii)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ii,async e=>{switch(e.params.ref.type){case"ref/prompt":return pg(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return mg(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 ks;let s=hr(n.argsSchema)?.[e.params.argument.name];if(!Kf(s))return ks;let i=Q0(s);if(!i)return ks;let a=await i(e.params.argument.value,e.params.context);return tv(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 ks;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 ks;let s=await o(e.params.argument.value,e.params.context);return tv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Er(ki)),this.server.assertCanSetRequestHandler(Er(Si)),this.server.assertCanSetRequestHandler(Er(Ti)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ki,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(Ti,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(Er(Ei)),this.server.assertCanSetRequestHandler(Er(zi)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ei,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?tC(r.argsSchema):void 0}))})),this.server.setRequestHandler(zi,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=An(n.argsSchema),s=await ii(o,e.params.arguments??{});if(!s.success){let c="error"in s?s.error:"Unknown error",u=ai(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:on(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=on(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 Ke?c._def?.innerType:c;return Kf(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){Gf(e);let l={title:r,description:n,inputSchema:ev(o),outputSchema:ev(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"&&Gf(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=on(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=on(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(Xf(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Xf(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()}},Sa=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new wa(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},eC={type:"object",properties:{}};function rv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function nv(t){return"_def"in t||"_zod"in t||rv(t)}function Xf(t){return typeof t!="object"||t===null||nv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(rv)}function ev(t){if(t){if(Xf(t))return on(t);if(!nv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function tC(t){let e=hr(t);return e?Object.entries(e).map(([r,n])=>{let o=kh(n),s=Sh(n);return{name:r,description:o,required:!s}}):[]}function Er(t){let r=hr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=On(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function tv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ks={completion:{values:[],hasMore:!1}};import sv from"node:process";yr();var rC=10*1024*1024,Ta=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??rC}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),nC(r)}clear(){this._buffer=void 0}};function nC(t){return Zo.parse(JSON.parse(t))}function ov(t){return JSON.stringify(t)+`
|
|
58
|
+
`}var Ea=class{constructor(e=sv.stdin,r=sv.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 Ta({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=ov(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};yr();function za(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=za(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 ep(t,e){let r=t&&typeof t=="object"?t:{},n=String(r.role??"user"),o=za(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(m=>`[tool call: ${m.function?.name??m.name}] ${m.function?.arguments??JSON.stringify(m.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 Yf(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 oC(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 Qf(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 m=oC(d);s+=(s&&m.text?`
|
|
60
|
+
`:"")+m.text,i||=m.hasBinary,m.kind&&(a=m.kind),c??=m.toolName,m.call&&(u+=m.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 sC(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}:za(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 ep(r,e)}function iv(t){if(typeof t!="string")if(t!==null&&typeof t=="object")try{t=JSON.stringify(t)}catch{return Yf("")}else t=t==null?"":String(t);let e;try{e=JSON.parse(t)}catch(l){return Yf(t,l)}if(e===null||typeof e!="object")return Yf(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,m)=>Qf(d,m))}:{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,m)=>ep(d,m))}}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 m=typeof d=="string"?{text:d,hasBinary:!1}:Qf(d,-1);l.push({index:-1,role:"system",kind:"system",text:m.text,hasBinary:m.hasBinary})}return l.push(...r.contents.map((m,p)=>Qf(m,p))),{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((m,p)=>sC(m,p))),{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=za(r.system);a.push({index:-1,role:"system",kind:"system",text:l.text,hasBinary:l.hasBinary})}a.push(...s.map((l,d)=>ep(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 jC}from"node:crypto";var av=[[/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]],rq=Math.max(...av.map(([,t])=>t));function Ra(t){if(t){for(let[e,r]of av)if(e.test(t))return r}}function zr(t){return t?/claude/i.test(t)?"anthropic":/gpt|^o\d/i.test(t)?"openai":/gemini/i.test(t)?"google":"generic":"generic"}function iC(t){return t.length===0?0:(t.match(/[{}[\]()<>;:=_\/\\|"'`#$%&*+^~-]/g)?.length??0)/t.length}var Ss={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 cv(t){return iC(t)>.08}function tp(t,e){let r=Ss[zr(e)];return cv(t)?r.code:r.prose}function Rt(t,e){return typeof t!="string"&&(t=String(t??"")),t?aC(t.length,cv(t),e):0}function aC(t,e,r){if(!(t>0))return 0;let n=Ss[zr(r)];return Math.ceil(t/(e?n.code:n.prose))}var rp=4;function z(t){if(!Number.isFinite(t))return"0";if(t<0)return`-${z(-t)}`;let e=Math.round(t);if(e<1e3)return String(e);let r=Math.round(e/100);if(r<100)return`${(r/10).toFixed(1)}k`;let n=Math.round(e/1e3);if(n<1e3)return`${n}k`;let o=Math.round(e/1e5);return o<1e4?`${(o/10).toFixed(1)}M`:`${(Math.round(e/1e8)/10).toFixed(1)}B`}var ie=(t,e,r)=>({inputPerM:t,outputPerM:e,cacheReadPerM:r});function Ne(t,e,r){return r===void 0?new RegExp(`claude-(?:${t})-${e}(?![.\\d]|-\\d{1,2}(?!\\d))`,"i"):new RegExp(`claude-(?:${t})-${e}[-.]${r}(?!\\d)`,"i")}var Pa=[/claude.*fable|claude.*mythos/i,/claude.*opus/i,/claude.*sonnet/i,/claude.*haiku/i],cC=[[Ne("fable|mythos",5,1),ie(10,50,.25)],[Ne("fable|mythos",5),ie(10,50,1)],[Ne("opus",5,5),ie(4,20,.2)],[Ne("opus",5),ie(5,25,.5)],[Ne("opus",4,8),ie(5,25,.5)],[Ne("opus",4,7),ie(5,25,.5)],[Ne("opus",4,6),ie(5,25,.5)],[Ne("opus",4,5),ie(5,25,.5)],[Ne("opus",4,1),ie(15,75,1.5)],[Ne("opus",4),ie(15,75,1.5)],[/claude-3-opus/i,ie(15,75,1.5)],[Ne("sonnet",5,5),ie(2,10,.2)],[Ne("sonnet",5),ie(2,10,.2)],[Ne("haiku",5,5),ie(.1,.5,.01)],[Ne("haiku",4,5),ie(1,5,.1)],[/claude-3-5-haiku/i,ie(.8,4,.08)],[/claude-3-haiku/i,ie(.25,1.25,.03)],[Ne("sonnet",4,6),ie(3,15,.3)],[Ne("sonnet",4,5),ie(3,15,.3)],[Ne("sonnet",4),ie(3,15,.3)],[/claude-3-[57]-sonnet/i,ie(3,15,.3)],[Pa[0],ie(10,50,1)],[Pa[1],ie(5,25,.5)],[Pa[2],ie(3,15,.3)],[Pa[3],ie(1,5,.1)],[/gpt-5.*(mini|nano)/i,{inputPerM:.25,outputPerM:2,cacheReadPerM:.025}],[/gpt-5/i,{inputPerM:1.25,outputPerM:10,cacheReadPerM:.125}],[/gpt-4o-mini/i,{inputPerM:.15,outputPerM:.6,cacheReadPerM:.075}],[/gpt-4o|gpt-4\.1/i,{inputPerM:2.5,outputPerM:10,cacheReadPerM:1.25}],[/gpt-4-turbo/i,{inputPerM:10,outputPerM:30,cacheReadPerM:10}],[/o[13](-|$)/i,{inputPerM:2,outputPerM:8,cacheReadPerM:1}],[/gemini-3[.\d]*-flash-lite/i,ie(.3,2.5,.03)],[/gemini-3\.1-flash-lite/i,ie(.25,1.5,.025)],[/gemini-3-flash/i,ie(.5,3,.05)],[/gemini-3[.\d]*-flash/i,ie(.75,3.75,.075)],[/gemini-3[.\d]*-pro/i,ie(2,12,.2)],[/gemini.*flash/i,{inputPerM:.1,outputPerM:.4,cacheReadPerM:.025}],[/gemini.*pro/i,{inputPerM:1.25,outputPerM:5,cacheReadPerM:.31}]];function so(t){if(t){for(let[e,r]of cC)if(e.test(t))return r}}function Rr(t,e){return t/1e6*e.inputPerM}function np(t){return t/25e3}function Ut(t){return Number.isFinite(t)?t>=1?`$${t.toFixed(2)}`:t>=.01?`$${t.toFixed(3)}`:`$${t.toFixed(4)}`:"$0.00"}var uv=/(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g,uC="[context-doctor: base64 blob removed \u2014 use file/image APIs instead]";function lv(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 io(t){for(let e of t.matchAll(uv))if(lv(e[0]))return!0;return!1}function op(t){return t.replace(uv,e=>lv(e)?uC:e)}import{mkdirSync as hq,readFileSync as zC,writeFileSync as gq}from"node:fs";import{dirname as RC,join as PC}from"node:path";import{appendFileSync as pC,existsSync as sp,mkdirSync as mC,readFileSync as hC,statSync as gC,writeFileSync as yC}from"node:fs";import{homedir as fv}from"node:os";import{dirname as mv,join as co}from"node:path";import{homedir as dv}from"node:os";import{join as lC,resolve as dC}from"node:path";function fC(t,e){if(t!==void 0&&t!==dv())return;let r=e.CLAUDE_CONFIG_DIR?.trim();return r?dC(r):void 0}function ao(t,e=process.env){return fC(t,e)??lC(t??dv(),".claude")}var _C={optimizeSaved:0,optimizeUsd:0,proxySaved:0,proxyUsd:0,proxyRequests:0,checks:0,warnings:0,shrinkage:0};function vC(t){let e={..._C},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 xC(){let t=process.env.XDG_STATE_HOME?.trim();return t?co(t,"context-doctor"):process.platform==="win32"?co(process.env.LOCALAPPDATA?.trim()||co(fv(),"AppData","Local"),"context-doctor"):co(fv(),".local","state","context-doctor")}function bC(){let t=xC();if(sp(t))return t;let e=ao();return sp(e)?e:t}function ip(){return process.env.CONTEXT_DOCTOR_HOOK_STATE??co(bC(),".context-doctor-hook-state.json")}function wC(){return co(mv(ip()),".context-doctor-ledger.jsonl")}var pv=100,$C=256*1024,kC=128*1024,SC=500,TC=4*1024;function EC(t){if(typeof t!="string")return;let e=t.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return e.length>pv?e.slice(0,pv):e}function Ia(t){let e=wC();try{if(mC(mv(e),{recursive:!0}),sp(e)&&gC(e).size>$C){let n=hC(e,"utf8").trimEnd().split(`
|
|
62
|
+
`),o=d=>{try{return[JSON.parse(d)]}catch{return[]}},s=new Set,i=0;for(let d=n.length-1;d>=0&&s.size<SC;d--){let m=Buffer.byteLength(n[d])+1;if(!(m>TC)){if(i+m>kC)break;s.add(d),i+=m}}let a=n.filter((d,m)=>s.has(m)),c=n.filter((d,m)=>!s.has(m)).flatMap(o),u=vC(c),l={ts:Date.now(),ev:"rollup",carried:u};yC(e,[JSON.stringify(l),...a].join(`
|
|
63
63
|
`)+`
|
|
64
|
-
`)}let r={...t};for(let n of["model","sid","cv","app"])if(n in r){let o=
|
|
65
|
-
`)}catch{}}var SC=2,TC=.5,EC=2;function zC(){return kC($C(rp()),".context-doctor-calibration.json")}function RC(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 PC(){try{return JSON.parse(wC(zC(),"utf8"))}catch{return{}}}function dv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=PC()[RC(t)];if(!e||e.v!==SC||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<TC||r>EC?{factor:1,samples:0}:{factor:r,samples:e.samples}}function CC(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 AC(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 OC(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function fv(t){return IC("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function NC(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 MC(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=NC(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var pv=.6;function jC(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 mv=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function ZC(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function DC(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;mv.lastIndex=0;for(let n of e.matchAll(mv)){let o=n[2].replace(/\\+$/,"");ZC(o)&&r.add(o)}return[...r]}function hv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=dv(r),o=t.messages.map(y=>({msg:y,tokens:Math.round(zt(y.text,r)*n.factor)+Qf})),s=o.reduce((y,x)=>y+x.tokens,0),i={system:0,user:0,assistant:0,tool_calls:0,tool_results:0,other:0};for(let y of o)i[CC(y.msg)]+=y.tokens;let a=[];for(let y of o)y.msg.kind==="tool_result"&&y.tokens>2e3&&a.push({id:"large_tool_result",severity:y.tokens>8e3?"high":"warn",estSavings:Math.round(y.tokens*.8),message:`Tool result at message #${y.msg.index}${y.msg.toolName?` (${y.msg.toolName})`:""} is ~${z(y.tokens)} tokens.`,suggestion:"Truncate or summarize large tool outputs before they enter history; keep only the fields the model actually used.",messages:[y.msg.index]});for(let y of o)y.msg.kind==="tool_call"&&y.tokens>2e3&&a.push({id:"large_tool_call",severity:y.tokens>8e3?"high":"warn",estSavings:Math.round(y.tokens*.8),message:`Tool call at message #${y.msg.index}${y.msg.toolName?` (${y.msg.toolName})`:""} carries ~${z(y.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:[y.msg.index]});let c=new Map;for(let y of o){if(y.msg.text.length<300)continue;let x=fv(y.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:y.tokens-Qf,message:`Message #${y.msg.index} duplicates the content of message #${$} (~${z(y.tokens)} tokens).`,suggestion:"Replace repeated content with a short reference to the first occurrence.",messages:[$,y.msg.index]}):c.set(x,y.msg.index)}{let y=o.filter(F=>F.msg.text.length>=300).sort((F,_e)=>_e.tokens-F.tokens).slice(0,150),x=y.map(F=>MC(F.msg.text)),$=x.map(F=>F.size),O=new Set(a.filter(F=>F.id==="duplicate_content").flatMap(F=>F.messages)),C=y.map((F,_e)=>_e),ae=F=>{for(;C[F]!==F;)F=C[F]=C[C[F]];return F},ce=y.map(()=>({sim:0,partnerTokens:0}));for(let F=0;F<y.length;F++)for(let _e=F+1;_e<y.length;_e++){let Rt=y[F],Ar=y[_e];if(O.has(Rt.msg.index)&&O.has(Ar.msg.index))continue;let Is=Math.min($[F],$[_e]),vn=Math.max($[F],$[_e]);if(vn===0||Is/vn<pv)continue;let yt=jC(x[F],x[_e]);yt<pv||(C[ae(F)]=ae(_e),yt>ce[F].sim&&(ce[F]={sim:yt,partnerTokens:Ar.tokens}),yt>ce[_e].sim&&(ce[_e]={sim:yt,partnerTokens:Rt.tokens}))}let Ee=new Map;y.forEach((F,_e)=>{if(ce[_e].sim===0)return;let Rt=ae(_e);Ee.set(Rt,[...Ee.get(Rt)??[],_e])});for(let F of Ee.values()){if(F.length<2)continue;F.sort((_t,Or)=>y[_t].msg.index-y[Or].msg.index);let _e=F.slice(1),Rt=_e.reduce((_t,Or)=>_t+Math.round(Math.min(y[Or].tokens,ce[Or].partnerTokens)*ce[Or].sim*.9),0),Ar=F.map(_t=>ce[_t].sim),Is=Math.round(Math.min(...Ar)*100),vn=Math.round(Math.max(...Ar)*100),yt=F.map(_t=>y[_t].msg.index),qp=Is===vn?`~${vn}%`:`${Is}-${vn}%`,kb=_e.reduce((_t,Or)=>_t+y[Or].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:Rt,message:F.length===2?`Messages #${yt[0]} and #${yt[1]} are ${qp} similar (~${z(Math.min(y[F[0]].tokens,y[F[1]].tokens))} tokens repeated with different framing).`:`${F.length} messages are ${qp} similar to each other (${yt.slice(0,6).map(_t=>`#${_t}`).join(", ")}${yt.length>6?", \u2026":""}): ~${z(kb)} 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:yt})}}let u=new Map;for(let y of o){if(y.msg.kind!=="tool_call"||!y.msg.toolCallText)continue;let x=fv(y.msg.toolCallText),$=u.get(x)??[];$.push(y.msg.index),u.set(x,$)}let l=y=>o.find(x=>x.msg.index>y&&x.msg.kind==="tool_result")?.msg;for(let[,y]of u){if(y.length<2)continue;let x=y.slice(1).filter((O,C)=>l(y[C])?.isError===!0).length,$=y.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 #${y.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:y}),$>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 #${y.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:y})}{let y=new Map;for(let x of o)if(!(x.msg.kind!=="tool_call"||!x.msg.toolCallText))for(let $ of DC(x.msg.toolName,x.msg.toolCallText))y.set($,[...y.get($)??[],x.msg.index]);for(let[x,$]of y){if($.length<3)continue;let O=o.filter(ae=>ae.msg.kind==="tool_result"&&$.some(ce=>ae.msg.index===ce+1)).reduce((ae,ce)=>ae+ce.tokens,0),C=Math.round(O*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:C>4e3?"high":"warn",estSavings:C,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 y of o)y.msg.kind!=="tool_result"||y.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(y.msg.text)||a.push({id:"retained_error_output",severity:"warn",estSavings:Math.round(y.tokens*.85),message:`Message #${y.msg.index} holds ~${z(y.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:[y.msg.index]});for(let y of o)so(y.msg.text)&&a.push({id:"base64_blob",severity:"high",estSavings:Math.round(y.tokens*.9),message:`Message #${y.msg.index} contains a base64/binary blob (~${z(y.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:[y.msg.index]});let d=t.messages.filter(y=>y.kind==="user"||y.kind==="assistant").length;if(d>40){let x=o.slice(0,Math.floor(o.length/2)).reduce(($,O)=>$+O.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${z(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 ~${z(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:[]}),(Er(e)==="anthropic"||Er(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(y=>({index:y.msg.index,role:y.msg.role,kind:y.msg.kind,tokens:y.tokens,preview:OC(y.msg.text),toolName:y.msg.toolName})).sort((y,x)=>x.tokens-y.tokens).slice(0,5),g={high:0,warn:1,info:2};a.sort((y,x)=>g[y.severity]-g[x.severity]||x.estSavings-y.estSavings);let h=AC(a,s),_=oo(e),v;if(_){let y=zr(s,_),x=zr(h,_);v={perCallUsd:y,per1kCallsUsd:y*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:ep(s),ttftSavedSeconds:ep(h)}}return{totalTokens:s,model:e,contextWindow:m,usagePct:p,messageCount:t.messages.length,categories:i,largestMessages:f,findings:a,totalEstSavings:h,cost:v,sourceFormat:t.sourceFormat,calibration:n.samples>0?n:void 0,parseWarning:t.parseWarning}}import{createHash as LC}from"node:crypto";var _v=10,Pa={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:_v};function qC(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 UC(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 gv(t,e,r){let n=Math.round(e*Yf("",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
|
|
67
|
-
`):JSON.stringify(t)}function
|
|
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
|
|
69
|
-
\u2026[context-doctor: trimmed ${s} chars of stale tool output]`}function
|
|
70
|
-
`);let y={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(p,h-p,y),d.push({strategy:"prune-history",messageIndex:p,tokensSaved:v-a(y.content),note:`Pruned ${_.length} old messages`})}}let g=c+o.reduce((h,_)=>h+u(_),0);return{conversation:n,tokensBefore:l,tokensAfter:g,applied:d,prunedDigest:m}}var
|
|
71
|
-
`)}var
|
|
72
|
-
`)):(e.push(""),e.push(`Findings (recoverable ~${z(t.totalEstSavings)} tokens, but only in a new chat: a chat app's history cannot be edited):`),t.findings.forEach((o,s)=>{let i=o.estSavings>0?` [~${z(o.estSavings)}]`:"";e.push(`${s+1}. ${o.severity.toUpperCase()}${i} ${o.message}`),e.push(` \u2192 ${o.action}`)}),e.push(""),e.push("Act on #1 in your reply (do it, do not just suggest it): work from your summary and refer to blocks by name from now on, which stops this chat growing; tell the user in one line what you summarized. What is already here stays until a new chat."),!t.findings.some(o=>o.id==="long_history")&&t.totalEstSavings>=
|
|
73
|
-
`))}function
|
|
64
|
+
`)}let r={...t};for(let n of["model","sid","cv","app"])if(n in r){let o=EC(r[n]);o===void 0?delete r[n]:r[n]=o}pC(e,JSON.stringify({ts:Date.now(),...r})+`
|
|
65
|
+
`)}catch{}}var IC=2,CC=.5,AC=2;function OC(){return PC(RC(ip()),".context-doctor-calibration.json")}function NC(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 MC(){try{return JSON.parse(zC(OC(),"utf8"))}catch{return{}}}function hv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=MC()[NC(t)];if(!e||e.v!==IC||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<CC||r>AC?{factor:1,samples:0}:{factor:r,samples:e.samples}}function ZC(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 DC(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 LC(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function gv(t){return jC("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function qC(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 UC(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=qC(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var yv=.6;function FC(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 HC(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function BC(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(/\\+$/,"");HC(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(y=>({msg:y,tokens:Math.round(Rt(y.text,r)*n.factor)+rp})),s=o.reduce((y,x)=>y+x.tokens,0),i={system:0,user:0,assistant:0,tool_calls:0,tool_results:0,other:0};for(let y of o)i[ZC(y.msg)]+=y.tokens;let a=[];for(let y of o)y.msg.kind==="tool_result"&&y.tokens>2e3&&a.push({id:"large_tool_result",severity:y.tokens>8e3?"high":"warn",estSavings:Math.round(y.tokens*.8),message:`Tool result at message #${y.msg.index}${y.msg.toolName?` (${y.msg.toolName})`:""} is ~${z(y.tokens)} tokens.`,suggestion:"Truncate or summarize large tool outputs before they enter history; keep only the fields the model actually used.",messages:[y.msg.index]});for(let y of o)y.msg.kind==="tool_call"&&y.tokens>2e3&&a.push({id:"large_tool_call",severity:y.tokens>8e3?"high":"warn",estSavings:Math.round(y.tokens*.8),message:`Tool call at message #${y.msg.index}${y.msg.toolName?` (${y.msg.toolName})`:""} carries ~${z(y.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:[y.msg.index]});let c=new Map;for(let y of o){if(y.msg.text.length<300)continue;let x=gv(y.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:y.tokens-rp,message:`Message #${y.msg.index} duplicates the content of message #${$} (~${z(y.tokens)} tokens).`,suggestion:"Replace repeated content with a short reference to the first occurrence.",messages:[$,y.msg.index]}):c.set(x,y.msg.index)}{let y=o.filter(F=>F.msg.text.length>=300).sort((F,_e)=>_e.tokens-F.tokens).slice(0,150),x=y.map(F=>UC(F.msg.text)),$=x.map(F=>F.size),O=new Set(a.filter(F=>F.id==="duplicate_content").flatMap(F=>F.messages)),C=y.map((F,_e)=>_e),ae=F=>{for(;C[F]!==F;)F=C[F]=C[C[F]];return F},ce=y.map(()=>({sim:0,partnerTokens:0}));for(let F=0;F<y.length;F++)for(let _e=F+1;_e<y.length;_e++){let Pt=y[F],Or=y[_e];if(O.has(Pt.msg.index)&&O.has(Or.msg.index))continue;let As=Math.min($[F],$[_e]),xn=Math.max($[F],$[_e]);if(xn===0||As/xn<yv)continue;let _t=FC(x[F],x[_e]);_t<yv||(C[ae(F)]=ae(_e),_t>ce[F].sim&&(ce[F]={sim:_t,partnerTokens:Or.tokens}),_t>ce[_e].sim&&(ce[_e]={sim:_t,partnerTokens:Pt.tokens}))}let Ee=new Map;y.forEach((F,_e)=>{if(ce[_e].sim===0)return;let Pt=ae(_e);Ee.set(Pt,[...Ee.get(Pt)??[],_e])});for(let F of Ee.values()){if(F.length<2)continue;F.sort((vt,Nr)=>y[vt].msg.index-y[Nr].msg.index);let _e=F.slice(1),Pt=_e.reduce((vt,Nr)=>vt+Math.round(Math.min(y[Nr].tokens,ce[Nr].partnerTokens)*ce[Nr].sim*.9),0),Or=F.map(vt=>ce[vt].sim),As=Math.round(Math.min(...Or)*100),xn=Math.round(Math.max(...Or)*100),_t=F.map(vt=>y[vt].msg.index),Bp=As===xn?`~${xn}%`:`${As}-${xn}%`,Rb=_e.reduce((vt,Nr)=>vt+y[Nr].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:Pt,message:F.length===2?`Messages #${_t[0]} and #${_t[1]} are ${Bp} similar (~${z(Math.min(y[F[0]].tokens,y[F[1]].tokens))} tokens repeated with different framing).`:`${F.length} messages are ${Bp} similar to each other (${_t.slice(0,6).map(vt=>`#${vt}`).join(", ")}${_t.length>6?", \u2026":""}): ~${z(Rb)} 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:_t})}}let u=new Map;for(let y of o){if(y.msg.kind!=="tool_call"||!y.msg.toolCallText)continue;let x=gv(y.msg.toolCallText),$=u.get(x)??[];$.push(y.msg.index),u.set(x,$)}let l=y=>o.find(x=>x.msg.index>y&&x.msg.kind==="tool_result")?.msg;for(let[,y]of u){if(y.length<2)continue;let x=y.slice(1).filter((O,C)=>l(y[C])?.isError===!0).length,$=y.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 #${y.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:y}),$>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 #${y.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:y})}{let y=new Map;for(let x of o)if(!(x.msg.kind!=="tool_call"||!x.msg.toolCallText))for(let $ of BC(x.msg.toolName,x.msg.toolCallText))y.set($,[...y.get($)??[],x.msg.index]);for(let[x,$]of y){if($.length<3)continue;let O=o.filter(ae=>ae.msg.kind==="tool_result"&&$.some(ce=>ae.msg.index===ce+1)).reduce((ae,ce)=>ae+ce.tokens,0),C=Math.round(O*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:C>4e3?"high":"warn",estSavings:C,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 y of o)y.msg.kind!=="tool_result"||y.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(y.msg.text)||a.push({id:"retained_error_output",severity:"warn",estSavings:Math.round(y.tokens*.85),message:`Message #${y.msg.index} holds ~${z(y.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:[y.msg.index]});for(let y of o)io(y.msg.text)&&a.push({id:"base64_blob",severity:"high",estSavings:Math.round(y.tokens*.9),message:`Message #${y.msg.index} contains a base64/binary blob (~${z(y.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:[y.msg.index]});let d=t.messages.filter(y=>y.kind==="user"||y.kind==="assistant").length;if(d>40){let x=o.slice(0,Math.floor(o.length/2)).reduce(($,O)=>$+O.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${z(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 ~${z(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:[]}),(zr(e)==="anthropic"||zr(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=Ra(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(y=>({index:y.msg.index,role:y.msg.role,kind:y.msg.kind,tokens:y.tokens,preview:LC(y.msg.text),toolName:y.msg.toolName})).sort((y,x)=>x.tokens-y.tokens).slice(0,5),g={high:0,warn:1,info:2};a.sort((y,x)=>g[y.severity]-g[x.severity]||x.estSavings-y.estSavings);let h=DC(a,s),_=so(e),v;if(_){let y=Rr(s,_),x=Rr(h,_);v={perCallUsd:y,per1kCallsUsd:y*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:np(s),ttftSavedSeconds:np(h)}}return{totalTokens:s,model:e,contextWindow:m,usagePct:p,messageCount:t.messages.length,categories:i,largestMessages:f,findings:a,totalEstSavings:h,cost:v,sourceFormat:t.sourceFormat,calibration:n.samples>0?n:void 0,parseWarning:t.parseWarning}}import{createHash as VC}from"node:crypto";var wv=10,Ca={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:wv};function JC(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 WC(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*tp("",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 ap(t,e,r=wv){let n=t-e;return n<=0?0:n<r?n:Math.floor(n/r)*r}function KC(t){return VC("sha1").update(t.trim()).digest("hex")}function uo(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"?uo(e.content):e?.type==="tool_use"?JSON.stringify(e.input??{}):"").join(`
|
|
67
|
+
`):JSON.stringify(t)}function cp(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 up(t){return typeof t=="string"?io(t)?op(t):t:Array.isArray(t)?t.map(up):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,up(r)])):t}function GC(t,e,r){let n=Math.round(e*tp(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 XC(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??Ca.strategies,keepRecent:e.keepRecent??Ca.keepRecent,maxToolResultTokens:e.maxToolResultTokens??Ca.maxToolResultTokens,trimBoundaryStep:e.trimBoundaryStep&&e.trimBoundaryStep>0?Math.floor(e.trimBoundaryStep):Ca.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 h=o.length-1;h>=0;h--)(!o[h]||typeof o[h]!="object")&&o.splice(h,1);let s=!Array.isArray(n)&&n?.system!=null||o.some(h=>Array.isArray(h?.content)&&h.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=h=>Rt(h,i),c=Array.isArray(n)?0:(n?.system!=null?a(typeof n.system=="string"?n.system:uo(n.system)):0)+(n?.tools!=null?a(JSON.stringify(n.tools)):0),u=h=>{let _=a(uo(h.content));for(let v of Array.isArray(h.tool_calls)?h.tool_calls:[]){let y=v?.function;y&&(_+=a(`${y.name??""} ${typeof y.arguments=="string"?y.arguments:JSON.stringify(y.arguments??{})}`))}return h.function_call&&(_+=a(`${h.function_call.name??""} ${h.function_call.arguments??""}`)),_},l=c+o.reduce((h,_)=>h+u(_),0),d=[];if(r.strategies.includes("strip-base64")&&o.forEach((h,_)=>{let v=uo(h.content);if(!io(v))return;let y=a(v),x=cp(h,O=>io(O)?op(O):O);Array.isArray(x)&&(x=x.map(O=>O?.type==="tool_use"&&O.input!=null?{...O,input:up(O.input)}:O));let $=y-a(uo(x));$>50&&(h.content=x,d.push({strategy:"strip-base64",messageIndex:_,tokensSaved:$,note:"Removed inline base64 data"}))}),r.strategies.includes("dedupe")){let h=ap(o.length,r.keepRecent,r.trimBoundaryStep),_=new Map;o.forEach((v,y)=>{let x=0,$,O=cp(v,C=>{if(C.length<300)return C;let ae=KC(C),ce=_.get(ae);if(ce===void 0)return _.set(ae,y),C;if(y>=h)return C;let Ee=`[context-doctor: identical to message #${ce} \u2014 content removed]`;return x+=a(C)-a(Ee),$??=ce,Ee});x<=0||(v.content=O,d.push({strategy:"dedupe",messageIndex:y,tokensSaved:x,note:`Duplicate of message #${$}`}))})}if(r.strategies.includes("trim-tool-results")){let h=ap(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=h||!bv(_))return;let y=0,x=cp(_,($,O)=>{if(O!=="tool_result")return $;let C=a($);if(C<=r.maxToolResultTokens)return $;let ae=GC($,r.maxToolResultTokens,i),ce=a(ae);return ce>=C?$:(y+=C-ce,ae)});y<=0||(_.content=x,d.push({strategy:"trim-tool-results",messageIndex:v,tokensSaved:y,note:"Stale tool result truncated"}))})}if(r.strategies.includes("trim-tool-calls")){let h=ap(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=h)return;let y=0;if(Array.isArray(_.content))for(let x of _.content){if(x?.type!=="tool_use"||x.input==null||typeof x.input!="object"||WC(o,v,JC(x)))continue;let $=a(JSON.stringify(x.input));if($<=r.maxToolResultTokens)continue;let O=xv(x.input,r.maxToolResultTokens,i),C=a(JSON.stringify(O));C>=$||(x.input=O,y+=$-C)}for(let x of _.tool_calls??[]){let $=x?.function?.arguments;if(typeof $!="string")continue;let O=a($);if(O<=r.maxToolResultTokens)continue;let C;try{C=JSON.parse($)}catch{continue}if(!C||typeof C!="object"||Array.isArray(C))continue;let ae=JSON.stringify(xv(C,r.maxToolResultTokens,i)),ce=a(ae);ce>=O||(x.function.arguments=ae,y+=O-ce)}y>0&&d.push({strategy:"trim-tool-calls",messageIndex:v,tokensSaved:y,note:"Arguments of a completed tool call truncated"})})}let m,p=0;for(;p<o.length&&(o[p]?.role==="system"||o[p]?.role==="developer");)p++;let f=Math.max(2,r.keepRecent);if(r.strategies.includes("prune-history")&&o.length-p>f*2){let h=o.length-f;for(;h<o.length&&bv(o[h]);)h++;if(o.length-h>=2){XC(o.slice(h));let _=o.slice(p,h),v=_.reduce((x,$)=>x+u($),0);m=_.map((x,$)=>`[${p+$}:${x.role}] ${uo(x.content).replace(/\s+/g," ").slice(0,200)}`).join(`
|
|
70
|
+
`);let y={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(p,h-p,y),d.push({strategy:"prune-history",messageIndex:p,tokensSaved:v-a(y.content),note:`Pruned ${_.length} old messages`})}}let g=c+o.reduce((h,_)=>h+u(_),0);return{conversation:n,tokensBefore:l,tokensAfter:g,applied:d,prunedDigest:m}}var kv={system:"System prompt",user:"User messages",assistant:"Assistant replies",tool_calls:"Tool calls",tool_results:"Tool results",other:"Other"},YC={high:"\u2716",warn:"\u25B2",info:"\u2139"};function QC(t,e=28){let r=Math.round(t*e);return"\u2588".repeat(r)+"\u2591".repeat(e-r)}function eA(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: ~${z(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 ${z(n.contextWindow)} window (${n.usagePct.toFixed(1)}%)`:" (unknown window size)";r.push(`Model: ${n.model}${i}`)}n.cost&&r.push(`Cost: ~${Ut(n.cost.perCallUsd)} input per call \xB7 ~${Ut(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)} ${QC(c)} ${String(Math.round(c*100)).padStart(3)}% ~${z(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}] ~${z(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 p=c.get(u.id)??{count:0,savings:0};c.set(u.id,{count:p.count+1,savings:p.savings+u.estSavings});continue}a.set(u.id,l+1);let d=u.estSavings>0?` [save ~${z(u.estSavings)}]`:"";r.push(`${YC[u.severity]} ${e.redact?eA(u.message):u.message}${d}`),r.push(` \u2192 ${u.suggestion}`);let m=c.get(u.id);l+1===i&&m===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),m=d>0?`, up to ~${z(d)} more recoverable`:"";r.push(` \u2026 and ${l.count} more of the same kind (${u})${m}. 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: ~${z(n.totalEstSavings)} tokens (~${u}% of context)`;n.cost&&n.cost.savingsPerCallUsd>0&&(l+=` \u2248 ${Ut(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 tA=2060,rA={code:42,tool_result:56,paste:56,text:80,base64:76,image:0},nA=6.3,oA={paste:2400,code:2400,tool_result:2400,text:900,base64:12e3,image:0},sA=1500,Tv=2e3,iA=30,lp=400,aA=1e4,cA=6;function uA(t,e){let r=Ss[zr(e)];return t==="code"||t==="tool_result"||t==="base64"?r.code:r.prose}function lA(t,e){if(t.kind==="image")return t.approx_tokens&&t.approx_tokens>0?Math.round(t.approx_tokens):sA;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*rA[t.kind]:t.approx_words&&t.approx_words>0?t.approx_words*nA:oA[t.kind];return Math.round(r/uA(t.kind,e))}function dp(t){return Math.round(tA/Ss[zr(t)].prose)}var Ev=60;function dA(t){let e=String(t??"").replace(/\s+/g," ").trim()||"unnamed block";return e.length>Ev?e.slice(0,Ev-1)+"\u2026":e}function fA(t){let e=Math.max(0,Math.floor(t.turns||0)),r=(Array.isArray(t.blocks)?t.blocks:[]).map(_=>({..._,label:dA(_?.label)})),n=dp(t.model),o=e*n,s=r.map(_=>({block:_,tokens:lA(_,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:y}of s){if(y>1&&c.push({id:"duplicate_block",severity:"warn",estSavings:v*(y-1),message:`"${_.label}" appears ${y} times (~${z(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 (~${z(v)}), which the model cannot read anyway.`,action:`Drop it: describe "${_.label}" in one line and ask the user to attach it as a file if needed.`});continue}if(_.kind!=="image"&&v>=Tv){let x=_.stale?Math.max(0,v-100):Math.round(v*.7);c.push({id:"large_block",severity:v>=4*Tv?"high":"warn",estSavings:x,message:`"${_.label}" (turn ${_.turn}, ${_.kind}) is ~${z(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,y)=>v+y.tokens*y.copies,0);c.push({id:"many_images",severity:"info",estSavings:0,message:`${u.length} images (~${z(_)}) 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>=iA){let _=cA*n+lp;c.push({id:"long_history",severity:a>1e5?"high":"warn",estSavings:Math.max(0,a-_),message:`${e} turns: every new message re-reads ~${z(a)}.`,action:`Offer a handoff once: with the user's agreement, write a \u2264${lp}-token brief (goal, decisions, current state, open items, key identifiers) and call save_handoff, or the user picks the \`handoff\` prompt. A new chat re-reads ~${z(_)} of conversation instead, plus the app's own system prompt, which every chat carries.`})}let l=Ra(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 ${z(l)} window. Quality drops and the app may start dropping early turns.`,action:"Do the handoff now rather than at the next problem."});let m={high:0,warn:1,info:2};c.sort((_,v)=>m[_.severity]-m[v.severity]||v.estSavings-_.estSavings);let p=c.find(_=>_.id==="long_history")?.estSavings??0,f=c.filter(_=>_.id!=="long_history").reduce((_,v)=>_+v.estSavings,0),g=Math.min(a,Math.max(p,f)),h=so(t.model);return{totalTokens:a,baselineTokens:o,blockTokens:i,turns:e,model:t.model,contextWindow:l,usagePct:d,findings:c,totalEstSavings:g,perTurnUsd:h?Rr(a,h):void 0,perTurnCachedUsd:h?a/1e6*h.cacheReadPerM:void 0}}function zv(t){let e=[],r=t.usagePct!==void 0?` (~${t.usagePct}% of ${z(t.contextWindow)})`:"";return e.push(`Context estimate from sketch: ~${z(t.totalTokens)} tokens${r}, ${t.turns} turns.`),e.push(` ${z(t.baselineTokens)} plain conversation + ${z(t.blockTokens)} in pastes, tool output and images. Estimate, usually within \xB120%.`),t.perTurnUsd!==void 0?e.push(` Re-read on every turn: ${Ut(t.perTurnUsd)} at list price, ${Ut(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 ~${z(t.totalEstSavings)} tokens, but only in a new chat: a chat app's history cannot be edited):`),t.findings.forEach((o,s)=>{let i=o.estSavings>0?` [~${z(o.estSavings)}]`:"";e.push(`${s+1}. ${o.severity.toUpperCase()}${i} ${o.message}`),e.push(` \u2192 ${o.action}`)}),e.push(""),e.push("Act on #1 in your reply (do it, do not just suggest it): work from your summary and refer to blocks by name from now on, which stops this chat growing; tell the user in one line what you summarized. What is already here stays until a new chat."),!t.findings.some(o=>o.id==="long_history")&&t.totalEstSavings>=aA&&e.push(`To recover the ~${z(t.totalEstSavings)}: offer a handoff once. With the user's agreement, call save_handoff (a \u2264${lp}-token brief plus the blocks that must stay exact); a new chat starts from that.`),e.join(`
|
|
73
|
+
`))}function Rv(t,{record:e=!0}={}){let r=fA(t);return e&&Ia({ev:"check",src:"mcp",tok:r.totalTokens,warn:r.findings.some(n=>n.severity!=="info"),model:t.model}),r}import{spawnSync as Kv}from"node:child_process";import{existsSync as Gv,lstatSync as RA,readdirSync as PA,readFileSync as IA,realpathSync as _p,statSync as CA}from"node:fs";import{homedir as AA}from"node:os";import{basename as vp,extname as Da,isAbsolute as OA,join as lo,relative as Xv,resolve as NA,sep as MA}from"node:path";import{execFile as pA,spawnSync as Pv}from"node:child_process";import{existsSync as Iv,mkdtempSync as Cv,readFileSync as pp,rmSync as Av}from"node:fs";import{tmpdir as Ov}from"node:os";import{dirname as Nv,extname as Mv,join as Aa}from"node:path";var Oa=new Set([".pdf",".docx",".doc",".rtf",".odt",".pptx"]),jv={encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024};function Ts(t,e){try{let r=Pv(t,e,jv);return r.status===0&&typeof r.stdout=="string"&&r.stdout.trim()?r.stdout:void 0}catch{return}}var Zv=["-convert","txt","-noload","-nostore","-stdout"],Dv='ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';function mA(t){let e=Ts("pdftotext",["-enc","UTF-8",t,"-"])??Ts("pdftotext",[t,"-"]);if(e)return e;let r=Aa(Cv(Aa(Ov(),"cd-pdf-")),"out.txt");try{Pv("pdftotext",[t,r],jv);let n=Iv(r)?pp(r,"utf8"):"";return n.trim()?n:void 0}catch{return}finally{Av(Nv(r),{recursive:!0,force:!0})}}function hA(t,e){let r=Ts("unzip",["-p",t,...e]);return r?Lv(r):void 0}function Lv(t){return t.replace(/<\/(w:p|a:p|text:p|text:h)>/g,`
|
|
74
74
|
|
|
75
75
|
`).replace(/<(w:tab|w:br)\/>/g," ").replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&").replace(/\n{3,}/g,`
|
|
76
76
|
|
|
77
|
-
`).trim()}function
|
|
77
|
+
`).trim()}function qv(t){let e=Mv(t).toLowerCase(),r=process.platform==="darwin",n;if(e===".pdf"){if(n=mA(t)?.replace(/\f/g,`
|
|
78
78
|
|
|
79
|
-
`),!n&&r&&(n=
|
|
79
|
+
`),!n&&r&&(n=Ts("osascript",["-l","JavaScript","-e",Dv,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=Ts("textutil",[...Zv,t])),!n){let o=e===".docx"?["word/document.xml"]:e===".pptx"?["ppt/slides/*.xml"]:e===".odt"?["content.xml"]:[];o.length&&(n=hA(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 Es=2e4,at=()=>performance.now();function gA(t){return Math.min(t,3e4,Math.max(2e3,t/2))}function fp(t,e,r){let n=Math.ceil(r-at());if(n<=0)return Promise.resolve({timedOut:!0});let o=Math.ceil(gA(n));return new Promise(s=>{let i=!1,a=l=>{i||(i=!0,clearTimeout(u),s(l))},c,u=setTimeout(()=>{c?.kill("SIGKILL"),a({timedOut:at()>=r-50})},o);try{c=pA(t,e,{encoding:"utf8",timeout:o,killSignal:"SIGKILL",maxBuffer:64*1024*1024,windowsHide:!0},(l,d)=>{if(l)return a({timedOut:at()>=r-50});a({out:typeof d=="string"&&d.trim()?d:void 0,timedOut:!1})}),c.on("error",()=>a({timedOut:!1})),c.stdin?.on("error",()=>{}),c.stdin?.end()}catch{a({timedOut:!1})}})}async function Na(t,e=at()+Es){let r=Mv(t).toLowerCase(),n=process.platform==="darwin",o,s=!1,i=async(c,u)=>{if(o||s)return;let l=await fp(c,u,e);l.timedOut?s=!0:o=l.out},a=()=>({error:"not read: the time allowed for reading documents in this call ran out"});if(r===".pdf"){if(await i("pdftotext",["-enc","UTF-8",t,"-"]),await i("pdftotext",[t,"-"]),!o&&!s){let c=Aa(Cv(Aa(Ov(),"cd-pdf-")),"out.txt");try{(await fp("pdftotext",[t,c],e)).timedOut?s=!0:Iv(c)&&(o=pp(c,"utf8").trim()?pp(c,"utf8"):void 0)}finally{Av(Nv(c),{recursive:!0,force:!0})}}return o=o?.replace(/\f/g,`
|
|
80
80
|
|
|
81
|
-
`),!o&&n&&await i("osascript",["-l","JavaScript","-e",
|
|
81
|
+
`),!o&&n&&await i("osascript",["-l","JavaScript","-e",Dv,t]),o?{text:o}:s?a():{error:n?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}if(n&&r!==".pptx"&&await i("textutil",[...Zv,t]),!o&&!s){let c=r===".docx"?["word/document.xml"]:r===".pptx"?["ppt/slides/*.xml"]:r===".odt"?["content.xml"]:[];if(c.length){let u=await fp("unzip",["-p",t,...c],e);u.timedOut?s=!0:u.out&&(o=Lv(u.out))}}return o?{text:o}:s?a():{error:n?"unreadable document":`needs unzip${r===".doc"||r===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}var jA=4e3,ZA=400,DA="claude",LA=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"]),qA=new Set([".md",".mdx",".markdown",".rst",".adoc"]);function UA(t,e){let r=Da(t).toLowerCase();return qA.has(r)?"markdown":LA.has(r)?"code":/^#{1,6}\s+\S/m.test(e)&&!/^#!/.test(e)?"markdown":"prose"}var FA=/^(?![\s})\]]|$)/,Wv=/^(\/\*\*?|\*\/?|\/\/|#(?!include|define|!)|"""|\'\'\'|--|@\w+)/;function HA(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 m=d[1].length;n.length=m-1,n[m-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()&&FA.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(p=>p.trim()).filter(Boolean),d=l.map(p=>p.replace(Wv,"").trim()).find(Boolean),m=e==="code"&&(l.find(p=>!Wv.test(p))||d)||l[0]||"";u.heading=m.slice(0,80)}return r}var BA=t=>t>=55296&&t<=56319,VA=t=>t>=56320&&t<=57343;function Yv(t,e={}){let r=Math.max(50,e.maxChunkTokens??ZA),n=e.model??DA,o=UA(t.name,t.text),s=[],i=[],a=Math.floor(r*2.4);t.text.replace(/\r\n?/g,`
|
|
82
82
|
`).split(`
|
|
83
|
-
`).forEach((m,p)=>{for(;m.length>a;){let f=m.lastIndexOf(" ",a),g=f>a/2?f+1:a;
|
|
84
|
-
`,n));let u=(m,p)=>c[p]-c[m],l=[];for(let m of
|
|
85
|
-
`);return{id:`${t.name}#${p+1}`,source:t.name,startLine:i[f]??f+1,endLine:i[g-1]??g,heading:m.heading,text:h,tokens:
|
|
86
|
-
`);r.push(`PACKED ~${z(t.packedTokens)} of ~${z(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${z(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 ${z(t.budget)}: ${s.map(a=>`${a.id} (~${z(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 ${z(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${z(a.tokens)} tokens. Raise the budget to at least ${a.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`),r.push(...
|
|
87
|
-
`)}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(...
|
|
83
|
+
`).forEach((m,p)=>{for(;m.length>a;){let f=m.lastIndexOf(" ",a),g=f>a/2?f+1:a;BA(m.charCodeAt(g-1))&&VA(m.charCodeAt(g))&&g--,s.push(m.slice(0,g)),i.push(p+1),m=m.slice(g)}s.push(m),i.push(p+1)});let c=[0];for(let m of s)c.push(c[c.length-1]+Rt(m+`
|
|
84
|
+
`,n));let u=(m,p)=>c[p]-c[m],l=[];for(let m of HA(s,o)){if(u(m.start,m.end)<=r){l.push(m);continue}let p=m.start;for(let f=m.start+1;f<=m.end;f++)if(f===m.end||u(p,f+1)>r){let g=p===m.start;l.push({start:p,end:f,heading:g?m.heading:`${m.heading} (cont.)`,hard:g&&m.hard}),p=f}}let d=[];for(let m of l){let p=d[d.length-1];p&&!m.hard&&p.heading===m.heading&&u(p.start,m.end)<=r||p&&!m.hard&&o!=="markdown"&&u(p.start,m.end)<=r?p.end=m.end:d.push({...m})}return d.map((m,p)=>{let f=m.start,g=m.end;for(;f<g&&!s[f].trim();)f++;for(;g>f&&!s[g-1].trim();)g--;let h=s.slice(f,g).join(`
|
|
85
|
+
`);return{id:`${t.name}#${p+1}`,source:t.name,startLine:i[f]??f+1,endLine:i[g-1]??g,heading:m.heading,text:h,tokens:Rt(h,n),score:0}})}var JA=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 ja(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||JA.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 Qv(t,e){let r=[...new Set(ja(e))];if(r.length===0||t.length===0)return;let n=t.map(i=>{let a=[...ja(i.text),...ja(i.heading),...ja(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))))})}}function ex(t,e={}){let r=t.map(o=>Yv(o,e)),n=e.query?.trim()||void 0;return n&&Qv(r.flat(),n),rx(t,r,n,e)}async function tx(t,e={}){let r=t.map(s=>Yv(s,e)),n=e.query?.trim()||void 0,o;if(n&&(Qv(r.flat(),n),e.semantic)){let{semanticRerank:s}=await Promise.resolve().then(()=>(Jv(),Vv));o=(await s(r.flat(),n,{model:typeof e.semantic=="string"?e.semantic:void 0})).note}return{...rx(t,r,n,e),semanticNote:o}}function rx(t,e,r,n){let o=Math.max(1,n.budget??jA),s=e.flat(),i=[],a=[],c=[],u=0,l=(p,f)=>{if(!i.includes(p)){if(u+p.tokens>o){c.some(g=>g.id===p.id)||c.push({id:p.id,tokens:p.tokens,requested:f});return}i.push(p),u+=p.tokens}},d="outline";if(n.ids?.length){d="ids";let p=new Map(s.map(f=>[f.id,f]));for(let f of n.ids){let g=p.get(f);g?l(g,!0):a.push(f)}}if(r){d==="outline"&&(d="query");for(let p of[...s].filter(f=>f.score>0).sort((f,g)=>g.score-f.score))l(p,!1)}let m=new Map(s.map((p,f)=>[p,f]));return i.sort((p,f)=>m.get(p)-m.get(f)),{mode:d,query:r,budget:o,totalTokens:s.reduce((p,f)=>p+f.tokens,0),packedTokens:u,selected:i,chunks:s,missingIds:a,unfit:c,sources:t.map((p,f)=>({name:p.name,tokens:e[f].reduce((g,h)=>g+h.tokens,0),chunks:e[f].length,selected:e[f].filter(g=>i.includes(g)).length}))}}function gp(t,e){let r=t.slice(0,e).map(n=>` ${n.id} L${n.startLine}-${n.endLine} ~${z(n.tokens)} ${n.heading}`);return t.length>e&&r.push(` \u2026 ${t.length-e} more`),r}function nx(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}: ~${z(t.totalTokens)} tokens in ${t.chunks.length} chunks. Nothing packed: pass a query, or chunk ids from this list.`),r.push(...gp(t.chunks,e)),r.join(`
|
|
86
|
+
`);r.push(`PACKED ~${z(t.packedTokens)} of ~${z(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${z(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 ${z(t.budget)}: ${s.map(a=>`${a.id} (~${z(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 ${z(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${z(a.tokens)} tokens. Raise the budget to at least ${a.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`),r.push(...gp(t.chunks,e)),r.join(`
|
|
87
|
+
`)}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(...gp(t.chunks,e)),r.join(`
|
|
88
88
|
`);for(let a of t.selected)r.push("",`\u2500\u2500 ${a.id} \xB7 L${a.startLine}-${a.endLine}${a.heading?` \xB7 ${a.heading}`:""} \xB7 ~${z(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(`
|
|
89
|
-
`)}var
|
|
89
|
+
`)}var WA=new Set(["node_modules",".git","dist","build",".next","target","__pycache__",".venv","venv","vendor"]),Za={files:500,fileBytes:5*1024*1024,totalBytes:50*1024*1024};function KA(t){try{let e=Kv("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&&Gv(lo(t,r))).sort()}catch{return}}function GA(t){let e=Kv("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 ox(t,e){let r=Xv(t,e);return r===""||r!==".."&&!r.startsWith(".."+MA)&&!OA(r)}var XA=new Set([".npmrc",".pypirc",".netrc","_netrc",".git-credentials",".pgpass",".htpasswd"]),YA=new Set([".pem",".key",".p12",".pfx",".keystore",".jks"]);function QA(t){let e=vp(t),r=e.toLowerCase();if(r===".env"||r.startsWith(".env."))return"an .env file";if(XA.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(YA.has(Da(r)))return`a key or certificate store (${Da(r)})`;let n=t.split(/[\\/]+/);if(r==="credentials"&&n[n.length-2]===".aws")return"AWS credentials"}function eO(){let t=AA(),e=[...[".ssh",".aws",".gnupg",".kube",".docker",".azure",lo(".config","gcloud"),lo("Library","Keychains"),".password-store"].map(n=>lo(t,n)),"/etc/shadow","/etc/gshadow","/etc/sudoers","/etc/master.passwd","/etc/ssh"],r=e.map(n=>{try{return _p(n)}catch{return n}});return[...new Set([...e,...r])]}function tO(t,e){return e.find(r=>ox(r,t))}function yp(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 rO(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?[]:eO(),a=[],c=[],u=0,l=new Set,d="",m=0,p=!1,f=h=>{try{return _p(h)}catch{return NA(h)}},g=(h,_)=>{if(a.length>=Za.files){(_||c.length<20)&&c.push(`${h}: over ${Za.files} files`);return}let v;try{v=_?CA(h):RA(h)}catch(C){c.push(`${h}: ${yp(C)}`);return}if(v.isSymbolicLink()){let C;try{C=_p(h)}catch{return}ox(d,C)||c.push(`${h}: symlink pointing outside the folder (not followed)`);return}if(i.length>0){let C=tO(f(h),i);if(C){_&&c.push(`${h}: refused, ${C} holds credentials${s}`);return}}if(v.isDirectory()){let C=vp(h);if(!_&&WA.has(C))return;if(!_&&C.startsWith(".")){m++;return}let ae=_?KA(h):void 0;if(_&&(p=ae!==void 0),ae){ae.length===0&&GA(h)&&c.push(`${h}: ignored by git (.gitignore); pack reads folders as git does, so ignored files stay out. Name a file to pack it anyway`);for(let Ee of ae)g(lo(h,Ee),!1);return}let ce;try{ce=PA(h).sort()}catch(Ee){c.push(`${h}: ${yp(Ee)}`);return}for(let Ee of ce)g(lo(h,Ee),!1);return}if(!v.isFile()){_&&c.push(`${h}: not a regular file`);return}if(!o){let C=QA(h);if(C){c.push(`${h}: ${C}, likely holding secrets; not packed${s}`);return}}if(!_&&vp(h).startsWith(".")&&!p){m++;return}let y=f(h);if(l.has(y))return;if(v.size>Za.fileBytes||u+v.size>Za.totalBytes){c.push(`${h}: too large (${Math.round(v.size/1024)} KB)`);return}let x=Xv(n,h),$=x&&!x.startsWith("..")?x:h;if(Oa.has(Da(h).toLowerCase())){if(r.defer){u+=v.size,l.add(y),a.push({name:$,text:""}),r.defer.push({slot:a.length-1,path:h});return}let C=qv(h);"error"in C?c.push(`${h}: ${C.error}`):(u+=v.size,l.add(y),a.push({name:$,text:C.text}));return}let O;try{O=IA(h)}catch(C){c.push(`${h}: ${yp(C)}`);return}if(O.subarray(0,8e3).includes(0)){_&&c.push(`${h}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);return}u+=v.size,l.add(y),a.push({name:$,text:O.toString("utf8")})};for(let h of t){if(!Gv(h)){c.push(`${h}: not found`);continue}d=f(h),m=0,p=!1,g(h,!0),m>0&&c.push(`${h}: ${m} hidden file(s) or folder(s) not read (name one to pack it)`)}return{sources:a,skipped:c}}async function sx(t,e={}){let r=[],{sources:n,skipped:o}=rO(t,{...e,defer:r}),s=at()+(e.budgetMs??Es),i=new Set;for(let a of r){let c=await Na(a.path,s);"error"in c?(o.push(`${a.path}: ${c.error}`),i.add(a.slot)):n[a.slot].text=c.text}return{sources:n.filter((a,c)=>!i.has(c)),skipped:o}}var ix=`Context hygiene rules (always on):
|
|
90
90
|
1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; in a chat app pass a \`sketch\`. Act on its top finding. Do not estimate token counts yourself.
|
|
91
91
|
2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.
|
|
92
92
|
3. Summarize any paste or tool result over ~2k tokens into the points you need.
|
|
93
93
|
4. Refer to earlier content by name; never re-quote it or inline base64.
|
|
94
94
|
5. For a big file you won't edit, call pack_context with the question; don't read it whole.
|
|
95
|
-
6. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.`;var
|
|
96
|
-
`),structured:i,meta:{"context-doctor/report":e,"context-doctor/largest":t.largestMessages.map(a=>({index:a.index,kind:a.kind,tokens:
|
|
97
|
-
`),structured:s,meta:{"context-doctor/report":e}}}function
|
|
95
|
+
6. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.`;var nO=["openai/session","openai/subject"];function ax(t,e=process.env){let r=e.CONTEXT_DOCTOR_RESULTS?.trim().toLowerCase();return r==="full"||r==="compact"?r:t&&typeof t=="object"&&nO.some(n=>typeof t[n]=="string")?"compact":"full"}var fo=t=>Math.round(t);function cx(t,e){let r=t.findings[0],n=t.totalTokens>0?Math.round(t.totalEstSavings/t.totalTokens*100):0,o=[`~${z(t.totalTokens)} tokens in ${t.messageCount} messages (${t.sourceFormat})${t.usagePct!==void 0?`, ${t.usagePct.toFixed(0)}% of the window`:""}; ~${z(t.totalEstSavings)} recoverable (${n}%).`];t.parseWarning&&o.unshift(`\u26A0 ${t.parseWarning}`),o.push(r?"Act on #1 (first in structuredContent.findings).":"No findings.");let s=Object.fromEntries(Object.entries(t.categories).filter(([,a])=>a>0).sort((a,c)=>c[1]-a[1]).map(([a,c])=>[a,fo(c)])),i={total_tokens:fo(t.totalTokens),messages:t.messageCount,recoverable_tokens:fo(t.totalEstSavings),by_category:s,findings:t.findings.slice(0,6).map(a=>`${a.severity}${a.estSavings>0?` ~${z(a.estSavings)}`:""}: ${a.message} \u2192 ${a.suggestion}`)};return t.findings.length>6&&(i.more_findings=t.findings.length-6),t.model&&(i.model=t.model),t.usagePct!==void 0&&(i.window_pct=Number(t.usagePct.toFixed(1))),t.cost&&(i.usd_per_call=Number(t.cost.perCallUsd.toFixed(4))),{text:o.join(`
|
|
96
|
+
`),structured:i,meta:{"context-doctor/report":e,"context-doctor/largest":t.largestMessages.map(a=>({index:a.index,kind:a.kind,tokens:fo(a.tokens),preview:a.preview}))}}}function ux(t,e){let[r,...n]=t.findings,o=[`~${z(t.totalTokens)} tokens, ${t.turns} turns${t.usagePct!==void 0?`, ~${t.usagePct}% of the window`:""} (estimate); ~${z(t.totalEstSavings)} recoverable, only in a new chat.`];r?(o.push(`Act on #1 now: ${r.message} \u2192 ${r.action}`),o.push("This chat's history cannot be edited: what is already here comes back only in a new chat (save_handoff).")):o.push("No findings. Keep going.");let s={total_tokens:t.totalTokens,recoverable_tokens:t.totalEstSavings,recoverable_by:"a new chat (handoff)"};return n.length&&(s.other_findings=n.map(i=>`${i.severity}${i.estSavings>0?` ~${z(i.estSavings)}`:""}: ${i.message}`)),t.usagePct!==void 0&&(s.window_pct=t.usagePct),t.perTurnUsd!==void 0&&(s.usd_per_turn=Number(t.perTurnUsd.toFixed(4))),{text:o.join(`
|
|
97
|
+
`),structured:s,meta:{"context-doctor/report":e}}}function oO(t,e){let r=n=>n.slice(n.lastIndexOf("#")+1);return t===e?`#${r(t)}`:`#${r(t)}-${r(e)}`}function sO(t){let e=t.replace(/\s*\(cont\.\)$/,""),r=e.split(" > ");return r[r.length-1]||e}function lx(t,e,r=120){let n=new Map;for(let d of t.chunks){let m=n.get(d.source)??[],p=sO(d.heading),f=m[m.length-1];f&&f.heading===p?(f.last=d.id,f.tokens+=d.tokens):m.push({first:d.id,last:d.id,heading:p,tokens:d.tokens}),n.set(d.source,m)}let o=r,s=0,i=[...n.entries()].map(([d,m])=>{let p=m.slice(0,Math.max(0,o));o-=p.length,s+=m.length-p.length;let f=m.reduce((g,h)=>g+h.tokens,0);return{name:d,tokens:fo(f),sections:p.map(g=>`${oO(g.first,g.last)} ${g.heading} ~${z(g.tokens)}`)}}),a=t.sources.length===1?t.sources[0].name:`${t.sources.length} files`,c=t.chunks[0]?.id??"name#1",u=`OUTLINE of ${a}: ~${z(t.totalTokens)} tokens in ${t.chunks.length} chunks, as sections in structuredContent. Nothing packed: pass a query, or ids (<name>#<n>, e.g. ${c}).`,l={total_tokens:fo(t.totalTokens),chunks:t.chunks.length,sources:i};return s>0&&(l.sections_not_shown=s),{text:u,structured:l,meta:{"context-doctor/outline":e}}}import{existsSync as iO,lstatSync as or,mkdirSync as mx,readdirSync as aO,readFileSync as xp,realpathSync as La,rmSync as cO,writeFileSync as dx}from"node:fs";import{homedir as mo}from"node:os";import{isAbsolute as uO,join as nt,relative as lO,sep as dO}from"node:path";var yt={briefTargetTokens:400,briefChars:6e3,titleChars:80,modelChars:100,blocks:20,labelChars:80,blockChars:2e4,totalChars:6e4,kept:100,readBytes:512*1024};function wp(t=mo()){return nt(t,".context-doctor","handoffs")}var fO=/^\d{8}-\d{6}-[a-z0-9]+(?:-[a-z0-9]+)*$/;function hx(t){return typeof t=="string"&&t.length<=80&&fO.test(t)}function pO(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/g,"")||"handoff"}function mO(t){let e=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}${e(t.getUTCMonth()+1)}${e(t.getUTCDate())}-${e(t.getUTCHours())}${e(t.getUTCMinutes())}${e(t.getUTCSeconds())}`}function $p(t){let e=[],r=yt;typeof t?.brief!="string"||!t.brief.trim()?e.push("`brief` is empty: write the handoff brief first."):t.brief.length>r.briefChars&&e.push(`\`brief\` is ${t.brief.length} characters; the limit is ${r.briefChars} (aim for \u2264${r.briefTargetTokens} tokens).`),t.title!==void 0&&(typeof t.title!="string"||t.title.length>r.titleChars)&&e.push(`\`title\` must be a string of at most ${r.titleChars} characters.`);let n=t.verbatim??[];if(!Array.isArray(n))e.push("`verbatim` must be a list of {label, text}.");else{n.length>r.blocks&&e.push(`${n.length} verbatim blocks; the limit is ${r.blocks}. Keep only what must stay exact.`);let o=typeof t.brief=="string"?t.brief.length:0;n.forEach((s,i)=>{(typeof s?.label!="string"||!s.label.trim()||s.label.length>r.labelChars)&&e.push(`verbatim[${i}].label must be 1-${r.labelChars} characters.`),typeof s?.text!="string"||!s.text.trim()?e.push(`verbatim[${i}].text is empty.`):s.text.length>r.blockChars?e.push(`verbatim[${i}] ("${String(s.label).slice(0,40)}") is ${s.text.length} characters; the limit is ${r.blockChars}. Summarize it, or keep only the exact lines needed.`):o+=s.text.length}),o>r.totalChars&&e.push(`The handoff is ${o} characters; the limit is ${r.totalChars}. A handoff that big is not a cut.`)}t.model!==void 0&&typeof t.model!="string"&&e.push("`model` must be a string.");for(let o of["chatTokens","turns"]){let s=t[o];s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||s<0||s>1e8)&&e.push(`\`${o}\` must be a non-negative number.`)}return e}var po="masked by context-doctor",qe=(t,e,r=()=>!0)=>({kind:t,re:e,replace:n=>r(n[0])?`[${t.replace(/^an? /,"")} ${po}]`:void 0}),hO=t=>/[0-9]/.test(t)&&/[A-Z]/.test(t)&&/[a-z]/.test(t),gO=[qe("a private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|$)/g),qe("an Anthropic key",/(?<![A-Za-z0-9_.-])sk-ant-[A-Za-z0-9_-]{20,}/g),qe("an OpenAI key",/(?<![A-Za-z0-9_.-])sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}/g,hO),qe("an AWS access key",/(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g),qe("a GitHub token",/(?<![A-Za-z0-9])(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/g),qe("a GitLab token",/(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20,}/g),qe("a Slack token",/(?<![A-Za-z0-9])xox[abposr]-[A-Za-z0-9-]{10,}/g),qe("a Slack webhook",/https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9_/-]+/g),qe("a Google API key",/(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{30,}/g),qe("an npm token",/(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g),qe("a Stripe key",/(?<![A-Za-z0-9])(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g),qe("a Stripe webhook secret",/(?<![A-Za-z0-9])whsec_[A-Za-z0-9]{20,}/g),qe("a Hugging Face token",/(?<![A-Za-z0-9])hf_[A-Za-z0-9]{30,}/g),qe("a SendGrid key",/(?<![A-Za-z0-9])SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g),qe("a Twilio key",/(?<![A-Za-z0-9])SK[0-9a-f]{32}(?![A-Za-z0-9])/g),qe("a JWT",/(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g),{kind:"a password in a URL",re:/\b([a-z][a-z0-9+.-]*:\/\/)([^\s:@/]*):([^\s@/]+)@/gi,replace:t=>`${t[1]}${t[2]}:[${po}]@`},{kind:"a bearer token",re:/\b(Bearer|Basic|Token)(\s+)([A-Za-z0-9._~+/=-]{16,})/g,replace:t=>`${t[1]}${t[2]}[${po}]`},{kind:"a database password",re:/(\bmysql(?:dump|admin)?\b[^\n]*?\s-p)([^\s-][^\s]*)/g,replace:t=>`${t[1]}[${po}]`}],gx="(?:password|passwd|passphrase|pwd|secret|secret[_-]?key|secret[_-]?access[_-]?key|access[_-]?key|client[_-]?secret|api[_-]?key|apikey|access[_-]?token|auth[_-]?token|authtoken|refresh[_-]?token|bearer[_-]?token|token|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key|credentials?)",yO=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${gx}["']?\\s*[:=]\\s*["']?)([^\\s"'\`,;()<>{}\\[\\]]{3,})(?=$|[\\s"'\`,;)\\]}])`,"gim"),_O=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${gx}["']?\\s*[:=]\\s*)(["'])([^"'\\n]{3,500})\\2`,"gim"),vO=/^(?:string|str|number|int|integer|bool|boolean|any|null|nil|none|undefined|true|false|required|optional|empty|redacted|hidden|secret|password|\*+|x{3,}|\.{3,})$/i,xO=/^(?:your[_-]|<|\$\{?|%|\{\{|changeme|placeholder|example|dummy)|(?:[_-]here)(?:[_-]?\d+)?$/i;function fx(t){return!(vO.test(t)||xO.test(t)||/^(?:\/|~\/|\.{1,2}\/|[A-Za-z]:\\)/.test(t)||/^(?:process\.env|os\.environ|env\.|ENV\[|getenv)/i.test(t)||/^[A-Za-z_$][\w$]*(?:\.[\w$]+)+$/.test(t)&&!/[0-9]/.test(t)||/^\d{1,7}$/.test(t))}function Pr(t){let e=0,r=new Set,n=String(t??"");for(let o of gO)n=n.replace(o.re,(...s)=>{let i=s.slice(0,-2).filter(c=>typeof c=="string"||c===void 0),a=o.replace(i);return a===void 0?i[0]:(e++,r.add(o.kind),a)});return n=n.replace(_O,(o,s,i,a)=>fx(a.trim())?(e++,r.add("a password or secret assignment"),`${s}${i}[${po}]${i}`):o),n=n.replace(yO,(o,s,i)=>fx(i)?(e++,r.add("a password or secret assignment"),`${s}[${po}]`):o),{text:n,count:e,kinds:[...r]}}function bO(t){let e=Math.max(0,...(t.match(/`+/g)??[]).map(r=>r.length));return"`".repeat(Math.max(3,e+1))}function bp(t,e){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function wO(t,e,r,n){let o=[`# Handoff: ${t}`,"",`Continue from this handoff (written ${e.slice(0,16).replace("T"," ")} UTC, saved by context-doctor). It replaces the earlier chat; ask for anything it does not cover.`,"",r.trim()];if(n.length){o.push("","## Verbatim (keep exact)");for(let s of n){let i=bO(s.text);o.push("",`### ${bp(s.label,yt.labelChars)}`,"",i,s.text.replace(/\s+$/,""),i)}}return o.join(`
|
|
98
98
|
`)+`
|
|
99
|
-
`}function
|
|
100
|
-
`)}function
|
|
101
|
-
`);return e?r.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,""):r.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}function
|
|
102
|
-
`).find(x=>x.trim())?.replace(/^#+\s*/,"")||"handoff",
|
|
103
|
-
`,{mode:384,flag:"wx"})}catch(x){throw new
|
|
104
|
-
`))!==-1;)e(s.slice(0,a)),s=s.slice(a+1)}s+=n.end(),s&&e(s)}finally{
|
|
105
|
-
`):""}function
|
|
106
|
-
[\u2026 ${t.length-
|
|
107
|
-
${i.text.slice(-e)}`,masked:r.count+i.count+o}}function
|
|
108
|
-
`)[0],s=JSON.parse(o)?.payload?.cwd;return typeof s=="string"?s:void 0}finally{
|
|
99
|
+
`}function $O(t,e){let r={after:t};e.chatTokens!==void 0&&e.chatTokens>0?(r.now=Math.round(e.chatTokens),r.nowSource="given"):e.turns!==void 0&&e.turns>0&&(r.now=Math.round(e.turns)*dp(e.model),r.nowSource="turns");let n=so(e.model);return n&&(r.afterUsd=Rr(r.after,n),r.afterCachedUsd=r.after/1e6*n.cacheReadPerM,r.now!==void 0&&(r.nowUsd=Rr(r.now,n),r.nowCachedUsd=r.now/1e6*n.cacheReadPerM)),r}function yx(t){let e=(o,s)=>o!==void 0?` (${Ut(o)} at list price, ${Ut(s??0)} cached)`:"";if(t.now===void 0)return`A new chat starts from ~${z(t.after)} tokens${e(t.afterUsd,t.afterCachedUsd)}, plus the app's own system prompt. Pass chat_tokens (from profile_context) to see the per-turn saving.`;let r=t.nowSource==="turns"?" (estimated from the turn count)":"",n=Math.max(0,t.now-t.after);return[`Now: ~${z(t.now)} tokens re-read on every turn${r}${e(t.nowUsd,t.nowCachedUsd)}.`,`After: ~${z(t.after)} in a new chat${e(t.afterUsd,t.afterCachedUsd)}, plus the app's own system prompt, which every chat carries.`,`Saves ~${z(n)} tokens per further turn${t.now>0?` (${Math.round(n/t.now*100)}%)`:""}; on a subscription that is usage limit.`].join(`
|
|
100
|
+
`)}function qa(t,e){let r=lO(t,e);return r===""||r!==".."&&!r.startsWith(".."+dO)&&!uO(r)}var _n=class extends Error{};function Ua(t,e){let r=i=>{if(e)throw new _n(i)},n;try{n=La(t)}catch{return r("the home directory cannot be read")}let o=nt(t,".context-doctor"),s=wp(t);for(let i of[o,s]){let a;try{a=or(i)}catch{if(!e)return;try{mx(i,{mode:448}),a=or(i)}catch(u){return r(`cannot create ${gt(i,t)} (${u.code??"error"})`)}}if(a.isSymbolicLink())return r(`${gt(i,t)} is a symbolic link; handoffs are only written to a real folder in the home directory`);if(!a.isDirectory())return r(`${gt(i,t)} is not a folder`);let c;try{c=La(i)}catch{return r(`${gt(i,t)} cannot be read`)}if(!qa(n,c))return r(`${gt(i,t)} resolves outside the home directory`)}return s}function px(t,e){let r=Date.parse(t.created);return Number.isFinite(r)&&r<=e+6e4?r:0}function kO(t){let e=r=>typeof r.order=="number"&&Number.isFinite(r.order)?r.order:0;return(r,n)=>px(n,t)-px(r,t)||e(n)-e(r)||(r.id<n.id?1:r.id>n.id?-1:0)}var SO=0;function Fa(t=mo()){let e=Ua(t,!1);if(!e)return[];let r;try{r=aO(e)}catch{return[]}let n=[];for(let o of r){if(!hx(o))continue;let s=nt(e,o);try{if(!or(s).isDirectory())continue;let i=nt(s,"meta.json");if(!or(i).isFile())continue;let a=JSON.parse(xp(i,"utf8"));if(a?.id!==o||typeof a.created!="string")continue;n.push(a)}catch{continue}}return n.sort(kO(Date.now()))}function kp(t,e=mo()){let r=t==="latest"?Fa(e)[0]?.id:t;if(!hx(r))return;let n=Ua(e,!1);if(!n)return;let o=nt(n,r),s=nt(o,"handoff.md");if(qa(n,s))try{let i=or(s);if(!i.isFile()||i.size>yt.readBytes||!or(o).isDirectory()||!or(nt(o,"meta.json")).isFile())return;let a=JSON.parse(xp(nt(o,"meta.json"),"utf8"));return a?.id!==r?void 0:{meta:a,markdown:xp(s,"utf8")}}catch{return}}function TO(t,e,r){let n=Ua(t,!1);if(!n)return 0;let o=Fa(t).filter(i=>i.id!==r),s=0;for(let i of o.slice(Math.max(0,e-1))){let a=nt(n,i.id);try{if(!qa(n,a)||!or(a).isDirectory()||!or(nt(a,"meta.json")).isFile()||!qa(La(n),La(a)))continue;cO(a,{recursive:!0,force:!0}),s++}catch{}}return s}function nr(t,{keepNewlines:e=!0}={}){let r=String(t??"").replace(/\r\n?/g,`
|
|
101
|
+
`);return e?r.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,""):r.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}function _x(t,{home:e=mo(),now:r=new Date,store:n=!0}={}){let o=$p(t);if(o.length)throw new Error(o.join(" "));let s=new Set,i=0,a=x=>{let $=Pr(x);return i+=$.count,$.kinds.forEach(O=>s.add(O)),$.text},c=a(nr(t.brief)),u=bp(t.title?.trim()?a(nr(t.title,{keepNewlines:!1})):c.split(`
|
|
102
|
+
`).find(x=>x.trim())?.replace(/^#+\s*/,"")||"handoff",yt.titleChars),l=(t.verbatim??[]).map(x=>({label:bp(a(nr(x.label,{keepNewlines:!1})),yt.labelChars),text:a(nr(x.text))})),d=t.model===void 0?void 0:a(nr(String(t.model),{keepNewlines:!1})).slice(0,yt.modelChars)||void 0,m=r.toISOString(),p=wO(u,m,c,l),f=`${mO(r)}-${pO(u)}`,g={id:f,title:u,created:m,model:d,tokens:Rt(p,d),briefTokens:Rt(c,d),blocks:l.map(x=>({label:x.label,tokens:Rt(x.text,d)})),masked:i,order:Date.now()*1e3+SO++%1e3},h=$O(g.tokens,{...t,model:d});if(!n)return{meta:g,markdown:p,maskedKinds:[...s],math:h,rotated:0};let _=Ua(e,!0),v="";for(let x=1;x<=200;x++){let $=x===1?f:`${f}-${x}`,O=nt(_,$);try{mx(O,{mode:448}),g.id=$,v=O;break}catch(C){if(C.code!=="EEXIST")throw new _n(`cannot create a handoff folder in ${gt(_,e)} (${C.code??"error"})`)}}if(!v)throw new _n(`too many handoffs saved in the same second in ${gt(_,e)}`);try{dx(nt(v,"handoff.md"),p,{mode:384,flag:"wx"}),dx(nt(v,"meta.json"),JSON.stringify(g,null,2)+`
|
|
103
|
+
`,{mode:384,flag:"wx"})}catch(x){throw new _n(`cannot write the handoff in ${gt(v,e)} (${x.code??"error"})`)}let y=TO(e,yt.kept,g.id);if(!iO(nt(v,"handoff.md")))throw new _n(`the handoff in ${gt(v,e)} is gone`);return{meta:g,markdown:p,dir:v,maskedKinds:[...s],math:h,rotated:y}}function gt(t,e=mo()){return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function vx(t,e=mo()){return e&&e.length>1?String(t).split(e).join("~"):String(t)}import{lookup as EO}from"node:dns";import{request as zO}from"node:http";import{request as RO}from"node:https";import{isIP as bx}from"node:net";import{mkdtempSync as PO,rmSync as IO,writeFileSync as CO}from"node:fs";import{tmpdir as AO}from"node:os";import{extname as OO,join as xx}from"node:path";var Je={files:10,bytes:5*1024*1024,totalBytes:20*1024*1024,timeoutMs:2e4,redirects:3,callMs:6e4},NO={"application/pdf":".pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/msword":".doc","application/rtf":".rtf","text/rtf":".rtf","application/vnd.oasis.opendocument.text":".odt","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx"};function wx(t=process.env){return t.CONTEXT_DOCTOR_TEST_LOOPBACK_FILES==="1"}function Sp(t){let[e,r]=t.split(".").map(Number),n=Number(t.split(".")[2]);return e===0||e===10||e===127||e>=224||e===169&&r===254||e===172&&r>=16&&r<=31||e===192&&r===168||e===100&&r>=64&&r<=127||e===192&&r===0||e===198&&(r===18||r===19)||e===198&&r===51&&n===100||e===203&&r===0&&n===113||e===192&&r===88&&n===99}function MO(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"").replace(/%.*$/,""),r=e.match(/(\d+\.\d+\.\d+\.\d+)$/);if(r){let[u,l,d,m]=r[1].split(".").map(Number);e=e.slice(0,-r[1].length)+`${(u<<8|l).toString(16)}:${(d<<8|m).toString(16)}`}let[n,o]=e.split("::"),s=n?n.split(":"):[],i=o!==void 0&&o?o.split(":"):[],a=e.includes("::")?8-s.length-i.length:0,c=[...s,...Array(Math.max(0,a)).fill("0"),...i].map(u=>parseInt(u||"0",16));return c.length===8&&c.every(u=>Number.isInteger(u)&&u>=0&&u<=65535)?c:void 0}function $x(t){let e=t.replace(/^\[|\]$/g,""),r=bx(e);if(r===4)return Sp(e);if(r===6){let n=MO(e);return n?n.slice(0,5).every(o=>o===0)&&(n[5]===65535||n[5]===0)?n[5]===0&&n[6]===0&&n[7]<=1?!0:Sp(`${n[6]>>8}.${n[6]&255}.${n[7]>>8}.${n[7]&255}`):n.slice(0,4).every(o=>o===0)&&n[4]===65535&&n[5]===0?Sp(`${n[6]>>8}.${n[6]&255}.${n[7]>>8}.${n[7]&255}`):n[0]===100&&n[1]===65435||n[0]===8194||n[0]===8193&&n[1]===0||(n[0]&65024)===64512||(n[0]&65472)===65152||(n[0]&65280)===65280||n[0]===8193&&n[1]===3512||n[0]===256&&n[1]===0&&n[2]===0&&n[3]===0:!0}return!0}function Tp(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^127\./.test(e)}function jO(t,e=process.env){let r;try{r=new URL(t)}catch{return{error:"not a URL"}}if(r.username||r.password)return{error:"credentials in the URL"};let n=r.hostname.replace(/^\[|\]$/g,""),o=wx(e)&&Tp(n);return r.protocol!=="https:"&&!(r.protocol==="http:"&&o)?{error:`only https downloads are allowed (got ${r.protocol.replace(":","")})`}:o?{url:r}:/^localhost$|\.localhost$|\.local$|\.internal$/i.test(n.replace(/\.$/,""))?{error:"a local host name"}:bx(n)&&$x(n)?{error:"a private or loopback address"}:{url:r}}function ZO(t){return(e,r,n)=>{EO(e,r,(o,s,i)=>{if(o)return n(o);if((Array.isArray(s)?s:[{address:s,family:i??4}]).find(u=>$x(u.address)&&!(t&&Tp(u.address))))return n(Object.assign(new Error(`${e} resolves to a private address`),{code:"EPRIVATE"}));Array.isArray(s)?n(null,s):n(null,s,i)})}}function DO(t,e,r,n){return new Promise(o=>{let s=wx(e)&&Tp(t.hostname),i=t.protocol==="https:"?RO:zO,a=!1,c=m=>{a||(a=!0,clearTimeout(l),o(m))},u=Math.max(1,r-at()),l=setTimeout(()=>{d.destroy(),c({status:0,error:"timed out"})},u),d=i(t,{method:"GET",lookup:ZO(s),timeout:u,headers:{accept:"*/*","user-agent":"context-doctor"}},m=>{let p=m.statusCode??0;if(p>=300&&p<400)return m.resume(),c({status:p,location:typeof m.headers.location=="string"?m.headers.location:void 0});if(p!==200)return m.resume(),c({status:p,error:`HTTP ${p}`});let f=n<Je.bytes?`over the ${Je.totalBytes/1024/1024} MB total for one call`:`too large (over ${Je.bytes/1024/1024} MB)`,g=Number(m.headers["content-length"]);if(Number.isFinite(g)&&g>n)return d.destroy(),c({status:p,error:f});let h=[],_=0;m.on("data",v=>{if(_+=v.length,_>n){d.destroy(),c({status:p,error:f});return}h.push(v)}),m.on("end",()=>c({status:p,body:Buffer.concat(h)})),m.on("error",v=>c({status:p,error:v.message}))});d.on("timeout",()=>{d.destroy(),c({status:0,error:"timed out"})}),d.on("error",m=>c({status:0,error:m.code==="EPRIVATE"?"refused: the host resolves to a private address":m.message})),d.end()})}async function LO(t,e=process.env,{deadline:r,maxBytes:n=Je.bytes}={}){let o=Math.min(at()+Je.timeoutMs,r??1/0),s=Math.max(0,Math.min(n,Je.bytes)),i=t;for(let a=0;a<=Je.redirects;a++){let c=jO(i,e);if("error"in c)return{error:a===0?`refused: ${c.error}`:`refused a redirect: ${c.error}`};if(at()>=o)return{error:"timed out"};let u=await DO(c.url,e,o,s);if(u.error)return{error:u.error};if(u.location!==void 0){if(!u.location)return{error:`HTTP ${u.status} without a location`};try{i=new URL(u.location,c.url).toString()}catch{return{error:"refused a redirect: not a URL"}}continue}return{body:u.body??Buffer.alloc(0)}}return{error:`more than ${Je.redirects} redirects`}}function qO(t){return((t.file_name??"").split(/[\\/]/).pop()?.replace(/[^\w.\- ]+/g,"_").trim()||String(t.file_id||"file").replace(/[^\w.-]+/g,"_")).slice(0,80)}async function kx(t,e=process.env){let r=[],n=[],o=0,s=at()+Je.callMs;for(let i of t.slice(0,Je.files)){let a=qO(i);if(at()>=s){n.push(`${a}: not read, the ${Je.callMs/1e3} s allowed for one call ran out`);continue}let c=await LO(String(i.download_url??""),e,{deadline:s,maxBytes:Je.totalBytes-o});if("error"in c){n.push(`${a}: ${c.error}`);continue}o+=c.body.length;let u=OO(a).toLowerCase(),l=Oa.has(u)?u:NO[(i.mime_type??"").split(";")[0].trim().toLowerCase()];if(l){let d=PO(xx(AO(),"cd-file-"));try{let m=xx(d,`upload${l}`);CO(m,c.body,{mode:384});let p=await Na(m,Math.min(at()+Es,s));"error"in p?n.push(`${a}: ${p.error}`):r.push({name:a,text:p.text})}finally{IO(d,{recursive:!0,force:!0})}continue}if(c.body.subarray(0,8e3).includes(0)){n.push(`${a}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);continue}r.push({name:a,text:c.body.toString("utf8")})}return t.length>Je.files&&n.push(`${t.length-Je.files} more file(s): at most ${Je.files} per call`),{sources:r,skipped:n}}var Sx={bodyBytes:10485760,bodyMs:3e4},UO=["https://chatgpt.com","https://chat.openai.com"],Tx=["localhost","127.0.0.1","::1"];function Ha(t){return(t??"").split(",").map(e=>e.trim()).filter(Boolean)}function Ba(t){let e=t.trim().toLowerCase();return e.startsWith("[")?e=e.slice(1,e.indexOf("]")>0?e.indexOf("]"):void 0):e.split(":").length===2&&(e=e.split(":")[0]),e.replace(/\.$/,"")}function Ex(t,e,r,n=process.env){let o=[...Ha(e),...Ha(n.CONTEXT_DOCTOR_ALLOWED_HOSTS)],s=new Set([...UO,...Ha(r),...Ha(n.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map(c=>c.toLowerCase().replace(/\/+$/,"")));if(o.includes("*"))return{hosts:"*",origins:s};let i=Ba(t),a=new Set([...Tx,...o.map(Ba)]);return i&&i!=="0.0.0.0"&&i!=="::"&&a.add(i),{hosts:a,origins:s}}function zx(t,e){if(t.hosts!=="*"){let n=Ba(String(e.host??""));if(!n)return"the request has no Host header";if(!t.hosts.has(n))return`Host "${n}" is not one this server answers to. Behind a tunnel or under a host name, start it with --allowed-hosts ${n}`}let r=e.origin;if(r!==void 0){let n=String(r).toLowerCase().replace(/\/+$/,"");if(t.origins.has(n))return;let o;try{o=new URL(n)}catch{return`Origin "${n}" is not allowed`}let s=Ba(o.host);if(!(Tx.includes(s)||t.hosts!=="*"&&t.hosts.has(s)))return`Origin "${n}" is not allowed. To let a web page call this server, start it with --allowed-origins ${n}`}}function Rx(t,e=Sx.bodyBytes,r=Sx.bodyMs){return new Promise(n=>{let o=!1,s=setTimeout(()=>{o||(o=!0,n({status:408,code:-32600,message:`the request body did not arrive within ${Math.round(r/1e3)} s`}))},r),i=d=>{clearTimeout(s),n(d)},a={status:413,code:-32600,message:`request body over ${Math.round(e/1024/1024)} MB`},c=Number(t.headers["content-length"]);if(Number.isFinite(c)&&c>e)return t.resume(),i(a);let u=[],l=0;t.on("data",d=>{if(!o){if(l+=d.length,l>e)return o=!0,u.length=0,t.resume(),i(a);u.push(d)}}),t.on("end",()=>{if(!o){o=!0;try{i({value:JSON.parse(Buffer.concat(u).toString("utf8"))})}catch{i({status:400,code:-32700,message:"Parse error: the body is not JSON"})}}}),t.on("error",()=>{o||(o=!0,i({status:400,code:-32700,message:"the request body could not be read"}))})})}import{closeSync as XO,existsSync as Ja,openSync as YO,readdirSync as Wa,readSync as QO,statSync as Rp}from"node:fs";import{homedir as Pp}from"node:os";import{basename as Mx,dirname as eN,isAbsolute as tN,join as vn,resolve as jx}from"node:path";import{homedir as Px}from"node:os";import{join as FO,resolve as HO}from"node:path";function Va(t,e=process.env){if(t===void 0||t===Px()){let r=e.CODEX_HOME?.trim();if(r)return HO(r)}return FO(t??Px(),".codex")}import{readdirSync as C9,readFileSync as A9,statSync as O9,existsSync as N9,openSync as BO,readSync as VO,closeSync as JO}from"node:fs";import{StringDecoder as WO}from"node:string_decoder";import{homedir as KO}from"node:os";import{join as GO}from"node:path";function Ix(t,e=KO()){return GO(ao(e),"projects",t.replace(/[^A-Za-z0-9]/g,"-"))}function Ep(t,e){let r=BO(t,"r"),n=new WO("utf8"),o=Buffer.allocUnsafe(4*1024*1024),s="";try{for(;;){let i=VO(r,o,0,o.length,null);if(i===0)break;s+=n.write(o.subarray(0,i));let a;for(;(a=s.indexOf(`
|
|
104
|
+
`))!==-1;)e(s.slice(0,a)),s=s.slice(a+1)}s+=n.end(),s&&e(s)}finally{JO(r)}}var zs=2e5,rN=8e6,Cx=16384;function zp(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:e?.type==="image"||e?.type==="input_image"?"[image]":"").filter(Boolean).join(`
|
|
105
|
+
`):""}function nN(t){if(t.length<=zs)return{whole:t};let e=zs/2;return{head:t.slice(0,e+Cx),tail:t.slice(-(e+Cx)),length:t.length}}var Ax=t=>"whole"in t?t.whole.length:zs;function oN(t){if("whole"in t){let a=Pr(nr(t.whole));return{text:a.text,masked:a.count}}let e=zs/2,r=Pr(nr(t.head)),n=nr(t.tail),o=0,s=/-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----/.exec(n);s&&!/-----BEGIN [A-Z0-9 ]*PRIVATE KEY/.test(n.slice(0,s.index))&&(n=`[private key masked by context-doctor]${n.slice(s.index+s[0].length)}`,o=1);let i=Pr(n);return{text:`${r.text.slice(0,e)}
|
|
106
|
+
[\u2026 ${t.length-zs} characters \u2026]
|
|
107
|
+
${i.text.slice(-e)}`,masked:r.count+i.count+o}}function Ox(t,e){let r=e??{},n=["command","file_path","path","pattern","url","query","cmd","description","prompt"].find(s=>typeof r[s]=="string"),o=n?String(r[n]):typeof e=="string"?e:JSON.stringify(e??"");return`${t}: ${o.slice(0,2e3)}`}function sN(t,e=rN){let r=[],n=0,o=0,s=0,i=0,a=/[\\/]subagents[\\/]agent-[^\\/]*\.jsonl$/.test(t)||void 0,c=new Map,u=(m,p,f)=>{let g=f.trim();if(!g)return;s++;let h=nN(g);for(r.push({n:s,at:typeof m=="string"?m:void 0,kind:p,raw:h,compactedBy:0,c:i}),o+=Ax(h);o>e&&n<r.length-1;)o-=Ax(r[n].raw),r[n].raw={whole:""},n++;n>1024&&(r.splice(0,n),n=0),c.size>1e5&&c.clear()};Ep(t,m=>{let p;try{p=JSON.parse(m)}catch{return}if(!p||typeof p!="object")return;if(p.payload&&typeof p.payload=="object"&&typeof p.type=="string"&&!p.message){let h=p.payload;if(p.type==="compacted"||h.type==="context_compacted"){i++;return}if(p.type!=="response_item")return;if(h.type==="message"&&(h.role==="user"||h.role==="assistant"))return u(p.timestamp,h.role,zp(h.content));if(h.type==="function_call"||h.type==="custom_tool_call"||h.type==="local_shell_call"){let _=String(h.name??(h.type==="local_shell_call"?"shell":h.type));typeof h.call_id=="string"&&c.set(h.call_id,_);let v=h.arguments??h.input??h.action;if(typeof v=="string")try{v=JSON.parse(v)}catch{}return u(p.timestamp,"tool call",Ox(_,v))}return/_call_output$/.test(String(h.type))?u(p.timestamp,`tool output (${c.get(h.call_id)??"tool"})`,zp(h.output)):void 0}if(p.type==="system"&&p.subtype==="compact_boundary"){i++;return}if(p.isCompactSummary)return;let f=p.message;if(!f||(a===void 0&&(a=p.isSidechain===!0),p.isSidechain&&!a))return;let g=f.content;if(p.type==="user"){if(typeof g=="string")return u(p.timestamp,"user",g);if(!Array.isArray(g))return;for(let h of g)h?.type==="tool_result"?u(p.timestamp,`tool output (${c.get(h.tool_use_id)??"tool"})`,zp(h.content)):typeof h?.text=="string"&&u(p.timestamp,"user",h.text);return}if(p.type==="assistant"&&Array.isArray(g))for(let h of g)h?.type==="text"?u(p.timestamp,"assistant",String(h.text??"")):h?.type==="tool_use"&&(typeof h.id=="string"&&c.set(h.id,String(h.name??"tool")),u(p.timestamp,"tool call",Ox(String(h.name??"tool"),h.input)))});let l=0;return{entries:r.slice(n).map(({c:m,raw:p,...f})=>{let g=oN(p);return l+=g.masked,{...f,text:g.text,compactedBy:i-m}}),total:s,compactions:i,masked:l}}function iN(t){try{let e=YO(t,"r");try{let r=Buffer.alloc(65536),n=QO(e,r,0,r.length,0),o=r.subarray(0,n).toString("utf8").split(`
|
|
108
|
+
`)[0],s=JSON.parse(o)?.payload?.cwd;return typeof s=="string"?s:void 0}finally{XO(e)}}catch{return}}function Nx(t){let e;try{for(let r of Wa(t)){if(!r.endsWith(".jsonl"))continue;let n=vn(t,r),o=Rp(n).mtimeMs;(!e||o>e.at)&&(e={path:n,at:o})}}catch{}return e}function aN(t,e){let r=vn(Va(e),"sessions");if(!Ja(r))return;let n=Date.now()-7*864e5,o=[],s=(i,a)=>{let c;try{c=Wa(i)}catch{return}for(let u of c){let l=vn(i,u),d;try{d=Rp(l)}catch{continue}d.isDirectory()?a<3&&s(l,a+1):u.endsWith(".jsonl")&&d.mtimeMs>=n&&o.push({path:l,at:d.mtimeMs})}};return s(r,0),o.sort((i,a)=>a.at-i.at).find(i=>iN(i.path)===jx(t))}function Zx(t=process.env,e=process.cwd(),r=Pp(),n={}){let o=t.CLAUDE_CODE_SESSION_ID?.trim();if(o&&/^[\w.-]+$/.test(o)){let a=cN(o,r);if(a&&a.endsWith(`${o}.jsonl`)){if(n.envMayBeStale){let c=Nx(eN(a));if(c&&c.path!==a&&c.at>Rp(a).mtimeMs)return{path:c.path,how:`the newest Claude Code session in this project (${Mx(c.path,".jsonl")}; CLAUDE_CODE_SESSION_ID still names ${o}, as after /clear)`}}return{path:a,how:`this Claude Code session (${o})`}}}let s=Nx(Ix(e,r)),i=aN(e,r);return i&&(!s||i.at>s.at)?{path:i.path,how:"the newest Codex session started in this folder"}:s?{path:s.path,how:"the newest Claude Code session in this folder"}:void 0}function cN(t,e=Pp()){if((tN(t)||t.includes("/")||t.includes("\\"))&&Ja(t))return jx(t);if(!/^[\w.-]+$/.test(t))return;let r=vn(ao(e),"projects"),n=[];try{n=Wa(r)}catch{}for(let a of n){let c=vn(r,a,`${t}.jsonl`);if(Ja(c))return c}let o=vn(Va(e),"sessions"),s,i=(a,c)=>{if(s)return;let u;try{u=Wa(a)}catch{return}for(let l of u){let d=vn(a,l);if(l.endsWith(".jsonl")&&l.includes(t)){s=d;return}c<3&&!l.includes(".")&&i(d,c+1)}};return Ja(o)&&i(o,0),s}function Dx(t,e,r={}){let n=sN(t),{entries:o,compactions:s}=n,i=new Map,a=o.map(p=>{let f=`#${p.n}`;return i.set(f,p),{name:f,text:p.text}}),c=Math.max(200,r.budget??2e3),u=ex(a,{query:e,budget:c,maxChunkTokens:300}),l=p=>p.compactedBy===0?"in context":`before compaction ${s-p.compactedBy+1} of ${s}`,d=[...u.selected].sort((p,f)=>f.score-p.score).map(p=>{let f=i.get(p.source);return{id:p.id,n:f.n,at:f.at,kind:f.kind,where:l(f),tokens:p.tokens,score:p.score,text:p.text}}),m=u.chunks.filter(p=>p.score>0&&!u.selected.includes(p)).length;return{path:t,how:r.how??"the session named",query:e,entries:n.total,compactions:s,totalTokens:u.totalTokens,hits:d,masked:n.masked,more:m,leftOut:n.total-o.length}}function Lx(t,e=Pp()){let r=Mx(t.path).replace(/\.jsonl$/,"").slice(0,48),n=[`RECALL from ${t.how}${t.how.includes(r)?"":` (${r})`}: ${t.entries} entries, ~${z(t.totalTokens)} tokens, ${t.compactions} compaction${t.compactions===1?"":"s"}.`];if(!t.hits.length)return n.push(`Nothing in it matches "${t.query}". Try the words the output itself would use (a file name, an error, a command).`),n.join(`
|
|
109
109
|
`);n.push(`Best ${t.hits.length} excerpt${t.hits.length===1?"":"s"} for "${t.query}", best first${t.more?` (${t.more} more matched; a narrower query or a larger max_tokens gets them)`:""}:`),t.masked&&n.push(`${t.masked} secret-looking string${t.masked===1?"":"s"} masked.`),t.leftOut&&n.push(`The oldest ${t.leftOut} entries were not searched: the transcript is that large.`);for(let o of t.hits){let s=o.at?o.at.slice(0,16).replace("T"," ")+" UTC":"time not recorded";n.push("",`\u2500\u2500 entry ${o.n} of ${t.entries} \xB7 ${s} \xB7 ${o.kind} \xB7 ${o.where} \xB7 ~${z(o.tokens)}`,o.text)}return n.join(`
|
|
110
|
-
`).replaceAll(e,"~")}var
|
|
111
|
-
prune-history skipped: ${_.ok?"the user unticked it":_.why}.`)}let d
|
|
110
|
+
`).replaceAll(e,"~")}var eM=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],tM={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function Hp(t,e,r){if(ax(t)==="full")return{content:[{type:"text",text:e}]};let n=r();return{content:[{type:"text",text:n.text}],structuredContent:n.structured,_meta:n.meta}}async function Tb(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form)return{asked:!1};try{let n=await t.server.elicitInput({mode:"form",message:e,requestedSchema:{type:"object",properties:r}},{timeout:12e4});return n.action==="accept"?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}catch(n){return n instanceof I&&n.code===A.RequestTimeout?{asked:!0,ok:!1,content:{},why:"no answer within two minutes"}:{asked:!0,ok:!1,content:{},why:"the consent form failed, so nothing was assumed"}}}function Eb({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new ka({name:"context-doctor",version:"0.42.0"},{instructions:ix,maxToolInputElements:1e4});n.tool("profile_context","Profile a conversation's context: token breakdown, largest blocks, wasted context. Pass `conversation` (JSON or text) or, in a chat app, a `sketch` (~120 tokens). Call it when the user asks about tokens, cost, speed or limits, and once past ~30 turns or 3+ large pastes. Act on the top finding.",{conversation:Z.string().optional().describe("JSON or text; in a chat app pass `sketch`"),sketch:Z.object({turns:Z.number().int().nonnegative().describe("Exchanges so far"),model:Z.string().optional(),blocks:Z.array(Z.object({turn:Z.number().int().positive(),kind:Z.enum(["paste","code","tool_result","image","base64","text"]),label:Z.string().describe("Short name"),approx_tokens:Z.number().optional(),approx_lines:Z.number().optional(),approx_words:Z.number().optional(),approx_chars:Z.number().optional(),repeated:Z.number().int().optional().describe("Times it appears (2+ = duplicate)"),stale:Z.boolean().optional().describe("Acted on, no longer needed")})).describe("Only blocks over ~500 tokens, repeated, or images.")}).optional().describe("For chat apps. One size hint per block: lines for code, words for prose, chars for logs."),model:Z.string().optional().describe("e.g. claude-sonnet-5")},{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,sketch:a,model:c},u)=>{if(a){let m=h=>({isError:!0,content:[{type:"text",text:h}]});if(a.turns>1e5)return m(`sketch.turns is ${a.turns}; the most that makes sense is 100000.`);if(a.blocks.length>500)return m(`sketch.blocks has ${a.blocks.length} blocks; list at most 500 (only those over ~500 tokens, repeated, or images).`);for(let[h,_]of a.blocks.entries()){if(_.turn>1e5)return m(`sketch.blocks[${h}].turn is ${_.turn}; the most that makes sense is 100000.`);if(_.repeated!==void 0&&(_.repeated<1||_.repeated>1e3))return m(`sketch.blocks[${h}].repeated is ${_.repeated}; give 1 to 1000.`);for(let[v,y]of Object.entries(tM)){let x=_[v];if(typeof x=="number"&&!(x>0))return m(`sketch.blocks[${h}].${v} is ${x}; a size is above 0.`);if(typeof x=="number"&&x>y)return m(`sketch.blocks[${h}].${v} is ${x}; the most that makes sense is ${y}. Give a rough size of the block itself.`)}}let p=i?"Note: both `conversation` and `sketch` were passed; profiled the sketch only. Pass one.\n\n":"",f=Rv({...a,model:a.model??c},{record:!t}),g=p+zv(f);return Hp(u?._meta,g,()=>{let h=ux(f,g);return{...h,text:p+h.text}})}if(!i)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 l=vv(iv(i),c),d=Sv(l);return Hp(u?._meta,d,()=>cx(l,d))}),n.tool("optimize_context","Rewrite a conversation to reclaim tokens (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns slimmed JSON and the savings. Use after profile_context finds waste the user wants fixed; prune-history only with the user's consent, then write the summary the result asks for.",{conversation:Z.string().describe("Conversation JSON"),strategies:Z.array(Z.enum(eM)).optional().describe("Default: dedupe, trim-tool-results, strip-base64"),keep_recent:Z.number().int().nonnegative().optional().describe("Tail messages kept (default 6)"),max_tool_result_tokens:Z.number().int().positive().optional().describe("Per trimmed result (default 300)")},{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,strategies:a,keep_recent:c,max_tool_result_tokens:u})=>{let l="";if(a?.includes("prune-history")){let _=await Tb(n,`Prune old turns from this conversation? It is lossy: all but the last ${Math.max(2,c??6)} messages are replaced by a summary the assistant writes.`,{prune:{type:"boolean",title:"Replace old turns with a summary",default:!0}});_.asked&&(!_.ok||_.content.prune===!1)&&(a=a.filter(v=>v!=="prune-history"),l=`
|
|
111
|
+
prune-history skipped: ${_.ok?"the user unticked it":_.why}.`)}let d=$v(i,{strategies:a,keepRecent:c,maxToolResultTokens:u}),m=d.tokensBefore-d.tokensAfter;m>0&&!t&&Ia({ev:"optimize",src:"mcp",saved:m,model:d.conversation?.model});let p=`Saved ~${z(m)} tokens (${z(d.tokensBefore)} \u2192 ${z(d.tokensAfter)}) via ${d.applied.length} change(s):
|
|
112
112
|
`+d.applied.map(_=>`- [${_.strategy}] message #${_.messageIndex}: ${_.note} (~${z(_.tokensSaved)})`).join(`
|
|
113
113
|
`)+l,f=1e5,g=JSON.stringify(d.conversation),h=[{type:"text",text:p},g.length<=f?{type:"text",text:g}:{type:"text",text:`[optimized conversation is ${g.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 d.prunedDigest&&h.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.
|
|
114
114
|
|
|
115
115
|
PRUNED TURNS DIGEST:
|
|
116
|
-
`+d.prunedDigest}),{content:h}});let o=Z.object({download_url:Z.string(),file_id:Z.string(),mime_type:Z.string().optional(),file_name:Z.string().optional()}).strict(),s={...t?{}:{paths:Z.array(Z.string()).optional().describe("Files or folders, absolute paths")},text:Z.string().optional().describe("Raw text to pack instead of files"),query:Z.string().optional().describe("The question; omit for an outline"),max_tokens:Z.number().int().positive().optional().describe("Budget, default 4000"),ids:Z.array(Z.string()).optional().describe("Chunk ids, e.g. docs/guide.md#4"),model:Z.string().optional().describe("Model to count for"),...t?{files:Z.array(o).optional().describe("Files the user uploaded")}:{semantic:Z.boolean().optional().describe("Also rank by meaning (local Ollama embeddings)")}};if(n.registerTool("pack_context",{description:"Read only the parts of large files a question needs: the chunks that best match `query` within `max_tokens`, with ids and line ranges. 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.",inputSchema:s,annotations:{title:"Pack context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},...t?{_meta:{"openai/fileParams":["files"]}}:{}},async(i,a)=>{let{paths:c,text:u,query:l,max_tokens:d,ids:m,model:p,semantic:f,files:g}=i,h=O=>({content:[{type:"text",text:O}],isError:!0});if((c?.length??0)>50)return h(`${c.length} paths; pass at most 50 (a folder counts as one).`);if((m?.length??0)>200)return h(`${m.length} ids; ask for at most 200.`);if(d!==void 0&&d>2e5)return h(`max_tokens ${d}; the most is 200000.`);if(c?.length&&!r)return h("This server runs over HTTP and does not read files. Pass the document as `text`, or attach it (`files`).");let{sources:_,skipped:v}=c?.length?await
|
|
117
|
-
Skipped: ${v.slice(0,10).join("; ")}${v.length>10?` (+${v.length-10} more)`:""}`:"",$=
|
|
116
|
+
`+d.prunedDigest}),{content:h}});let o=Z.object({download_url:Z.string(),file_id:Z.string(),mime_type:Z.string().optional(),file_name:Z.string().optional()}).strict(),s={...t?{}:{paths:Z.array(Z.string()).optional().describe("Files or folders, absolute paths")},text:Z.string().optional().describe("Raw text to pack instead of files"),query:Z.string().optional().describe("The question; omit for an outline"),max_tokens:Z.number().int().positive().optional().describe("Budget, default 4000"),ids:Z.array(Z.string()).optional().describe("Chunk ids, e.g. docs/guide.md#4"),model:Z.string().optional().describe("Model to count for"),...t?{files:Z.array(o).optional().describe("Files the user uploaded")}:{semantic:Z.boolean().optional().describe("Also rank by meaning (local Ollama embeddings)")}};if(n.registerTool("pack_context",{description:"Read only the parts of large files a question needs: the chunks that best match `query` within `max_tokens`, with ids and line ranges. 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.",inputSchema:s,annotations:{title:"Pack context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},...t?{_meta:{"openai/fileParams":["files"]}}:{}},async(i,a)=>{let{paths:c,text:u,query:l,max_tokens:d,ids:m,model:p,semantic:f,files:g}=i,h=O=>({content:[{type:"text",text:O}],isError:!0});if((c?.length??0)>50)return h(`${c.length} paths; pass at most 50 (a folder counts as one).`);if((m?.length??0)>200)return h(`${m.length} ids; ask for at most 200.`);if(d!==void 0&&d>2e5)return h(`max_tokens ${d}; the most is 200000.`);if(c?.length&&!r)return h("This server runs over HTTP and does not read files. Pass the document as `text`, or attach it (`files`).");let{sources:_,skipped:v}=c?.length?await sx(c):{sources:[],skipped:[]};if(t&&g?.length){let O=await kx(g);_.push(...O.sources),v.push(...O.skipped)}if(u&&_.push({name:"text",text:u}),_.length===0)return h(v.length?`Nothing readable: ${v.join("; ")}`:r?"Pass `paths` (files or folders) or `text`.":"This server runs over HTTP and reads no files from its own disk: pass the user's upload as `files`, or the document as `text`.");let y=await tx(_,{query:l,budget:d,ids:m,model:p,semantic:t?void 0:f}),x=v.length?`
|
|
117
|
+
Skipped: ${v.slice(0,10).join("; ")}${v.length>10?` (+${v.length-10} more)`:""}`:"",$=nx(y)+x;return y.mode!=="outline"?{content:[{type:"text",text:$}]}:Hp(a?._meta,$,()=>{let O=lx(y,$);return{...O,text:O.text+x}})}),n.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."}}]})),n.registerPrompt("handoff",{title:"Hand off to a new chat",description:"Write a short brief of this chat, save it, and continue in a new chat: the only way to cut a long chat's cost.",argsSchema:{focus:Z.string().max(200).optional().describe("What the next chat should work on (optional)")}},async({focus:i})=>({messages:[{role:"user",content:{type:"text",text:`Hand this chat off to a new one. Write a dense brief of at most ${yt.briefTargetTokens} tokens: the goal, decisions made (with the reason in a few words), the current state, open items and the next step, and key identifiers (names, paths, IDs, versions, numbers). Leave out what is finished or no longer needed. Separately, list only the blocks that must stay exact (code, config, commands, figures), each with a short label. Then call save_handoff with the brief, those blocks as \`verbatim\`, a short title, the model you run as, and \`chat_tokens\` if you have a profile_context figure (else \`turns\`). Do not write the brief into this reply before the call. After it, tell me in two lines how to continue, as its result says.`+(i?.trim()?` The next chat will work on: ${i.trim()}`:"")}}]})),n.registerPrompt("ask_file",{title:"Ask a big file",description:"Answer from a big file or folder without reading it whole: pack_context returns only the parts the question needs.",argsSchema:{path:Z.string().max(1e3).describe("Absolute path to the file or folder"),question:Z.string().max(2e3).describe("What you want to know from it")}},async({path:i,question:a})=>({messages:[{role:"user",content:{type:"text",text:`Answer from ${JSON.stringify(i)} without pasting or reading it whole: ${a}
|
|
118
118
|
|
|
119
|
-
Call pack_context with paths [${JSON.stringify(i)}] and the question as \`query\`. Answer from the chunks it returns and cite their ids. If they do not hold the answer, call it again with the ids it names as next best, or with no query for an outline to pick from; do not read the file whole. If pack_context cannot read paths here, ask me to attach or paste the file, and pass it as \`files\` or \`text\`.`}}]})),n.registerTool("save_handoff",{description:`Save a handoff for continuing in a new chat (a chat's history cannot be cut; a new chat can). Write \`brief\` yourself (\u2264${
|
|
120
|
-
`)[0]).text.slice(0,80)}"${y?`, with ${y} verbatim block(s): ${
|
|
121
|
-
`)}]}}),e&&!t){let i="No handoff saved yet. In a long chat, pick the `handoff` prompt (+ menu) or ask for a handoff; the assistant saves it with save_handoff.";n.registerResource("handoff-latest","handoff://latest",{title:"Latest handoff",description:"The newest saved handoff: attach it to a new chat to continue there.",mimeType:"text/markdown"},async a=>({contents:[{uri:a.href,mimeType:"text/markdown",text:
|
|
122
|
-
`)}]})),
|
|
119
|
+
Call pack_context with paths [${JSON.stringify(i)}] and the question as \`query\`. Answer from the chunks it returns and cite their ids. If they do not hold the answer, call it again with the ids it names as next best, or with no query for an outline to pick from; do not read the file whole. If pack_context cannot read paths here, ask me to attach or paste the file, and pass it as \`files\` or \`text\`.`}}]})),n.registerTool("save_handoff",{description:`Save a handoff for continuing in a new chat (a chat's history cannot be cut; a new chat can). Write \`brief\` yourself (\u2264${yt.briefTargetTokens} tokens: goal, decisions, state, open items, identifiers); put what must stay exact in \`verbatim\`. Only when the user agrees.`,inputSchema:{brief:Z.string(),verbatim:Z.array(Z.object({label:Z.string(),text:Z.string()})).optional().describe("Code, config, figures"),title:Z.string().optional(),chat_tokens:Z.number().optional().describe("Chat size, from profile_context"),turns:Z.number().optional(),model:Z.string().optional()},annotations:{title:"Save handoff",readOnlyHint:!e,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},async({brief:i,verbatim:a,title:c,chat_tokens:u,turns:l,model:d})=>{let m={brief:i,verbatim:a,title:c,model:d,chatTokens:u,turns:l},p=$p(m);if(p.length)return{isError:!0,content:[{type:"text",text:`Not saved: ${p.join(" ")}`}]};let f=a;if(e){let y=a?.length??0,x=await Tb(n,`Save a handoff of this chat on this computer (${gt(wp())}) to start a new chat from? "${Pr(c??i.split(`
|
|
120
|
+
`)[0]).text.slice(0,80)}"${y?`, with ${y} verbatim block(s): ${Pr(a.map($=>$.label).join(", ")).text.slice(0,200)}`:""}.`,y?{include_verbatim:{type:"boolean",title:"Include the verbatim blocks",default:!0}}:{});if(x.asked&&!x.ok)return{content:[{type:"text",text:`Not saved: ${x.why}. Do not retry; ask the user in the chat if they still want a handoff.`}]};x.asked&&x.content.include_verbatim===!1&&(f=void 0)}let g;try{g=_x({...m,verbatim:f},{store:e})}catch(y){let x=vx(y.message);return{isError:!0,content:[{type:"text",text:`Not saved: ${t?"the server could not store the handoff":x}.`}]}}let h=g.meta,_=`brief ~${z(h.briefTokens)}${h.blocks.length?`, ${h.blocks.length} verbatim block(s) ~${z(h.blocks.reduce((y,x)=>y+x.tokens,0))}`:""}`,v=[g.dir?`Handoff saved: ${h.id} (~${z(h.tokens)} tokens: ${_}) in ${gt(g.dir)}.`:`Handoff ready (~${z(h.tokens)} tokens: ${_}), not stored: this server runs over HTTP and keeps nothing.`];return h.masked>0&&v.push(`Masked ${h.masked} secret-looking string(s) (${g.maskedKinds.join(", ")}) before saving; the user re-adds them by hand in the new chat if needed.`),h.briefTokens>yt.briefTargetTokens&&v.push(`The brief is ~${h.briefTokens} tokens; the target is \u2264${yt.briefTargetTokens}. It is saved; tighter is cheaper next time.`),v.push(yx(g.math)),g.dir?(v.push(t?"Now print the brief and the verbatim blocks in one fenced block, and tell the user to start a new chat with it as the first message (or, on the machine running this server, `context-doctor handoff latest --copy`). Then stop working in this chat.":"Now tell the user, in two lines: open a new chat and attach the resource handoff://latest (Claude Desktop: + menu, context-doctor), or paste the handoff; `context-doctor handoff latest --copy` copies it. Where attaching is not possible (ChatGPT, the web, phones), print the brief and the verbatim blocks in one fenced block to paste. Then stop working in this chat."),t||n.server.sendResourceListChanged().catch(()=>{})):v.push("Now print the brief and the verbatim blocks in one fenced block, and tell the user to start a new chat with it as the first message. Then stop working in this chat."),{content:[{type:"text",text:v.join(`
|
|
121
|
+
`)}]}}),e&&!t){let i="No handoff saved yet. In a long chat, pick the `handoff` prompt (+ menu) or ask for a handoff; the assistant saves it with save_handoff.";n.registerResource("handoff-latest","handoff://latest",{title:"Latest handoff",description:"The newest saved handoff: attach it to a new chat to continue there.",mimeType:"text/markdown"},async a=>({contents:[{uri:a.href,mimeType:"text/markdown",text:kp("latest")?.markdown??i}]})),n.registerResource("handoff",new Sa("handoff://{id}",{list:async()=>({resources:Fa().slice(0,20).map(a=>({uri:`handoff://${a.id}`,name:a.id,title:a.title,description:`~${z(a.tokens)} tokens, saved ${a.created.slice(0,16).replace("T"," ")} UTC`,mimeType:"text/markdown"}))})}),{title:"Saved handoff",description:"A saved handoff, by id.",mimeType:"text/markdown"},async(a,{id:c})=>{let u=kp(String(Array.isArray(c)?c[0]:c));if(!u)throw new I(A.InvalidParams,`No saved handoff at ${a.href}. List them with resources/list, or run \`context-doctor handoff list\`.`);return{contents:[{uri:a.href,mimeType:"text/markdown",text:u.markdown}]}})}return r&&n.registerTool("recall",{description:"Search this session's transcript on disk (compacted turns, cleared tool output) for `query`: best excerpts with time and position. Use before asking the user again.",inputSchema:{query:Z.string(),max_tokens:Z.number().optional()},annotations:{title:"Recall",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({query:i,max_tokens:a})=>{let c=Zx(process.env,process.cwd(),void 0,{envMayBeStale:!0});if(!c)return{isError:!0,content:[{type:"text",text:"No transcript of this session on disk (Claude Code and Codex keep one; chat apps do not)."}]};let u=Math.min(2e4,Math.max(200,Math.floor(Number(a)||2e3))),l=Dx(c.path,i,{budget:u,how:c.how});return{content:[{type:"text",text:Lx(l)}]}}),n.tool("context_best_practices","Checklist for keeping context lean and prompts cacheable, optionally per provider.",{provider:Z.enum(["general","anthropic","openai"]).optional().describe("Default: general")},{title:"Context best practices",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({provider:i})=>({content:[{type:"text",text:[...zb.general,...i&&i!=="general"?zb[i]:[]].map((c,u)=>`${u+1}. ${c}`).join(`
|
|
122
|
+
`)}]})),rM(n),n}function rM(t){let e=t.server._requestHandlers,r=e?.get("tools/list");!e||!r||e.set("tools/list",async(n,o)=>{let s=await r(n,o);for(let i of s?.tools??[])i.inputSchema&&delete i.inputSchema.$schema;return s})}var zb={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 nM(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 rc=process.argv.slice(2);if(rc.includes("--http")){let t=a=>{let c=rc.indexOf(a);return c>=0?rc[c+1]:void 0},e=Number(t("--port"))>0?Number(t("--port")):8808,r=t("--host")??"127.0.0.1",n=rc.includes("--store-handoffs"),o=Ex(r,t("--allowed-hosts"),t("--allowed-origins")),{createServer:s}=await import("node:http"),{StreamableHTTPServerTransport:i}=await Promise.resolve().then(()=>(Sb(),kb));s(async(a,c)=>{try{if(a.url==="/health"){c.setHeader("content-type","application/json"),c.end(JSON.stringify({ok:!0,service:"context-doctor-mcp"}));return}let u=(a.url??"").split("?")[0];if(u!=="/mcp"&&u!=="/mcp/"){c.statusCode=404,c.end(JSON.stringify({error:"MCP endpoint is /mcp"}));return}let l=(_,v,y)=>{let x=()=>{c.writableEnded||(c.statusCode=_,c.setHeader("content-type","application/json"),(_===413||_===408)&&c.setHeader("connection","close"),c.end(JSON.stringify({jsonrpc:"2.0",error:{code:v,message:y},id:null})),(_===413||_===408)&&setTimeout(()=>a.destroy(),1e3).unref())};if(_===413&&a.headers["content-length"]===void 0&&!a.complete){a.resume();let $=setTimeout(x,5e3);$.unref(),a.once("end",()=>{clearTimeout($),x()}),a.once("error",()=>{clearTimeout($),x()});return}x()},d=zx(o,a.headers);if(d)return l(403,-32e3,`Forbidden: ${d}.`);if(a.method!=="POST"){c.statusCode=405,c.setHeader("allow","POST"),c.end(JSON.stringify({error:"Stateless server: POST /mcp only"}));return}let m=await Rx(a);if(!("value"in m))return l(m.status,m.code,m.message);let p=String(a.headers.accept??""),f=p.includes("text/event-stream");(!f||!p.includes("application/json"))&&nM(a,"accept","application/json, text/event-stream");let g=Eb({http:!0,storeHandoffs:n}),h=new i({sessionIdGenerator:void 0,enableJsonResponse:!f});c.on("close",()=>{h.close(),g.close()}),await g.connect(h),await h.handleRequest(a,c,m.value)}catch(u){c.headersSent||(c.statusCode=500),c.end(JSON.stringify({error:u.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."),console.error(o.hosts==="*"?"Host check off (--allowed-hosts '*').":`Answering Host: ${[...o.hosts].join(", ")}. Behind a tunnel, add its host name: --allowed-hosts <name>.`)})}else{let t=new Ea;await Eb().connect(t)}
|