context-doctor 0.44.0 → 0.46.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 -2
- package/dist/budget.d.ts +14 -1
- package/dist/budget.js +50 -28
- package/dist/cache.js +5 -4
- package/dist/cachemisses.js +6 -4
- package/dist/cacheplan.js +2 -2
- package/dist/cachettl.js +8 -5
- package/dist/ci.js +18 -2
- package/dist/cli.js +27 -6
- package/dist/codexcompact.js +14 -7
- package/dist/coldresume.d.ts +6 -0
- package/dist/coldresume.js +20 -11
- package/dist/compactwindow.js +14 -8
- package/dist/doctor.js +26 -2
- package/dist/extract.d.ts +2 -2
- package/dist/extract.js +14 -3
- package/dist/fanout.js +1 -1
- package/dist/fix.js +14 -10
- package/dist/hook.js +6 -2
- package/dist/httpguard.d.ts +9 -1
- package/dist/httpguard.js +5 -4
- package/dist/lens.js +7 -7
- package/dist/limits.d.ts +14 -5
- package/dist/limits.js +26 -17
- package/dist/mcp.js +62 -62
- package/dist/mcpschema.js +5 -3
- package/dist/mod/api.d.ts +129 -0
- package/dist/mod/api.js +12 -0
- package/dist/mod/logic.d.ts +146 -0
- package/dist/mod/logic.js +222 -0
- package/dist/mod/register.d.ts +58 -0
- package/dist/mod/register.js +237 -0
- package/dist/modelids.d.ts +23 -0
- package/dist/modelids.js +49 -0
- package/dist/modmeasure.d.ts +121 -0
- package/dist/modmeasure.js +298 -0
- package/dist/orgrates.d.ts +75 -0
- package/dist/orgrates.js +165 -0
- package/dist/overhead.js +11 -8
- package/dist/pack.js +95 -22
- package/dist/pricing.d.ts +123 -6
- package/dist/pricing.js +236 -62
- package/dist/proxy.d.ts +12 -1
- package/dist/proxy.js +13 -1
- package/dist/prune.js +55 -3
- package/dist/savings.js +19 -10
- package/dist/scan.d.ts +7 -1
- package/dist/scan.js +19 -1
- package/dist/sessionprice.d.ts +25 -2
- package/dist/sessionprice.js +60 -20
- package/dist/spend.d.ts +62 -10
- package/dist/spend.js +255 -29
- package/dist/statusline.d.ts +10 -2
- package/dist/statusline.js +18 -9
- package/dist/subagentmodel.d.ts +2 -2
- package/dist/subagentmodel.js +31 -24
- package/dist/subagentpay.d.ts +7 -1
- package/dist/subagentpay.js +51 -25
- package/dist/subagents.js +15 -10
- package/dist/tasks.js +9 -6
- package/dist/tooloutput.js +14 -5
- 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 Wb=Object.create;var uc=Object.defineProperty;var Kb=Object.getOwnPropertyDescriptor;var Gb=Object.getOwnPropertyNames;var Xb=Object.getPrototypeOf,Yb=Object.prototype.hasOwnProperty;var X=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),$o=(t,e)=>{for(var r in e)uc(t,r,{get:e[r],enumerable:!0})},Qb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Gb(e))!Yb.call(t,o)&&o!==r&&uc(t,o,{get:()=>e[o],enumerable:!(n=Kb(e,o))||n.enumerable});return t};var lc=(t,e,r)=>(r=t!=null?Wb(Xb(t)):{},Qb(e||!t||!t.__esModule?uc(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 it(t){return t&&Object.assign(Us,t),Us}var u$,l$,er,Us,Nn=X(()=>{u$=Object.freeze({status:"aborted"});l$=Symbol("zod_brand"),er=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Us={}});var ee={};$o(ee,{BIGINT_FORMAT_RANGES:()=>pm,Class:()=>gc,NUMBER_FORMAT_RANGES:()=>$c,aborted:()=>on,allowsEval:()=>xc,assert:()=>h$,assertEqual:()=>d$,assertIs:()=>p$,assertNever:()=>m$,assertNotEqual:()=>f$,assignProp:()=>vc,cached:()=>Ro,captureStackTrace:()=>Bs,cleanEnum:()=>z$,cleanRegex:()=>Io,clone:()=>at,createTransparentProxy:()=>b$,defineLazy:()=>pe,esc:()=>nn,escapeRegex:()=>yr,extend:()=>k$,finalizeIssue:()=>$t,floatSafeRemainder:()=>_c,getElementAtPath:()=>g$,getEnumValues:()=>zo,getLengthableOrigin:()=>Co,getParsedType:()=>x$,getSizableOrigin:()=>mm,isObject:()=>Mn,isPlainObject:()=>jn,issue:()=>kc,joinValues:()=>Hs,jsonStringifyReplacer:()=>yc,merge:()=>S$,normalizeParams:()=>q,nullish:()=>Po,numKeys:()=>v$,omit:()=>$$,optionalKeys:()=>wc,partial:()=>T$,pick:()=>w$,prefixIssues:()=>jt,primitiveTypes:()=>fm,promiseAllObject:()=>y$,propertyKeyTypes:()=>bc,randomString:()=>_$,required:()=>E$,stringifyPrimitive:()=>Vs,unwrapMessage:()=>Eo});function d$(t){return t}function f$(t){return t}function p$(t){}function m$(t){throw new Error}function h$(t){}function zo(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 Hs(t,e="|"){return t.map(r=>Vs(r)).join(e)}function yc(t,e){return typeof e=="bigint"?e.toString():e}function Ro(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Po(t){return t==null}function Io(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function _c(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 pe(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 vc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function g$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function y$(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 _$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function nn(t){return JSON.stringify(t)}function Mn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function jn(t){if(Mn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Mn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function v$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function yr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function at(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function q(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 b$(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 Vs(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function wc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function w$(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 at(t,{...t._zod.def,shape:r,checks:[]})}function $$(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 at(t,{...t._zod.def,shape:r,checks:[]})}function k$(t,e){if(!jn(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 vc(this,"shape",n),n},checks:[]};return at(t,r)}function S$(t,e){return at(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return vc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function T$(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 at(e,{...e._zod.def,shape:o,checks:[]})}function E$(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 at(e,{...e._zod.def,shape:o,checks:[]})}function on(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function jt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Eo(t){return typeof t=="string"?t:t?.message}function $t(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Eo(t.inst?._zod.def?.error?.(t))??Eo(e?.error?.(t))??Eo(r.customError?.(t))??Eo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function mm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Co(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function kc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function z$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Bs,xc,x$,bc,fm,$c,pm,gc,Zt=X(()=>{Bs=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};xc=Ro(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});x$=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}`)}},bc=new Set(["string","number","symbol"]),fm=new Set(["string","number","bigint","boolean","symbol","undefined"]);$c={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]},pm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};gc=class{constructor(...e){}}});function Sc(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 Tc(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 hm,Js,Ao,Ec=X(()=>{Nn();Zt();hm=(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,yc,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Js=w("$ZodError",hm),Ao=w("$ZodError",hm,{Parent:Error})});var zc,Rc,Pc,Ic,Cc,sn,Ac,an,Oc=X(()=>{Nn();Ec();Zt();zc=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 er;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>$t(c,s,it())));throw Bs(a,o?.callee),a}return i.value},Rc=zc(Ao),Pc=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=>$t(c,s,it())));throw Bs(a,o?.callee),a}return i.value},Ic=Pc(Ao),Cc=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 er;return s.issues.length?{success:!1,error:new(t??Js)(s.issues.map(i=>$t(i,o,it())))}:{success:!0,data:s.value}},sn=Cc(Ao),Ac=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=>$t(i,o,it())))}:{success:!0,data:s.value}},an=Ac(Ao)});function Sm(){return new RegExp(P$,"u")}function Nm(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 Mm(t){return new RegExp(`^${Nm(t)}$`)}function jm(t){let e=Nm({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(`^${Am}T(?:${n})$`)}var gm,ym,_m,vm,xm,bm,wm,$m,Nc,km,P$,Tm,Em,zm,Rm,Pm,Mc,Im,Cm,Am,Om,Zm,Dm,Lm,qm,Fm,Um,Hm,Ks=X(()=>{gm=/^[cC][^\s-]{8,}$/,ym=/^[0-9a-z]+$/,_m=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,vm=/^[0-9a-vA-V]{20}$/,xm=/^[A-Za-z0-9]{27}$/,bm=/^[a-zA-Z0-9_-]{21}$/,wm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,$m=/^([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})$/,Nc=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)$/,km=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,P$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Tm=/^(?:(?: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])$/,Em=/^(([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})$/,zm=/^((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])$/,Rm=/^(([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])$/,Pm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Mc=/^[A-Za-z0-9_-]*$/,Im=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Cm=/^\+(?:[0-9]){6,14}[0-9]$/,Am="(?:(?:\\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])))",Om=new RegExp(`^${Am}$`);Zm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Dm=/^\d+$/,Lm=/^-?\d+(?:\.\d+)?/i,qm=/true|false/i,Fm=/null/i,Um=/^[^A-Z]*$/,Hm=/^[^a-z]*$/});var Ie,Bm,jc,Zc,Vm,Jm,Wm,Km,Gm,Oo,Xm,Ym,Qm,eh,th,rh,nh,Gs=X(()=>{Nn();Ks();Zt();Ie=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Bm={number:"number",bigint:"bigint",object:"date"},jc=w("$ZodCheckLessThan",(t,e)=>{Ie.init(t,e);let r=Bm[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})}}),Zc=w("$ZodCheckGreaterThan",(t,e)=>{Ie.init(t,e);let r=Bm[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})}}),Vm=w("$ZodCheckMultipleOf",(t,e)=>{Ie.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):_c(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})}}),Jm=w("$ZodCheckNumberFormat",(t,e)=>{Ie.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=$c[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=Dm)}),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})}}),Wm=w("$ZodCheckMaxLength",(t,e)=>{var r;Ie.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Po(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=Co(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Km=w("$ZodCheckMinLength",(t,e)=>{var r;Ie.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Po(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=Co(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Gm=w("$ZodCheckLengthEquals",(t,e)=>{var r;Ie.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Po(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=Co(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})}}),Oo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Ie.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=()=>{})}),Xm=w("$ZodCheckRegex",(t,e)=>{Oo.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})}}),Ym=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Um),Oo.init(t,e)}),Qm=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Hm),Oo.init(t,e)}),eh=w("$ZodCheckIncludes",(t,e)=>{Ie.init(t,e);let r=yr(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})}}),th=w("$ZodCheckStartsWith",(t,e)=>{Ie.init(t,e);let r=new RegExp(`^${yr(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})}}),rh=w("$ZodCheckEndsWith",(t,e)=>{Ie.init(t,e);let r=new RegExp(`.*${yr(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})}}),nh=w("$ZodCheckOverwrite",(t,e)=>{Ie.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Xs,Dc=X(()=>{Xs=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 aw=Object.create;var pc=Object.defineProperty;var cw=Object.getOwnPropertyDescriptor;var uw=Object.getOwnPropertyNames;var lw=Object.getPrototypeOf,dw=Object.prototype.hasOwnProperty;var Q=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),To=(t,e)=>{for(var r in e)pc(t,r,{get:e[r],enumerable:!0})},fw=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of uw(e))!dw.call(t,o)&&o!==r&&pc(t,o,{get:()=>e[o],enumerable:!(n=cw(e,o))||n.enumerable});return t};var mc=(t,e,r)=>(r=t!=null?aw(lw(t)):{},fw(e||!t||!t.__esModule?pc(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 at(t){return t&&Object.assign(Vs,t),Vs}var w$,$$,nr,Vs,Dn=Q(()=>{w$=Object.freeze({status:"aborted"});$$=Symbol("zod_brand"),nr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Vs={}});var re={};To(re,{BIGINT_FORMAT_RANGES:()=>wm,Class:()=>xc,NUMBER_FORMAT_RANGES:()=>Ec,aborted:()=>cn,allowsEval:()=>kc,assert:()=>z$,assertEqual:()=>k$,assertIs:()=>T$,assertNever:()=>E$,assertNotEqual:()=>S$,assignProp:()=>$c,cached:()=>Oo,captureStackTrace:()=>Ws,cleanEnum:()=>q$,cleanRegex:()=>Io,clone:()=>ct,createTransparentProxy:()=>I$,defineLazy:()=>me,esc:()=>an,escapeRegex:()=>xr,extend:()=>j$,finalizeIssue:()=>St,floatSafeRemainder:()=>wc,getElementAtPath:()=>R$,getEnumValues:()=>Co,getLengthableOrigin:()=>No,getParsedType:()=>A$,getSizableOrigin:()=>$m,isObject:()=>Ln,isPlainObject:()=>qn,issue:()=>zc,joinValues:()=>Js,jsonStringifyReplacer:()=>bc,merge:()=>Z$,normalizeParams:()=>q,nullish:()=>Ao,numKeys:()=>O$,omit:()=>M$,optionalKeys:()=>Tc,partial:()=>D$,pick:()=>N$,prefixIssues:()=>qt,primitiveTypes:()=>bm,promiseAllObject:()=>P$,propertyKeyTypes:()=>Sc,randomString:()=>C$,required:()=>L$,stringifyPrimitive:()=>Gs,unwrapMessage:()=>Po});function k$(t){return t}function S$(t){return t}function T$(t){}function E$(t){throw new Error}function z$(t){}function Co(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 Js(t,e="|"){return t.map(r=>Gs(r)).join(e)}function bc(t,e){return typeof e=="bigint"?e.toString():e}function Oo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ao(t){return t==null}function Io(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function wc(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 me(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 $c(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function R$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function P$(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 C$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function an(t){return JSON.stringify(t)}function Ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qn(t){if(Ln(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ln(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function O$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function xr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ct(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function q(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 I$(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Gs(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Tc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function N$(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 ct(t,{...t._zod.def,shape:r,checks:[]})}function M$(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 ct(t,{...t._zod.def,shape:r,checks:[]})}function j$(t,e){if(!qn(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 $c(this,"shape",n),n},checks:[]};return ct(t,r)}function Z$(t,e){return ct(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return $c(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function D$(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 ct(e,{...e._zod.def,shape:o,checks:[]})}function L$(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 ct(e,{...e._zod.def,shape:o,checks:[]})}function cn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function qt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Po(t){return typeof t=="string"?t:t?.message}function St(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Po(t.inst?._zod.def?.error?.(t))??Po(e?.error?.(t))??Po(r.customError?.(t))??Po(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function $m(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function No(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function zc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function q$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ws,kc,A$,Sc,bm,Ec,wm,xc,Ut=Q(()=>{Ws=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};kc=Oo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});A$=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}`)}},Sc=new Set(["string","number","symbol"]),bm=new Set(["string","number","bigint","boolean","symbol","undefined"]);Ec={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]},wm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};xc=class{constructor(...e){}}});function Rc(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 Pc(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 km,Ks,Mo,Cc=Q(()=>{Dn();Ut();km=(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,bc,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ks=w("$ZodError",km),Mo=w("$ZodError",km,{Parent:Error})});var Oc,Ac,Ic,Nc,Mc,un,jc,ln,Zc=Q(()=>{Dn();Cc();Ut();Oc=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 nr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>St(c,s,at())));throw Ws(a,o?.callee),a}return i.value},Ac=Oc(Mo),Ic=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=>St(c,s,at())));throw Ws(a,o?.callee),a}return i.value},Nc=Ic(Mo),Mc=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 nr;return s.issues.length?{success:!1,error:new(t??Ks)(s.issues.map(i=>St(i,o,at())))}:{success:!0,data:s.value}},un=Mc(Mo),jc=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=>St(i,o,at())))}:{success:!0,data:s.value}},ln=jc(Mo)});function Im(){return new RegExp(F$,"u")}function Hm(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 Bm(t){return new RegExp(`^${Hm(t)}$`)}function Vm(t){let e=Hm({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(`^${Um}T(?:${n})$`)}var Sm,Tm,Em,zm,Rm,Pm,Cm,Om,Dc,Am,F$,Nm,Mm,jm,Zm,Dm,Lc,Lm,qm,Um,Fm,Jm,Wm,Gm,Km,Xm,Ym,Qm,Ys=Q(()=>{Sm=/^[cC][^\s-]{8,}$/,Tm=/^[0-9a-z]+$/,Em=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,zm=/^[0-9a-vA-V]{20}$/,Rm=/^[A-Za-z0-9]{27}$/,Pm=/^[a-zA-Z0-9_-]{21}$/,Cm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Om=/^([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})$/,Dc=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)$/,Am=/^(?!\.)(?!.*\.\.)([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})+$";Nm=/^(?:(?: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})$/,jm=/^((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])$/,Zm=/^(([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])$/,Dm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Lc=/^[A-Za-z0-9_-]*$/,Lm=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,qm=/^\+(?:[0-9]){6,14}[0-9]$/,Um="(?:(?:\\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])))",Fm=new RegExp(`^${Um}$`);Jm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Wm=/^\d+$/,Gm=/^-?\d+(?:\.\d+)?/i,Km=/true|false/i,Xm=/null/i,Ym=/^[^A-Z]*$/,Qm=/^[^a-z]*$/});var Ae,eh,qc,Uc,th,rh,nh,oh,sh,jo,ih,ah,ch,uh,lh,dh,fh,Qs=Q(()=>{Dn();Ys();Ut();Ae=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),eh={number:"number",bigint:"bigint",object:"date"},qc=w("$ZodCheckLessThan",(t,e)=>{Ae.init(t,e);let r=eh[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})}}),Uc=w("$ZodCheckGreaterThan",(t,e)=>{Ae.init(t,e);let r=eh[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})}}),th=w("$ZodCheckMultipleOf",(t,e)=>{Ae.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):wc(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})}}),rh=w("$ZodCheckNumberFormat",(t,e)=>{Ae.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Ec[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=Wm)}),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})}}),nh=w("$ZodCheckMaxLength",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=No(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),oh=w("$ZodCheckMinLength",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=No(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),sh=w("$ZodCheckLengthEquals",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=No(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),jo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Ae.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=()=>{})}),ih=w("$ZodCheckRegex",(t,e)=>{jo.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})}}),ah=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ym),jo.init(t,e)}),ch=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Qm),jo.init(t,e)}),uh=w("$ZodCheckIncludes",(t,e)=>{Ae.init(t,e);let r=xr(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})}}),lh=w("$ZodCheckStartsWith",(t,e)=>{Ae.init(t,e);let r=new RegExp(`^${xr(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})}}),dh=w("$ZodCheckEndsWith",(t,e)=>{Ae.init(t,e);let r=new RegExp(`.*${xr(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})}}),fh=w("$ZodCheckOverwrite",(t,e)=>{Ae.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ei,Fc=Q(()=>{ei=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 mh,Hc=Q(()=>{mh={major:4,minor:0,patch:0}});function zh(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function H$(t){if(!Lc.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return zh(r)}function B$(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 hh(t,e,r){t.issues.length&&e.issues.push(...qt(r,t.issues)),e.value[r]=t.value}function ti(t,e,r){t.issues.length&&e.issues.push(...qt(r,t.issues)),e.value[r]=t.value}function gh(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(...qt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function yh(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=>St(s,n,at())))}),e}function Bc(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(qn(t)&&qn(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=Bc(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=Bc(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 _h(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),cn(t))return t;let n=Bc(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 vh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function xh(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 bh(t,e,r){return cn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function wh(t){return t.value=Object.freeze(t.value),t}function $h(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(zc(o))}}var de,Zo,he,Vc,Jc,Wc,Gc,Kc,Xc,Yc,Qc,eu,tu,ru,kh,Sh,Th,Eh,nu,ou,su,iu,au,cu,uu,lu,ri,du,fu,pu,mu,hu,gu,ni,oi,yu,_u,vu,xu,bu,wu,$u,ku,Su,Tu,Eu,zu,Ru,Pu,Cu,Rh=Q(()=>{Qs();Dn();Fc();Zc();Ys();Ut();Hc();Ut();de=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=mh;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=cn(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 nr;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==d&&(c||(c=cn(s,d)))});else{if(s.issues.length===d)continue;c||(c=cn(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 nr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=un(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ln(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Zo=w("$ZodString",(t,e)=>{de.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Jm(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}}),he=w("$ZodStringFormat",(t,e)=>{jo.init(t,e),Zo.init(t,e)}),Vc=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Om),he.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=Dc(n))}else e.pattern??(e.pattern=Dc());he.init(t,e)}),Wc=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Am),he.init(t,e)}),Gc=w("$ZodURL",(t,e)=>{he.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:Lm.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})}}}),Kc=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Im()),he.init(t,e)}),Xc=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Pm),he.init(t,e)}),Yc=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Sm),he.init(t,e)}),Qc=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Tm),he.init(t,e)}),eu=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Em),he.init(t,e)}),tu=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=zm),he.init(t,e)}),ru=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Rm),he.init(t,e)}),kh=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Vm(e)),he.init(t,e)}),Sh=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Fm),he.init(t,e)}),Th=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Bm(e)),he.init(t,e)}),Eh=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Cm),he.init(t,e)}),nu=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Nm),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),ou=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Mm),he.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})}}}),su=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=jm),he.init(t,e)}),iu=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Zm),he.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})}}});au=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Dm),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{zh(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});cu=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Lc),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{H$(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),uu=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=qm),he.init(t,e)});lu=w("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{B$(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),ri=w("$ZodNumber",(t,e)=>{de.init(t,e),t._zod.pattern=t._zod.bag.pattern??Gm,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}}),du=w("$ZodNumber",(t,e)=>{rh.init(t,e),ri.init(t,e)}),fu=w("$ZodBoolean",(t,e)=>{de.init(t,e),t._zod.pattern=Km,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}}),pu=w("$ZodNull",(t,e)=>{de.init(t,e),t._zod.pattern=Xm,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}}),mu=w("$ZodUnknown",(t,e)=>{de.init(t,e),t._zod.parse=r=>r}),hu=w("$ZodNever",(t,e)=>{de.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});gu=w("$ZodArray",(t,e)=>{de.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=>hh(u,r,i))):hh(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});ni=w("$ZodObject",(t,e)=>{de.init(t,e);let r=Oo(()=>{let d=Object.keys(e.shape);for(let p of d)if(!(e.shape[p]instanceof de))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let m=Tc(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(m)}});me(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 h of f.values)m[p].add(h)}}return m});let n=d=>{let m=new ei(["shape","payload","ctx"]),p=r.value,f=v=>{let y=an(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};m.write("const input = payload.value;");let h=Object.create(null),g=0;for(let v of p.keys)h[v]=`key_${g++}`;m.write("const newResult = {}");for(let v of p.keys)if(p.optionalKeys.has(v)){let y=h[v];m.write(`const ${y} = ${f(v)};`);let x=an(v);m.write(`
|
|
6
6
|
if (${y}.issues.length) {
|
|
7
7
|
if (input[${x}] === undefined) {
|
|
8
8
|
if (${x} in input) {
|
|
@@ -21,21 +21,21 @@ var Wb=Object.create;var uc=Object.defineProperty;var Kb=Object.getOwnPropertyDe
|
|
|
21
21
|
} else {
|
|
22
22
|
newResult[${x}] = ${y}.value;
|
|
23
23
|
}
|
|
24
|
-
`)}else{let y=
|
|
24
|
+
`)}else{let y=h[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[${nn(v)}] = ${y}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let _=m.compile();return(v,y)=>_(d,v,y)},o,s=Mn,i=!Us.jitless,c=i&&xc.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],N=$._zod.run({value:p[x],issues:[]},m),A=$._zod.optin==="optional"&&$._zod.optout==="optional";N instanceof Promise?f.push(N.then(ce=>A?ah(ce,d,x,p):Ys(ce,d,x))):A?ah(N,d,x,p):Ys(N,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($=>Ys($,d,y))):Ys(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}});ti=w("$ZodUnion",(t,e)=>{le.init(t,e),pe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),pe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),pe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),pe(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=>Io(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=>ch(i,r,t,n)):ch(s,r,t,n)}}),pu=w("$ZodDiscriminatedUnion",(t,e)=>{ti.init(t,e);let r=t._zod.parse;pe(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=Ro(()=>{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(!Mn(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)}}),mu=w("$ZodIntersection",(t,e)=>{le.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])=>uh(r,c,u)):uh(r,s,i)}});hu=w("$ZodRecord",(t,e)=>{le.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!jn(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(...jt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...jt(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=>$t(u,n,it())),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(...jt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...jt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),gu=w("$ZodEnum",(t,e)=>{le.init(t,e);let r=zo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>bc.has(typeof n)).map(n=>typeof n=="string"?yr(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}}),yu=w("$ZodLiteral",(t,e)=>{le.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?yr(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}}),_u=w("$ZodTransform",(t,e)=>{le.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 er;return r.value=o,r}}),vu=w("$ZodOptional",(t,e)=>{le.init(t,e),t._zod.optin="optional",t._zod.optout="optional",pe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Io(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)}),xu=w("$ZodNullable",(t,e)=>{le.init(t,e),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Io(r.source)}|null)$`):void 0}),pe(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)}),bu=w("$ZodDefault",(t,e)=>{le.init(t,e),t._zod.optin="optional",pe(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=>lh(s,e)):lh(o,e)}});wu=w("$ZodPrefault",(t,e)=>{le.init(t,e),t._zod.optin="optional",pe(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))}),$u=w("$ZodNonOptional",(t,e)=>{le.init(t,e),pe(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=>dh(s,t)):dh(o,t)}});ku=w("$ZodCatch",(t,e)=>{le.init(t,e),t._zod.optin="optional",pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(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=>$t(i,n,it()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>$t(s,n,it()))},input:r.value}),r.issues=[]),r)}}),Su=w("$ZodPipe",(t,e)=>{le.init(t,e),pe(t._zod,"values",()=>e.in._zod.values),pe(t._zod,"optin",()=>e.in._zod.optin),pe(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=>fh(s,e,n)):fh(o,e,n)}});Tu=w("$ZodReadonly",(t,e)=>{le.init(t,e),pe(t._zod,"propValues",()=>e.innerType._zod.propValues),pe(t._zod,"values",()=>e.innerType._zod.values),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(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(ph):ph(o)}});Eu=w("$ZodCustom",(t,e)=>{Ie.init(t,e),le.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=>mh(s,r,n,t));mh(o,r,n,t)}})});function bh(){return{localeError:O$()}}var A$,O$,wh=X(()=>{Zt();A$=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},O$=()=>{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 ${A$(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Vs(n.values[0])}`:`Invalid option: expected one of ${Hs(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":""}: ${Hs(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 ri=X(()=>{});function $h(){return new Mo}var N$,M$,Mo,_r,Ru=X(()=>{N$=Symbol("ZodOutput"),M$=Symbol("ZodInput"),Mo=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};_r=$h()});function Pu(t,e){return new t({type:"string",...q(e)})}function Iu(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...q(e)})}function ni(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...q(e)})}function Cu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...q(e)})}function Au(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(e)})}function Ou(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(e)})}function Nu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(e)})}function Mu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...q(e)})}function ju(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...q(e)})}function Zu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(e)})}function Du(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...q(e)})}function Lu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(e)})}function qu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...q(e)})}function Fu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...q(e)})}function Uu(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(e)})}function Hu(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(e)})}function Bu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(e)})}function Vu(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(e)})}function Ju(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(e)})}function Wu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...q(e)})}function Ku(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...q(e)})}function Gu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...q(e)})}function Xu(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...q(e)})}function kh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(e)})}function Sh(t,e){return new t({type:"string",format:"date",check:"string_format",...q(e)})}function Th(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...q(e)})}function Eh(t,e){return new t({type:"string",format:"duration",check:"string_format",...q(e)})}function Yu(t,e){return new t({type:"number",checks:[],...q(e)})}function Qu(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...q(e)})}function el(t,e){return new t({type:"boolean",...q(e)})}function tl(t,e){return new t({type:"null",...q(e)})}function rl(t){return new t({type:"unknown"})}function nl(t,e){return new t({type:"never",...q(e)})}function oi(t,e){return new jc({check:"less_than",...q(e),value:t,inclusive:!1})}function jo(t,e){return new jc({check:"less_than",...q(e),value:t,inclusive:!0})}function si(t,e){return new Zc({check:"greater_than",...q(e),value:t,inclusive:!1})}function Zo(t,e){return new Zc({check:"greater_than",...q(e),value:t,inclusive:!0})}function ii(t,e){return new Vm({check:"multiple_of",...q(e),value:t})}function ai(t,e){return new Wm({check:"max_length",...q(e),maximum:t})}function Zn(t,e){return new Km({check:"min_length",...q(e),minimum:t})}function ci(t,e){return new Gm({check:"length_equals",...q(e),length:t})}function ol(t,e){return new Xm({check:"string_format",format:"regex",...q(e),pattern:t})}function sl(t){return new Ym({check:"string_format",format:"lowercase",...q(t)})}function il(t){return new Qm({check:"string_format",format:"uppercase",...q(t)})}function al(t,e){return new eh({check:"string_format",format:"includes",...q(e),includes:t})}function cl(t,e){return new th({check:"string_format",format:"starts_with",...q(e),prefix:t})}function ul(t,e){return new rh({check:"string_format",format:"ends_with",...q(e),suffix:t})}function cn(t){return new nh({check:"overwrite",tx:t})}function ll(t){return cn(e=>e.normalize(t))}function dl(){return cn(t=>t.trim())}function fl(){return cn(t=>t.toLowerCase())}function pl(){return cn(t=>t.toUpperCase())}function zh(t,e,r){return new t({type:"array",element:e,...q(r)})}function ml(t,e,r){let n=q(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function hl(t,e,r){return new t({type:"custom",check:"custom",fn:e,...q(r)})}var Rh=X(()=>{Gs();Zt()});var Ph=X(()=>{});function gl(t,e){if(t instanceof Mo){let n=new ui(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 ui(e);return r.process(t),r.emit(t,e)}function Te(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 Te(o.element,r);case"object":{for(let s in o.shape)if(Te(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Te(s,r))return!0;return!1}case"intersection":return Te(o.left,r)||Te(o.right,r);case"tuple":{for(let s of o.items)if(Te(s,r))return!0;return!!(o.rest&&Te(o.rest,r))}case"record":return Te(o.keyType,r)||Te(o.valueType,r);case"map":return Te(o.keyType,r)||Te(o.valueType,r);case"set":return Te(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Te(o.innerType,r);case"lazy":return Te(o.getter(),r);case"default":return Te(o.innerType,r);case"prefault":return Te(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Te(o.in,r)||Te(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var ui,Ih=X(()=>{Ru();Zt();ui=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??_r,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=zo(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"&&Te(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 ? [${an(v)}, ...iss.path] : [${an(v)}]
|
|
28
|
+
})));`),m.write(`newResult[${an(v)}] = ${y}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let _=m.compile();return(v,y)=>_(d,v,y)},o,s=Ln,i=!Vs.jitless,c=i&&kc.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],I=$._zod.run({value:p[x],issues:[]},m),U=$._zod.optin==="optional"&&$._zod.optout==="optional";I instanceof Promise?f.push(I.then(H=>U?gh(H,d,x,p):ti(H,d,x))):U?gh(I,d,x,p):ti(I,d,x)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let h=[],g=l.keySet,_=u._zod,v=_.def.type;for(let y of Object.keys(p)){if(g.has(y))continue;if(v==="never"){h.push(y);continue}let x=_.run({value:p[y],issues:[]},m);x instanceof Promise?f.push(x.then($=>ti($,d,y))):ti(x,d,y)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:t}),f.length?Promise.all(f).then(()=>d):d}});oi=w("$ZodUnion",(t,e)=>{de.init(t,e),me(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),me(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),me(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),me(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=>Io(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=>yh(i,r,t,n)):yh(s,r,t,n)}}),yu=w("$ZodDiscriminatedUnion",(t,e)=>{oi.init(t,e);let r=t._zod.parse;me(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=Oo(()=>{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(!Ln(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)}}),_u=w("$ZodIntersection",(t,e)=>{de.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])=>_h(r,c,u)):_h(r,s,i)}});vu=w("$ZodRecord",(t,e)=>{de.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!qn(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(...qt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...qt(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=>St(u,n,at())),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(...qt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...qt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),xu=w("$ZodEnum",(t,e)=>{de.init(t,e);let r=Co(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Sc.has(typeof n)).map(n=>typeof n=="string"?xr(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}}),bu=w("$ZodLiteral",(t,e)=>{de.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?xr(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}}),wu=w("$ZodTransform",(t,e)=>{de.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 nr;return r.value=o,r}}),$u=w("$ZodOptional",(t,e)=>{de.init(t,e),t._zod.optin="optional",t._zod.optout="optional",me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Io(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)}),ku=w("$ZodNullable",(t,e)=>{de.init(t,e),me(t._zod,"optin",()=>e.innerType._zod.optin),me(t._zod,"optout",()=>e.innerType._zod.optout),me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Io(r.source)}|null)$`):void 0}),me(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)}),Su=w("$ZodDefault",(t,e)=>{de.init(t,e),t._zod.optin="optional",me(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=>vh(s,e)):vh(o,e)}});Tu=w("$ZodPrefault",(t,e)=>{de.init(t,e),t._zod.optin="optional",me(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))}),Eu=w("$ZodNonOptional",(t,e)=>{de.init(t,e),me(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=>xh(s,t)):xh(o,t)}});zu=w("$ZodCatch",(t,e)=>{de.init(t,e),t._zod.optin="optional",me(t._zod,"optout",()=>e.innerType._zod.optout),me(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=>St(i,n,at()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>St(s,n,at()))},input:r.value}),r.issues=[]),r)}}),Ru=w("$ZodPipe",(t,e)=>{de.init(t,e),me(t._zod,"values",()=>e.in._zod.values),me(t._zod,"optin",()=>e.in._zod.optin),me(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=>bh(s,e,n)):bh(o,e,n)}});Pu=w("$ZodReadonly",(t,e)=>{de.init(t,e),me(t._zod,"propValues",()=>e.innerType._zod.propValues),me(t._zod,"values",()=>e.innerType._zod.values),me(t._zod,"optin",()=>e.innerType._zod.optin),me(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(wh):wh(o)}});Cu=w("$ZodCustom",(t,e)=>{Ae.init(t,e),de.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=>$h(s,r,n,t));$h(o,r,n,t)}})});function Ph(){return{localeError:J$()}}var V$,J$,Ch=Q(()=>{Ut();V$=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},J$=()=>{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 ${V$(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Gs(n.values[0])}`:`Invalid option: expected one of ${Js(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":""}: ${Js(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 si=Q(()=>{});function Oh(){return new Do}var W$,G$,Do,br,Au=Q(()=>{W$=Symbol("ZodOutput"),G$=Symbol("ZodInput"),Do=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)}};br=Oh()});function Iu(t,e){return new t({type:"string",...q(e)})}function Nu(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...q(e)})}function ii(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...q(e)})}function Mu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...q(e)})}function ju(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(e)})}function Zu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(e)})}function Du(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(e)})}function Lu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...q(e)})}function qu(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...q(e)})}function Uu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(e)})}function Fu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...q(e)})}function Hu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(e)})}function Bu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...q(e)})}function Vu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...q(e)})}function Ju(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(e)})}function Wu(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(e)})}function Gu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(e)})}function Ku(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(e)})}function Xu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(e)})}function Yu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...q(e)})}function Qu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...q(e)})}function el(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...q(e)})}function tl(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...q(e)})}function Ah(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(e)})}function Ih(t,e){return new t({type:"string",format:"date",check:"string_format",...q(e)})}function Nh(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...q(e)})}function Mh(t,e){return new t({type:"string",format:"duration",check:"string_format",...q(e)})}function rl(t,e){return new t({type:"number",checks:[],...q(e)})}function nl(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...q(e)})}function ol(t,e){return new t({type:"boolean",...q(e)})}function sl(t,e){return new t({type:"null",...q(e)})}function il(t){return new t({type:"unknown"})}function al(t,e){return new t({type:"never",...q(e)})}function ai(t,e){return new qc({check:"less_than",...q(e),value:t,inclusive:!1})}function Lo(t,e){return new qc({check:"less_than",...q(e),value:t,inclusive:!0})}function ci(t,e){return new Uc({check:"greater_than",...q(e),value:t,inclusive:!1})}function qo(t,e){return new Uc({check:"greater_than",...q(e),value:t,inclusive:!0})}function ui(t,e){return new th({check:"multiple_of",...q(e),value:t})}function li(t,e){return new nh({check:"max_length",...q(e),maximum:t})}function Un(t,e){return new oh({check:"min_length",...q(e),minimum:t})}function di(t,e){return new sh({check:"length_equals",...q(e),length:t})}function cl(t,e){return new ih({check:"string_format",format:"regex",...q(e),pattern:t})}function ul(t){return new ah({check:"string_format",format:"lowercase",...q(t)})}function ll(t){return new ch({check:"string_format",format:"uppercase",...q(t)})}function dl(t,e){return new uh({check:"string_format",format:"includes",...q(e),includes:t})}function fl(t,e){return new lh({check:"string_format",format:"starts_with",...q(e),prefix:t})}function pl(t,e){return new dh({check:"string_format",format:"ends_with",...q(e),suffix:t})}function dn(t){return new fh({check:"overwrite",tx:t})}function ml(t){return dn(e=>e.normalize(t))}function hl(){return dn(t=>t.trim())}function gl(){return dn(t=>t.toLowerCase())}function yl(){return dn(t=>t.toUpperCase())}function jh(t,e,r){return new t({type:"array",element:e,...q(r)})}function _l(t,e,r){let n=q(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function vl(t,e,r){return new t({type:"custom",check:"custom",fn:e,...q(r)})}var Zh=Q(()=>{Qs();Ut()});var Dh=Q(()=>{});function xl(t,e){if(t instanceof Do){let n=new fi(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 fi(e);return r.process(t),r.emit(t,e)}function Ee(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 Ee(o.element,r);case"object":{for(let s in o.shape)if(Ee(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ee(s,r))return!0;return!1}case"intersection":return Ee(o.left,r)||Ee(o.right,r);case"tuple":{for(let s of o.items)if(Ee(s,r))return!0;return!!(o.rest&&Ee(o.rest,r))}case"record":return Ee(o.keyType,r)||Ee(o.valueType,r);case"map":return Ee(o.keyType,r)||Ee(o.valueType,r);case"set":return Ee(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ee(o.innerType,r);case"lazy":return Ee(o.getter(),r);case"default":return Ee(o.innerType,r);case"prefault":return Ee(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ee(o.in,r)||Ee(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var fi,Lh=Q(()=>{Au();Ut();fi=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??br,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},m=e._zod.parent;if(m)a.ref=m,this.process(m,d),this.seen.get(m).isParent=!0;else{let p=a.schema;switch(o.type){case"string":{let f=p;f.type="string";let{minimum:h,maximum:g,format:_,patterns:v,contentEncoding:y}=e._zod.bag;if(typeof h=="number"&&(f.minLength=h),typeof g=="number"&&(f.maxLength=g),_&&(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:h,maximum:g,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 h=="number"&&(f.minimum=h,typeof x=="number"&&(x>=h?delete f.minimum:delete f.exclusiveMinimum)),typeof y=="number"&&(f.exclusiveMaximum=y),typeof g=="number"&&(f.maximum=g,typeof y=="number"&&(y<=g?delete f.maximum:delete f.exclusiveMaximum)),typeof v=="number"&&(f.multipleOf=v);break}case"boolean":{let f=p;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{p.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=p,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof g=="number"&&(f.maxItems=g),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=p;f.type="object",f.properties={};let h=o.shape;for(let v in h)f.properties[v]=this.process(h[v],{...d,path:[...d.path,"properties",v]});let g=new Set(Object.keys(h)),_=new Set([...g].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((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let f=p,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),_=y=>"allOf"in y&&Object.keys(y).length===1,v=[..._(h)?h.allOf:[h],..._(g)?g.allOf:[g]];f.allOf=v;break}case"tuple":{let f=p;f.type="array";let h=o.items.map((v,y)=>this.process(v,{...d,path:[...d.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?f.prefixItems=h:f.items=h,o.rest){let v=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=v:f.additionalItems=v}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:_}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof _=="number"&&(f.maxItems=_);break}case"record":{let f=p;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=p,h=Co(o.entries);h.every(g=>typeof g=="number")&&(f.type="number"),h.every(g=>typeof g=="string")&&(f.type="string"),f.enum=h;break}case"literal":{let f=p,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];f.type=g===null?"null":typeof g,f.const=g}else h.every(g=>typeof g=="number")&&(f.type="number"),h.every(g=>typeof g=="string")&&(f.type="string"),h.every(g=>typeof g=="boolean")&&(f.type="string"),h.every(g=>g===null)&&(f.type="null"),f.enum=h;break}case"file":{let f=p,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:_,mime:v}=e._zod.bag;g!==void 0&&(h.minLength=g),_!==void 0&&(h.maxLength=_),v?v.length===1?(h.contentMediaType=v[0],Object.assign(f,h)):f.anyOf=v.map(y=>({...h,contentMediaType:y})):Object.assign(f,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);p.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=p;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,p.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(p._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}p.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=p,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=h.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,p.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Ee(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,g=n.external.uri??(v=>v);if(h)return{ref:g(h)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${g("__shared")}#/${d}/${_}`}}if(l[1]===o)return{ref:"#"};let p=`#/${d}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:p+f}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:m,defId:p}=s(l);d.def={...d.schema},p&&(d.defId=p);let f=d.schema;for(let h in f)delete f[h];f.$ref=m};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
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 Ch=X(()=>{});var Ue=X(()=>{Nn();Oc();Ec();xh();Gs();Lc();Zt();Ks();ri();Ru();Dc();Ph();Rh();Ih();Ch()});var _l=X(()=>{Ue()});var Do={};$o(Do,{ZodISODate:()=>Mh,ZodISODateTime:()=>Nh,ZodISODuration:()=>Zh,ZodISOTime:()=>jh,date:()=>xl,datetime:()=>vl,duration:()=>wl,time:()=>bl});function vl(t){return kh(Nh,t)}function xl(t){return Sh(Mh,t)}function bl(t){return Th(jh,t)}function wl(t){return Eh(Zh,t)}var Nh,Mh,jh,Zh,$l=X(()=>{Ue();kl();Nh=w("ZodISODateTime",(t,e)=>{hh.init(t,e),xe.init(t,e)});Mh=w("ZodISODate",(t,e)=>{gh.init(t,e),xe.init(t,e)});jh=w("ZodISOTime",(t,e)=>{yh.init(t,e),xe.init(t,e)});Zh=w("ZodISODuration",(t,e)=>{_h.init(t,e),xe.init(t,e)})});var Dh,oZ,Lo,Sl=X(()=>{Ue();Ue();Dh=(t,e)=>{Js.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Tc(t,r)},flatten:{value:r=>Sc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},oZ=w("ZodError",Dh),Lo=w("ZodError",Dh,{Parent:Error})});var Lh,qh,Fh,Uh,Tl=X(()=>{Ue();Sl();Lh=zc(Lo),qh=Pc(Lo),Fh=Cc(Lo),Uh=Ac(Lo)});function b(t){return Pu(zk,t)}function ae(t){return Yu(Wh,t)}function Bh(t){return Qu(Vk,t)}function Re(t){return el(Jk,t)}function Kh(t){return tl(Wk,t)}function be(){return rl(Kk)}function Xk(t){return nl(Gk,t)}function te(t,e){return zh(Yk,t,e)}function I(t,e){let r={type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},...ee.normalizeParams(e)};return new Gh(r)}function He(t,e){return new Gh({type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},catchall:be(),...ee.normalizeParams(e)})}function ge(t,e){return new Xh({type:"union",options:t,...ee.normalizeParams(e)})}function Rl(t,e,r){return new Qk({type:"union",options:e,discriminator:t,...ee.normalizeParams(r)})}function pi(t,e){return new eS({type:"intersection",left:t,right:e})}function he(t,e,r){return new tS({type:"record",keyType:t,valueType:e,...ee.normalizeParams(r)})}function Qe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new El({type:"enum",entries:r,...ee.normalizeParams(e)})}function j(t,e){return new rS({type:"literal",values:Array.isArray(t)?t:[t],...ee.normalizeParams(e)})}function Yh(t){return new nS({type:"transform",transform:t})}function we(t){return new Qh({type:"optional",innerType:t})}function Vh(t){return new oS({type:"nullable",innerType:t})}function iS(t,e){return new sS({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function cS(t,e){return new aS({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function uS(t,e){return new eg({type:"nonoptional",innerType:t,...ee.normalizeParams(e)})}function dS(t,e){return new lS({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function zl(t,e){return new fS({type:"pipe",in:t,out:e})}function mS(t){return new pS({type:"readonly",innerType:t})}function hS(t){let e=new Ie({check:"custom"});return e._zod.check=t,e}function rg(t,e){return ml(tg,t??(()=>!0),e)}function gS(t,e={}){return hl(tg,t,e)}function yS(t){let e=hS(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ee.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(ee.issue(o))}},t(r.value,r)));return e}function Pl(t,e){return zl(Yh(t),e)}var ke,Jh,zk,xe,Rk,Hh,fi,Pk,Ik,Ck,Ak,Ok,Nk,Mk,jk,Zk,Dk,Lk,qk,Fk,Uk,Hk,Bk,Wh,Vk,Jk,Wk,Kk,Gk,Yk,Gh,Xh,Qk,eS,tS,El,rS,nS,Qh,oS,sS,aS,eg,lS,fS,pS,tg,kl=X(()=>{Ue();Ue();_l();$l();Tl();ke=w("ZodType",(t,e)=>(le.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)=>at(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Lh(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Fh(t,r,n),t.parseAsync=async(r,n)=>qh(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Uh(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(gS(r,n)),t.superRefine=r=>t.check(yS(r)),t.overwrite=r=>t.check(cn(r)),t.optional=()=>we(t),t.nullable=()=>Vh(t),t.nullish=()=>we(Vh(t)),t.nonoptional=r=>uS(t,r),t.array=()=>te(t),t.or=r=>ge([t,r]),t.and=r=>pi(t,r),t.transform=r=>zl(t,Yh(r)),t.default=r=>iS(t,r),t.prefault=r=>cS(t,r),t.catch=r=>dS(t,r),t.pipe=r=>zl(t,r),t.readonly=()=>mS(t),t.describe=r=>{let n=t.clone();return _r.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return _r.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return _r.get(t);let n=t.clone();return _r.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Jh=w("_ZodString",(t,e)=>{No.init(t,e),ke.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(ol(...n)),t.includes=(...n)=>t.check(al(...n)),t.startsWith=(...n)=>t.check(cl(...n)),t.endsWith=(...n)=>t.check(ul(...n)),t.min=(...n)=>t.check(Zn(...n)),t.max=(...n)=>t.check(ai(...n)),t.length=(...n)=>t.check(ci(...n)),t.nonempty=(...n)=>t.check(Zn(1,...n)),t.lowercase=n=>t.check(sl(n)),t.uppercase=n=>t.check(il(n)),t.trim=()=>t.check(dl()),t.normalize=(...n)=>t.check(ll(...n)),t.toLowerCase=()=>t.check(fl()),t.toUpperCase=()=>t.check(pl())}),zk=w("ZodString",(t,e)=>{No.init(t,e),Jh.init(t,e),t.email=r=>t.check(Iu(Rk,r)),t.url=r=>t.check(Mu(Pk,r)),t.jwt=r=>t.check(Xu(Bk,r)),t.emoji=r=>t.check(ju(Ik,r)),t.guid=r=>t.check(ni(Hh,r)),t.uuid=r=>t.check(Cu(fi,r)),t.uuidv4=r=>t.check(Au(fi,r)),t.uuidv6=r=>t.check(Ou(fi,r)),t.uuidv7=r=>t.check(Nu(fi,r)),t.nanoid=r=>t.check(Zu(Ck,r)),t.guid=r=>t.check(ni(Hh,r)),t.cuid=r=>t.check(Du(Ak,r)),t.cuid2=r=>t.check(Lu(Ok,r)),t.ulid=r=>t.check(qu(Nk,r)),t.base64=r=>t.check(Wu(Fk,r)),t.base64url=r=>t.check(Ku(Uk,r)),t.xid=r=>t.check(Fu(Mk,r)),t.ksuid=r=>t.check(Uu(jk,r)),t.ipv4=r=>t.check(Hu(Zk,r)),t.ipv6=r=>t.check(Bu(Dk,r)),t.cidrv4=r=>t.check(Vu(Lk,r)),t.cidrv6=r=>t.check(Ju(qk,r)),t.e164=r=>t.check(Gu(Hk,r)),t.datetime=r=>t.check(vl(r)),t.date=r=>t.check(xl(r)),t.time=r=>t.check(bl(r)),t.duration=r=>t.check(wl(r))});xe=w("ZodStringFormat",(t,e)=>{me.init(t,e),Jh.init(t,e)}),Rk=w("ZodEmail",(t,e)=>{Hc.init(t,e),xe.init(t,e)}),Hh=w("ZodGUID",(t,e)=>{Fc.init(t,e),xe.init(t,e)}),fi=w("ZodUUID",(t,e)=>{Uc.init(t,e),xe.init(t,e)}),Pk=w("ZodURL",(t,e)=>{Bc.init(t,e),xe.init(t,e)}),Ik=w("ZodEmoji",(t,e)=>{Vc.init(t,e),xe.init(t,e)}),Ck=w("ZodNanoID",(t,e)=>{Jc.init(t,e),xe.init(t,e)}),Ak=w("ZodCUID",(t,e)=>{Wc.init(t,e),xe.init(t,e)}),Ok=w("ZodCUID2",(t,e)=>{Kc.init(t,e),xe.init(t,e)}),Nk=w("ZodULID",(t,e)=>{Gc.init(t,e),xe.init(t,e)}),Mk=w("ZodXID",(t,e)=>{Xc.init(t,e),xe.init(t,e)}),jk=w("ZodKSUID",(t,e)=>{Yc.init(t,e),xe.init(t,e)}),Zk=w("ZodIPv4",(t,e)=>{Qc.init(t,e),xe.init(t,e)}),Dk=w("ZodIPv6",(t,e)=>{eu.init(t,e),xe.init(t,e)}),Lk=w("ZodCIDRv4",(t,e)=>{tu.init(t,e),xe.init(t,e)}),qk=w("ZodCIDRv6",(t,e)=>{ru.init(t,e),xe.init(t,e)}),Fk=w("ZodBase64",(t,e)=>{nu.init(t,e),xe.init(t,e)}),Uk=w("ZodBase64URL",(t,e)=>{ou.init(t,e),xe.init(t,e)}),Hk=w("ZodE164",(t,e)=>{su.init(t,e),xe.init(t,e)}),Bk=w("ZodJWT",(t,e)=>{iu.init(t,e),xe.init(t,e)}),Wh=w("ZodNumber",(t,e)=>{Qs.init(t,e),ke.init(t,e),t.gt=(n,o)=>t.check(si(n,o)),t.gte=(n,o)=>t.check(Zo(n,o)),t.min=(n,o)=>t.check(Zo(n,o)),t.lt=(n,o)=>t.check(oi(n,o)),t.lte=(n,o)=>t.check(jo(n,o)),t.max=(n,o)=>t.check(jo(n,o)),t.int=n=>t.check(Bh(n)),t.safe=n=>t.check(Bh(n)),t.positive=n=>t.check(si(0,n)),t.nonnegative=n=>t.check(Zo(0,n)),t.negative=n=>t.check(oi(0,n)),t.nonpositive=n=>t.check(jo(0,n)),t.multipleOf=(n,o)=>t.check(ii(n,o)),t.step=(n,o)=>t.check(ii(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});Vk=w("ZodNumberFormat",(t,e)=>{au.init(t,e),Wh.init(t,e)});Jk=w("ZodBoolean",(t,e)=>{cu.init(t,e),ke.init(t,e)});Wk=w("ZodNull",(t,e)=>{uu.init(t,e),ke.init(t,e)});Kk=w("ZodUnknown",(t,e)=>{lu.init(t,e),ke.init(t,e)});Gk=w("ZodNever",(t,e)=>{du.init(t,e),ke.init(t,e)});Yk=w("ZodArray",(t,e)=>{fu.init(t,e),ke.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Zn(r,n)),t.nonempty=r=>t.check(Zn(1,r)),t.max=(r,n)=>t.check(ai(r,n)),t.length=(r,n)=>t.check(ci(r,n)),t.unwrap=()=>t.element});Gh=w("ZodObject",(t,e)=>{ei.init(t,e),ke.init(t,e),ee.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Qe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:be()}),t.loose=()=>t.clone({...t._zod.def,catchall:be()}),t.strict=()=>t.clone({...t._zod.def,catchall:Xk()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ee.extend(t,r),t.merge=r=>ee.merge(t,r),t.pick=r=>ee.pick(t,r),t.omit=r=>ee.omit(t,r),t.partial=(...r)=>ee.partial(Qh,t,r[0]),t.required=(...r)=>ee.required(eg,t,r[0])});Xh=w("ZodUnion",(t,e)=>{ti.init(t,e),ke.init(t,e),t.options=e.options});Qk=w("ZodDiscriminatedUnion",(t,e)=>{Xh.init(t,e),pu.init(t,e)});eS=w("ZodIntersection",(t,e)=>{mu.init(t,e),ke.init(t,e)});tS=w("ZodRecord",(t,e)=>{hu.init(t,e),ke.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});El=w("ZodEnum",(t,e)=>{gu.init(t,e),ke.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 El({...e,checks:[],...ee.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 El({...e,checks:[],...ee.normalizeParams(o),entries:s})}});rS=w("ZodLiteral",(t,e)=>{yu.init(t,e),ke.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]}})});nS=w("ZodTransform",(t,e)=>{_u.init(t,e),ke.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ee.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(ee.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Qh=w("ZodOptional",(t,e)=>{vu.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});oS=w("ZodNullable",(t,e)=>{xu.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});sS=w("ZodDefault",(t,e)=>{bu.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});aS=w("ZodPrefault",(t,e)=>{wu.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});eg=w("ZodNonOptional",(t,e)=>{$u.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});lS=w("ZodCatch",(t,e)=>{ku.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});fS=w("ZodPipe",(t,e)=>{Su.init(t,e),ke.init(t,e),t.in=e.in,t.out=e.out});pS=w("ZodReadonly",(t,e)=>{Tu.init(t,e),ke.init(t,e)});tg=w("ZodCustom",(t,e)=>{Eu.init(t,e),ke.init(t,e)})});var ng=X(()=>{});var og=X(()=>{});var sg=X(()=>{Ue();kl();_l();Sl();Tl();ng();Ue();wh();ri();$l();og();it(bh())});var ig=X(()=>{sg()});var ag=X(()=>{ig()});function wg(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function $g(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Cl,cg,Fn,br,hi,Ee,ug,lg,xZ,xS,bS,Al,ct,qo,dg,Ce,ft,pt,Ae,gi,fg,tr,pg,mg,Ol,rr,O,Nl,Un,Fo,bZ,yi,wS,_i,$S,Uo,qn,hg,kS,SS,TS,ES,zS,RS,vi,Ml,PS,IS,jl,xi,CS,AS,bi,OS,Ho,Bo,NS,Vo,Hn,MS,Jo,wi,$i,ki,wZ,Si,Ti,Ei,gg,yg,_g,Zl,vg,Wo,Bn,xg,jS,zi,ZS,Ri,DS,Dl,LS,Pi,qS,FS,US,HS,BS,VS,JS,WS,KS,GS,Ii,XS,YS,Ci,Ll,ql,Fl,QS,eT,tT,Ul,rT,nT,oT,sT,iT,bg,Ai,aT,Oi,$Z,cT,Vn,uT,kZ,Ko,lT,Hl,dT,fT,pT,mT,hT,gT,yT,mi,_T,vT,xT,Go,Bl,bT,wT,$T,kT,ST,TT,ET,zT,RT,PT,IT,CT,AT,OT,NT,MT,jT,ZT,Jn,DT,LT,qT,Ni,FT,UT,HT,Vl,BT,SZ,TZ,EZ,zZ,RZ,PZ,C,Il,wr=X(()=>{ag();Cl="2025-11-25",cg="2025-03-26",Fn=[Cl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],br="io.modelcontextprotocol/related-task",hi="2.0",Ee=rg(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ug=ge([b(),ae().int()]),lg=b(),xZ=He({ttl:ae().optional(),pollInterval:ae().optional()}),xS=I({ttl:ae().optional()}),bS=I({taskId:b()}),Al=He({progressToken:ug.optional(),[br]:bS.optional()}),ct=I({_meta:Al.optional()}),qo=ct.extend({task:xS.optional()}),dg=t=>qo.safeParse(t).success,Ce=I({method:b(),params:ct.loose().optional()}),ft=I({_meta:Al.optional()}),pt=I({method:b(),params:ft.loose().optional()}),Ae=He({_meta:Al.optional()}),gi=ge([b(),ae().int()]),fg=I({jsonrpc:j(hi),id:gi,...Ce.shape}).strict(),tr=t=>fg.safeParse(t).success,pg=I({jsonrpc:j(hi),...pt.shape}).strict(),mg=t=>pg.safeParse(t).success,Ol=I({jsonrpc:j(hi),id:gi,result:Ae}).strict(),rr=t=>Ol.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"})(O||(O={}));Nl=I({jsonrpc:j(hi),id:gi.optional(),error:I({code:ae().int(),message:b(),data:be().optional()})}).strict(),Un=t=>Nl.safeParse(t).success,Fo=ge([fg,pg,Ol,Nl]),bZ=ge([Ol,Nl]),yi=Ae.strict(),wS=ft.extend({requestId:gi.optional(),reason:b().optional()}),_i=pt.extend({method:j("notifications/cancelled"),params:wS}),$S=I({src:b(),mimeType:b().optional(),sizes:te(b()).optional(),theme:Qe(["light","dark"]).optional()}),Uo=I({icons:te($S).optional()}),qn=I({name:b(),title:b().optional()}),hg=qn.extend({...qn.shape,...Uo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),kS=pi(I({applyDefaults:Re().optional()}),he(b(),be())),SS=Pl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,pi(I({form:kS.optional(),url:Ee.optional()}),he(b(),be()).optional())),TS=He({list:Ee.optional(),cancel:Ee.optional(),requests:He({sampling:He({createMessage:Ee.optional()}).optional(),elicitation:He({create:Ee.optional()}).optional()}).optional()}),ES=He({list:Ee.optional(),cancel:Ee.optional(),requests:He({tools:He({call:Ee.optional()}).optional()}).optional()}),zS=I({experimental:he(b(),Ee).optional(),sampling:I({context:Ee.optional(),tools:Ee.optional()}).optional(),elicitation:SS.optional(),roots:I({listChanged:Re().optional()}).optional(),tasks:TS.optional(),extensions:he(b(),Ee).optional()}),RS=ct.extend({protocolVersion:b(),capabilities:zS,clientInfo:hg}),vi=Ce.extend({method:j("initialize"),params:RS}),Ml=t=>vi.safeParse(t).success,PS=I({experimental:he(b(),Ee).optional(),logging:Ee.optional(),completions:Ee.optional(),prompts:I({listChanged:Re().optional()}).optional(),resources:I({subscribe:Re().optional(),listChanged:Re().optional()}).optional(),tools:I({listChanged:Re().optional()}).optional(),tasks:ES.optional(),extensions:he(b(),Ee).optional()}),IS=Ae.extend({protocolVersion:b(),capabilities:PS,serverInfo:hg,instructions:b().optional()}),jl=pt.extend({method:j("notifications/initialized"),params:ft.optional()}),xi=Ce.extend({method:j("ping"),params:ct.optional()}),CS=I({progress:ae(),total:we(ae()),message:we(b())}),AS=I({...ft.shape,...CS.shape,progressToken:ug}),bi=pt.extend({method:j("notifications/progress"),params:AS}),OS=ct.extend({cursor:lg.optional()}),Ho=Ce.extend({params:OS.optional()}),Bo=Ae.extend({nextCursor:lg.optional()}),NS=Qe(["working","input_required","completed","failed","cancelled"]),Vo=I({taskId:b(),status:NS,ttl:ge([ae(),Kh()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:we(ae()),statusMessage:we(b())}),Hn=Ae.extend({task:Vo}),MS=ft.merge(Vo),Jo=pt.extend({method:j("notifications/tasks/status"),params:MS}),wi=Ce.extend({method:j("tasks/get"),params:ct.extend({taskId:b()})}),$i=Ae.merge(Vo),ki=Ce.extend({method:j("tasks/result"),params:ct.extend({taskId:b()})}),wZ=Ae.loose(),Si=Ho.extend({method:j("tasks/list")}),Ti=Bo.extend({tasks:te(Vo)}),Ei=Ce.extend({method:j("tasks/cancel"),params:ct.extend({taskId:b()})}),gg=Ae.merge(Vo),yg=I({uri:b(),mimeType:we(b()),_meta:he(b(),be()).optional()}),_g=yg.extend({text:b()}),Zl=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),vg=yg.extend({blob:Zl}),Wo=Qe(["user","assistant"]),Bn=I({audience:te(Wo).optional(),priority:ae().min(0).max(1).optional(),lastModified:Do.datetime({offset:!0}).optional()}),xg=I({...qn.shape,...Uo.shape,uri:b(),description:we(b()),mimeType:we(b()),size:we(ae()),annotations:Bn.optional(),_meta:we(He({}))}),jS=I({...qn.shape,...Uo.shape,uriTemplate:b(),description:we(b()),mimeType:we(b()),annotations:Bn.optional(),_meta:we(He({}))}),zi=Ho.extend({method:j("resources/list")}),ZS=Bo.extend({resources:te(xg)}),Ri=Ho.extend({method:j("resources/templates/list")}),DS=Bo.extend({resourceTemplates:te(jS)}),Dl=ct.extend({uri:b()}),LS=Dl,Pi=Ce.extend({method:j("resources/read"),params:LS}),qS=Ae.extend({contents:te(ge([_g,vg]))}),FS=pt.extend({method:j("notifications/resources/list_changed"),params:ft.optional()}),US=Dl,HS=Ce.extend({method:j("resources/subscribe"),params:US}),BS=Dl,VS=Ce.extend({method:j("resources/unsubscribe"),params:BS}),JS=ft.extend({uri:b()}),WS=pt.extend({method:j("notifications/resources/updated"),params:JS}),KS=I({name:b(),description:we(b()),required:we(Re())}),GS=I({...qn.shape,...Uo.shape,description:we(b()),arguments:we(te(KS)),_meta:we(He({}))}),Ii=Ho.extend({method:j("prompts/list")}),XS=Bo.extend({prompts:te(GS)}),YS=ct.extend({name:b(),arguments:he(b(),b()).optional()}),Ci=Ce.extend({method:j("prompts/get"),params:YS}),Ll=I({type:j("text"),text:b(),annotations:Bn.optional(),_meta:he(b(),be()).optional()}),ql=I({type:j("image"),data:Zl,mimeType:b(),annotations:Bn.optional(),_meta:he(b(),be()).optional()}),Fl=I({type:j("audio"),data:Zl,mimeType:b(),annotations:Bn.optional(),_meta:he(b(),be()).optional()}),QS=I({type:j("tool_use"),name:b(),id:b(),input:he(b(),be()),_meta:he(b(),be()).optional()}),eT=I({type:j("resource"),resource:ge([_g,vg]),annotations:Bn.optional(),_meta:he(b(),be()).optional()}),tT=xg.extend({type:j("resource_link")}),Ul=ge([Ll,ql,Fl,tT,eT]),rT=I({role:Wo,content:Ul}),nT=Ae.extend({description:b().optional(),messages:te(rT)}),oT=pt.extend({method:j("notifications/prompts/list_changed"),params:ft.optional()}),sT=I({title:b().optional(),readOnlyHint:Re().optional(),destructiveHint:Re().optional(),idempotentHint:Re().optional(),openWorldHint:Re().optional()}),iT=I({taskSupport:Qe(["required","optional","forbidden"]).optional()}),bg=I({...qn.shape,...Uo.shape,description:b().optional(),inputSchema:I({type:j("object"),properties:he(b(),Ee).optional(),required:te(b()).optional()}).catchall(be()),outputSchema:I({type:j("object"),properties:he(b(),Ee).optional(),required:te(b()).optional()}).catchall(be()).optional(),annotations:sT.optional(),execution:iT.optional(),_meta:he(b(),be()).optional()}),Ai=Ho.extend({method:j("tools/list")}),aT=Bo.extend({tools:te(bg)}),Oi=Ae.extend({content:te(Ul).default([]),structuredContent:he(b(),be()).optional(),isError:Re().optional()}),$Z=Oi.or(Ae.extend({toolResult:be()})),cT=qo.extend({name:b(),arguments:he(b(),be()).optional()}),Vn=Ce.extend({method:j("tools/call"),params:cT}),uT=pt.extend({method:j("notifications/tools/list_changed"),params:ft.optional()}),kZ=I({autoRefresh:Re().default(!0),debounceMs:ae().int().nonnegative().default(300)}),Ko=Qe(["debug","info","notice","warning","error","critical","alert","emergency"]),lT=ct.extend({level:Ko}),Hl=Ce.extend({method:j("logging/setLevel"),params:lT}),dT=ft.extend({level:Ko,logger:b().optional(),data:be()}),fT=pt.extend({method:j("notifications/message"),params:dT}),pT=I({name:b().optional()}),mT=I({hints:te(pT).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),hT=I({mode:Qe(["auto","required","none"]).optional()}),gT=I({type:j("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:te(Ul).default([]),structuredContent:I({}).loose().optional(),isError:Re().optional(),_meta:he(b(),be()).optional()}),yT=Rl("type",[Ll,ql,Fl]),mi=Rl("type",[Ll,ql,Fl,QS,gT]),_T=I({role:Wo,content:ge([mi,te(mi)]),_meta:he(b(),be()).optional()}),vT=qo.extend({messages:te(_T),modelPreferences:mT.optional(),systemPrompt:b().optional(),includeContext:Qe(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:te(b()).optional(),metadata:Ee.optional(),tools:te(bg).optional(),toolChoice:hT.optional()}),xT=Ce.extend({method:j("sampling/createMessage"),params:vT}),Go=Ae.extend({model:b(),stopReason:we(Qe(["endTurn","stopSequence","maxTokens"]).or(b())),role:Wo,content:yT}),Bl=Ae.extend({model:b(),stopReason:we(Qe(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Wo,content:ge([mi,te(mi)])}),bT=I({type:j("boolean"),title:b().optional(),description:b().optional(),default:Re().optional()}),wT=I({type:j("string"),title:b().optional(),description:b().optional(),minLength:ae().optional(),maxLength:ae().optional(),format:Qe(["email","uri","date","date-time"]).optional(),default:b().optional()}),$T=I({type:Qe(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),kT=I({type:j("string"),title:b().optional(),description:b().optional(),enum:te(b()),default:b().optional()}),ST=I({type:j("string"),title:b().optional(),description:b().optional(),oneOf:te(I({const:b(),title:b()})),default:b().optional()}),TT=I({type:j("string"),title:b().optional(),description:b().optional(),enum:te(b()),enumNames:te(b()).optional(),default:b().optional()}),ET=ge([kT,ST]),zT=I({type:j("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({type:j("string"),enum:te(b())}),default:te(b()).optional()}),RT=I({type:j("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({anyOf:te(I({const:b(),title:b()}))}),default:te(b()).optional()}),PT=ge([zT,RT]),IT=ge([TT,ET,PT]),CT=ge([IT,bT,wT,$T]),AT=qo.extend({mode:j("form").optional(),message:b(),requestedSchema:I({type:j("object"),properties:he(b(),CT),required:te(b()).optional()})}),OT=qo.extend({mode:j("url"),message:b(),elicitationId:b(),url:b().url()}),NT=ge([AT,OT]),MT=Ce.extend({method:j("elicitation/create"),params:NT}),jT=ft.extend({elicitationId:b()}),ZT=pt.extend({method:j("notifications/elicitation/complete"),params:jT}),Jn=Ae.extend({action:Qe(["accept","decline","cancel"]),content:Pl(t=>t===null?void 0:t,he(b(),ge([b(),ae(),Re(),te(b())])).optional())}),DT=I({type:j("ref/resource"),uri:b()}),LT=I({type:j("ref/prompt"),name:b()}),qT=ct.extend({ref:ge([LT,DT]),argument:I({name:b(),value:b()}),context:I({arguments:he(b(),b()).optional()}).optional()}),Ni=Ce.extend({method:j("completion/complete"),params:qT});FT=Ae.extend({completion:He({values:te(b()).max(100),total:we(ae().int()),hasMore:we(Re())})}),UT=I({uri:b().startsWith("file://"),name:b().optional(),_meta:he(b(),be()).optional()}),HT=Ce.extend({method:j("roots/list"),params:ct.optional()}),Vl=Ae.extend({roots:te(UT)}),BT=pt.extend({method:j("notifications/roots/list_changed"),params:ft.optional()}),SZ=ge([xi,vi,Ni,Hl,Ci,Ii,zi,Ri,Pi,HS,VS,Vn,Ai,wi,ki,Si,Ei]),TZ=ge([_i,bi,jl,BT,Jo]),EZ=ge([yi,Go,Bl,Jn,Vl,$i,Ti,Hn]),zZ=ge([xi,xT,MT,HT,wi,ki,Si,Ei]),RZ=ge([_i,bi,fT,WS,FS,uT,oT,Jo,ZT]),PZ=ge([yi,IS,FT,nT,XS,ZS,DS,qS,Oi,aT,$i,Ti,Hn]),C=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===O.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Il(o.elicitations,r)}return new t(e,r,n)}},Il=class extends C{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(O.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var es=z(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.regexpCode=ie.getEsmExportName=ie.getProperty=ie.safeStringify=ie.stringify=ie.strConcat=ie.addCodeArg=ie.str=ie._=ie.nil=ie._Code=ie.Name=ie.IDENTIFIER=ie._CodeOrName=void 0;var Yo=class{};ie._CodeOrName=Yo;ie.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var dn=class extends Yo{constructor(e){if(super(),!ie.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}}};ie.Name=dn;var mt=class extends Yo{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 dn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ie._Code=mt;ie.nil=new mt("");function oy(t,...e){let r=[t[0]],n=0;for(;n<e.length;)rd(r,e[n]),r.push(t[++n]);return new mt(r)}ie._=oy;var td=new mt("+");function sy(t,...e){let r=[Qo(t[0])],n=0;for(;n<e.length;)r.push(td),rd(r,e[n]),r.push(td,Qo(t[++n]));return rE(r),new mt(r)}ie.str=sy;function rd(t,e){e instanceof mt?t.push(...e._items):e instanceof dn?t.push(e):t.push(sE(e))}ie.addCodeArg=rd;function rE(t){let e=1;for(;e<t.length-1;){if(t[e]===td){let r=nE(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function nE(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof dn||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 dn))return`"${t}${e.slice(1)}`}function oE(t,e){return e.emptyStr()?t:t.emptyStr()?e:sy`${t}${e}`}ie.strConcat=oE;function sE(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Qo(Array.isArray(t)?t.join(","):t)}function iE(t){return new mt(Qo(t))}ie.stringify=iE;function Qo(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ie.safeStringify=Qo;function aE(t){return typeof t=="string"&&ie.IDENTIFIER.test(t)?new mt(`.${t}`):oy`[${t}]`}ie.getProperty=aE;function cE(t){if(typeof t=="string"&&ie.IDENTIFIER.test(t))return new mt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ie.getEsmExportName=cE;function uE(t){return new mt(t.toString())}ie.regexpCode=uE});var sd=z(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.ValueScope=tt.ValueScopeName=tt.Scope=tt.varKinds=tt.UsedValueState=void 0;var et=es(),nd=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},qi;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(qi||(tt.UsedValueState=qi={}));tt.varKinds={const:new et.Name("const"),let:new et.Name("let"),var:new et.Name("var")};var Fi=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof et.Name?e:this.name(e)}name(e){return new et.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}}};tt.Scope=Fi;var Ui=class extends et.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,et._)`.${new et.Name(r)}[${n}]`}};tt.ValueScopeName=Ui;var lE=(0,et._)`\n`,od=class extends Fi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?lE:et.nil}}get(){return this._scope}name(e){return new Ui(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,et._)`${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=et.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,qi.Started);let l=r(u);if(l){let d=this.opts.es5?tt.varKinds.var:tt.varKinds.const;s=(0,et._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,et._)`${s}${l}${this.opts._n}`;else throw new nd(u);c.set(u,qi.Completed)})}return s}};tt.ValueScope=od});var W=z(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.or=K.and=K.not=K.CodeGen=K.operators=K.varKinds=K.ValueScopeName=K.ValueScope=K.Scope=K.Name=K.regexpCode=K.stringify=K.getProperty=K.nil=K.strConcat=K.str=K._=void 0;var ne=es(),Tt=sd(),kr=es();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return kr._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return kr.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return kr.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return kr.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return kr.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return kr.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return kr.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return kr.Name}});var Ji=sd();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return Ji.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return Ji.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return Ji.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return Ji.varKinds}});K.operators={GT:new ne._Code(">"),GTE:new ne._Code(">="),LT:new ne._Code("<"),LTE:new ne._Code("<="),EQ:new ne._Code("==="),NEQ:new ne._Code("!=="),NOT:new ne._Code("!"),OR:new ne._Code("||"),AND:new ne._Code("&&"),ADD:new ne._Code("+")};var nr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},id=class extends nr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Tt.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=Kn(this.rhs,e,r)),this}get names(){return this.rhs instanceof ne._CodeOrName?this.rhs.names:{}}},Hi=class extends nr{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 ne.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Kn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ne.Name?{}:{...this.lhs.names};return Vi(e,this.rhs)}},ad=class extends Hi{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},cd=class extends nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ud=class extends nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ld=class extends nr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},dd=class extends nr{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=Kn(this.code,e,r),this}get names(){return this.code instanceof ne._CodeOrName?this.code.names:{}}},ts=class extends nr{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)||(dE(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>mn(e,r.names),{})}},or=class extends ts{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},fd=class extends ts{},Wn=class extends or{};Wn.kind="else";var fn=class t extends or{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 Wn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(iy(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=Kn(this.condition,e,r),this}get names(){let e=super.names;return Vi(e,this.condition),this.else&&mn(e,this.else.names),e}};fn.kind="if";var pn=class extends or{};pn.kind="for";var pd=class extends pn{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=Kn(this.iteration,e,r),this}get names(){return mn(super.names,this.iteration.names)}},md=class extends pn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Tt.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=Vi(super.names,this.from);return Vi(e,this.to)}},Bi=class extends pn{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=Kn(this.iterable,e,r),this}get names(){return mn(super.names,this.iterable.names)}},rs=class extends or{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)}};rs.kind="func";var ns=class extends ts{render(e){return"return "+super.render(e)}};ns.kind="return";var hd=class extends or{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&&mn(e,this.catch.names),this.finally&&mn(e,this.finally.names),e}},os=class extends or{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};os.kind="catch";var ss=class extends or{render(e){return"finally"+super.render(e)}};ss.kind="finally";var gd=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
31
|
-
`:""},this._extScope=e,this._scope=new Tt.Scope({parent:e}),this._nodes=[new fd]}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 id(e,s,n)),s}const(e,r,n){return this._def(Tt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Tt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Tt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Hi(e,r,n))}add(e,r){return this._leafNode(new ad(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ne.nil&&this._leafNode(new dd(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,ne.addCodeArg)(r,o));return r.push("}"),new ne._Code(r)}if(e,r,n){if(this._blockNode(new fn(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 fn(e))}else(){return this._elseNode(new Wn)}endIf(){return this._endBlockNode(fn,Wn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new pd(e),r)}forRange(e,r,n,o,s=this.opts.es5?Tt.varKinds.var:Tt.varKinds.let){let i=this._scope.toName(e);return this._for(new md(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Tt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ne.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ne._)`${i}.length`,a=>{this.var(s,(0,ne._)`${i}[${a}]`),n(s)})}return this._for(new Bi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Tt.varKinds.var:Tt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ne._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Bi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(pn)}label(e){return this._leafNode(new cd(e))}break(e){return this._leafNode(new ud(e))}return(e){let r=new ns;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ns)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new hd;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new os(s),r(s)}return n&&(this._currNode=o.finally=new ss,this.code(n)),this._endBlockNode(os,ss)}throw(e){return this._leafNode(new ld(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=ne.nil,n,o){return this._blockNode(new rs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(rs)}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 fn))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}};K.CodeGen=gd;function mn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Vi(t,e){return e instanceof ne._CodeOrName?mn(t,e.names):t}function Kn(t,e,r){if(t instanceof ne.Name)return n(t);if(!o(t))return t;return new ne._Code(t._items.reduce((s,i)=>(i instanceof ne.Name&&(i=n(i)),i instanceof ne._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 ne._Code&&s._items.some(i=>i instanceof ne.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function dE(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function iy(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ne._)`!${yd(t)}`}K.not=iy;var fE=ay(K.operators.AND);function pE(...t){return t.reduce(fE)}K.and=pE;var mE=ay(K.operators.OR);function hE(...t){return t.reduce(mE)}K.or=hE;function ay(t){return(e,r)=>e===ne.nil?r:r===ne.nil?e:(0,ne._)`${yd(e)} ${t} ${yd(r)}`}function yd(t){return t instanceof ne.Name?t:(0,ne._)`(${t})`}});var oe=z(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.checkStrictMode=G.getErrorPath=G.Type=G.useFunc=G.setEvaluated=G.evaluatedPropsToName=G.mergeEvaluated=G.eachItem=G.unescapeJsonPointer=G.escapeJsonPointer=G.escapeFragment=G.unescapeFragment=G.schemaRefOrVal=G.schemaHasRulesButRef=G.schemaHasRules=G.checkUnknownRules=G.alwaysValidSchema=G.toHash=void 0;var fe=W(),gE=es();function yE(t){let e={};for(let r of t)e[r]=!0;return e}G.toHash=yE;function _E(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ly(t,e),!dy(e,t.self.RULES.all))}G.alwaysValidSchema=_E;function ly(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]||my(t,`unknown keyword: "${s}"`)}G.checkUnknownRules=ly;function dy(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}G.schemaHasRules=dy;function vE(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}G.schemaHasRulesButRef=vE;function xE({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,fe._)`${r}`}return(0,fe._)`${t}${e}${(0,fe.getProperty)(n)}`}G.schemaRefOrVal=xE;function bE(t){return fy(decodeURIComponent(t))}G.unescapeFragment=bE;function wE(t){return encodeURIComponent(vd(t))}G.escapeFragment=wE;function vd(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=vd;function fy(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=fy;function $E(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=$E;function cy({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof fe.Name?(s instanceof fe.Name?t(o,s,i):e(o,s,i),i):s instanceof fe.Name?(e(o,i,s),s):r(s,i);return a===fe.Name&&!(c instanceof fe.Name)?n(o,c):c}}G.mergeEvaluated={props:cy({mergeNames:(t,e,r)=>t.if((0,fe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,fe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,fe._)`${r} || {}`).code((0,fe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,fe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,fe._)`${r} || {}`),xd(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:py}),items:cy({mergeNames:(t,e,r)=>t.if((0,fe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,fe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,fe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,fe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function py(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,fe._)`{}`);return e!==void 0&&xd(t,r,e),r}G.evaluatedPropsToName=py;function xd(t,e,r){Object.keys(r).forEach(n=>t.assign((0,fe._)`${e}${(0,fe.getProperty)(n)}`,!0))}G.setEvaluated=xd;var uy={};function kE(t,e){return t.scopeValue("func",{ref:e,code:uy[e.code]||(uy[e.code]=new gE._Code(e.code))})}G.useFunc=kE;var _d;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(_d||(G.Type=_d={}));function SE(t,e,r){if(t instanceof fe.Name){let n=e===_d.Num;return r?n?(0,fe._)`"[" + ${t} + "]"`:(0,fe._)`"['" + ${t} + "']"`:n?(0,fe._)`"/" + ${t}`:(0,fe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,fe.getProperty)(t).toString():"/"+vd(t)}G.getErrorPath=SE;function my(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}G.checkStrictMode=my});var sr=z(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Ze=W(),TE={data:new Ze.Name("data"),valCxt:new Ze.Name("valCxt"),instancePath:new Ze.Name("instancePath"),parentData:new Ze.Name("parentData"),parentDataProperty:new Ze.Name("parentDataProperty"),rootData:new Ze.Name("rootData"),dynamicAnchors:new Ze.Name("dynamicAnchors"),vErrors:new Ze.Name("vErrors"),errors:new Ze.Name("errors"),this:new Ze.Name("this"),self:new Ze.Name("self"),scope:new Ze.Name("scope"),json:new Ze.Name("json"),jsonPos:new Ze.Name("jsonPos"),jsonLen:new Ze.Name("jsonLen"),jsonPart:new Ze.Name("jsonPart")};bd.default=TE});var is=z(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.extendErrors=De.resetErrorsCount=De.reportExtraError=De.reportError=De.keyword$DataError=De.keywordError=void 0;var se=W(),Wi=oe(),Ve=sr();De.keywordError={message:({keyword:t})=>(0,se.str)`must pass "${t}" keyword validation`};De.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,se.str)`"${t}" keyword must be ${e} ($data)`:(0,se.str)`"${t}" keyword is invalid ($data)`};function EE(t,e=De.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=yy(t,e,r);n??(i||a)?hy(s,c):gy(o,(0,se._)`[${c}]`)}De.reportError=EE;function zE(t,e=De.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=yy(t,e,r);hy(o,a),s||i||gy(n,Ve.default.vErrors)}De.reportExtraError=zE;function RE(t,e){t.assign(Ve.default.errors,e),t.if((0,se._)`${Ve.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,se._)`${Ve.default.vErrors}.length`,e),()=>t.assign(Ve.default.vErrors,null)))}De.resetErrorsCount=RE;function PE({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,Ve.default.errors,a=>{t.const(i,(0,se._)`${Ve.default.vErrors}[${a}]`),t.if((0,se._)`${i}.instancePath === undefined`,()=>t.assign((0,se._)`${i}.instancePath`,(0,se.strConcat)(Ve.default.instancePath,s.errorPath))),t.assign((0,se._)`${i}.schemaPath`,(0,se.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,se._)`${i}.schema`,r),t.assign((0,se._)`${i}.data`,n))})}De.extendErrors=PE;function hy(t,e){let r=t.const("err",e);t.if((0,se._)`${Ve.default.vErrors} === null`,()=>t.assign(Ve.default.vErrors,(0,se._)`[${r}]`),(0,se._)`${Ve.default.vErrors}.push(${r})`),t.code((0,se._)`${Ve.default.errors}++`)}function gy(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,se._)`new ${t.ValidationError}(${e})`):(r.assign((0,se._)`${n}.errors`,e),r.return(!1))}var hn={keyword:new se.Name("keyword"),schemaPath:new se.Name("schemaPath"),params:new se.Name("params"),propertyName:new se.Name("propertyName"),message:new se.Name("message"),schema:new se.Name("schema"),parentSchema:new se.Name("parentSchema")};function yy(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,se._)`{}`:IE(t,e,r)}function IE(t,e,r={}){let{gen:n,it:o}=t,s=[CE(o,r),AE(t,r)];return OE(t,e,s),n.object(...s)}function CE({errorPath:t},{instancePath:e}){let r=e?(0,se.str)`${t}${(0,Wi.getErrorPath)(e,Wi.Type.Str)}`:t;return[Ve.default.instancePath,(0,se.strConcat)(Ve.default.instancePath,r)]}function AE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,se.str)`${e}/${t}`;return r&&(o=(0,se.str)`${o}${(0,Wi.getErrorPath)(r,Wi.Type.Str)}`),[hn.schemaPath,o]}function OE(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([hn.keyword,o],[hn.params,typeof e=="function"?e(t):e||(0,se._)`{}`]),c.messages&&n.push([hn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([hn.schema,i],[hn.parentSchema,(0,se._)`${l}${d}`],[Ve.default.data,s]),u&&n.push([hn.propertyName,u])}});var vy=z(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.boolOrEmptySchema=Gn.topBoolOrEmptySchema=void 0;var NE=is(),ME=W(),jE=sr(),ZE={message:"boolean schema is false"};function DE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?_y(t,!1):typeof r=="object"&&r.$async===!0?e.return(jE.default.data):(e.assign((0,ME._)`${n}.errors`,null),e.return(!0))}Gn.topBoolOrEmptySchema=DE;function LE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),_y(t)):r.var(e,!0)}Gn.boolOrEmptySchema=LE;function _y(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,NE.reportError)(o,ZE,void 0,e)}});var wd=z(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.getRules=Xn.isJSONType=void 0;var qE=["string","number","integer","boolean","null","object","array"],FE=new Set(qE);function UE(t){return typeof t=="string"&&FE.has(t)}Xn.isJSONType=UE;function HE(){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:{}}}Xn.getRules=HE});var $d=z(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.shouldUseRule=Sr.shouldUseGroup=Sr.schemaHasRulesForType=void 0;function BE({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&xy(t,n)}Sr.schemaHasRulesForType=BE;function xy(t,e){return e.rules.some(r=>by(t,r))}Sr.shouldUseGroup=xy;function by(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))}Sr.shouldUseRule=by});var as=z(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var VE=wd(),JE=$d(),WE=is(),V=W(),wy=oe(),Yn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Yn||(Le.DataType=Yn={}));function KE(t){let e=$y(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}Le.getSchemaTypes=KE;function $y(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(VE.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=$y;function GE(t,e){let{gen:r,data:n,opts:o}=t,s=XE(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,JE.schemaHasRulesForType)(t,e[0]));if(i){let a=Sd(e,n,o.strictNumbers,Yn.Wrong);r.if(a,()=>{s.length?YE(t,e,s):Td(t)})}return i}Le.coerceAndCheckDataType=GE;var ky=new Set(["string","number","integer","boolean","null"]);function XE(t,e){return e?t.filter(r=>ky.has(r)||e==="array"&&r==="array"):[]}function YE(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,V._)`typeof ${o}`),a=n.let("coerced",(0,V._)`undefined`);s.coerceTypes==="array"&&n.if((0,V._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,V._)`${o}[0]`).assign(i,(0,V._)`typeof ${o}`).if(Sd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,V._)`${a} !== undefined`);for(let u of r)(ky.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Td(t),n.endIf(),n.if((0,V._)`${a} !== undefined`,()=>{n.assign(o,a),QE(t,a)});function c(u){switch(u){case"string":n.elseIf((0,V._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,V._)`"" + ${o}`).elseIf((0,V._)`${o} === null`).assign(a,(0,V._)`""`);return;case"number":n.elseIf((0,V._)`${i} == "boolean" || ${o} === null
|
|
32
|
-
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,
|
|
33
|
-
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,
|
|
34
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,V._)`[${o}]`)}}}function QE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,V._)`${e} !== undefined`,()=>t.assign((0,V._)`${e}[${r}]`,n))}function kd(t,e,r,n=Yn.Correct){let o=n===Yn.Correct?V.operators.EQ:V.operators.NEQ,s;switch(t){case"null":return(0,V._)`${e} ${o} null`;case"array":s=(0,V._)`Array.isArray(${e})`;break;case"object":s=(0,V._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,V._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,V._)`typeof ${e} ${o} ${t}`}return n===Yn.Correct?s:(0,V.not)(s);function i(a=V.nil){return(0,V.and)((0,V._)`typeof ${e} == "number"`,a,r?(0,V._)`isFinite(${e})`:V.nil)}}Le.checkDataType=kd;function Sd(t,e,r,n){if(t.length===1)return kd(t[0],e,r,n);let o,s=(0,wy.toHash)(t);if(s.array&&s.object){let i=(0,V._)`typeof ${e} != "object"`;o=s.null?i:(0,V._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=V.nil;s.number&&delete s.integer;for(let i in s)o=(0,V.and)(o,kd(i,e,r,n));return o}Le.checkDataTypes=Sd;var ez={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,V._)`{type: ${t}}`:(0,V._)`{type: ${e}}`};function Td(t){let e=tz(t);(0,WE.reportError)(e,ez)}Le.reportTypeError=Td;function tz(t){let{gen:e,data:r,schema:n}=t,o=(0,wy.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Ty=z(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.assignDefaults=void 0;var Qn=W(),rz=oe();function nz(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Sy(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Sy(t,s,o.default))}Ki.assignDefaults=nz;function Sy(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Qn._)`${s}${(0,Qn.getProperty)(e)}`;if(o){(0,rz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Qn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Qn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Qn._)`${a} = ${(0,Qn.stringify)(r)}`)}});var ht=z(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.validateUnion=de.validateArray=de.usePattern=de.callValidateCode=de.schemaProperties=de.allSchemaProperties=de.noPropertyInData=de.propertyInData=de.isOwnProperty=de.hasPropFunc=de.reportMissingProp=de.checkMissingProp=de.checkReportMissingProp=void 0;var ye=W(),Ed=oe(),Tr=sr(),oz=oe();function sz(t,e){let{gen:r,data:n,it:o}=t;r.if(Rd(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ye._)`${e}`},!0),t.error()})}de.checkReportMissingProp=sz;function iz({gen:t,data:e,it:{opts:r}},n,o){return(0,ye.or)(...n.map(s=>(0,ye.and)(Rd(t,e,s,r.ownProperties),(0,ye._)`${o} = ${s}`)))}de.checkMissingProp=iz;function az(t,e){t.setParams({missingProperty:e},!0),t.error()}de.reportMissingProp=az;function Ey(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ye._)`Object.prototype.hasOwnProperty`})}de.hasPropFunc=Ey;function zd(t,e,r){return(0,ye._)`${Ey(t)}.call(${e}, ${r})`}de.isOwnProperty=zd;function cz(t,e,r,n){let o=(0,ye._)`${e}${(0,ye.getProperty)(r)} !== undefined`;return n?(0,ye._)`${o} && ${zd(t,e,r)}`:o}de.propertyInData=cz;function Rd(t,e,r,n){let o=(0,ye._)`${e}${(0,ye.getProperty)(r)} === undefined`;return n?(0,ye.or)(o,(0,ye.not)(zd(t,e,r))):o}de.noPropertyInData=Rd;function zy(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}de.allSchemaProperties=zy;function uz(t,e){return zy(e).filter(r=>!(0,Ed.alwaysValidSchema)(t,e[r]))}de.schemaProperties=uz;function lz({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ye._)`${t}, ${e}, ${n}${o}`:e,d=[[Tr.default.instancePath,(0,ye.strConcat)(Tr.default.instancePath,s)],[Tr.default.parentData,i.parentData],[Tr.default.parentDataProperty,i.parentDataProperty],[Tr.default.rootData,Tr.default.rootData]];i.opts.dynamicRef&&d.push([Tr.default.dynamicAnchors,Tr.default.dynamicAnchors]);let m=(0,ye._)`${l}, ${r.object(...d)}`;return c!==ye.nil?(0,ye._)`${a}.call(${c}, ${m})`:(0,ye._)`${a}(${m})`}de.callValidateCode=lz;var dz=(0,ye._)`new RegExp`;function fz({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,ye._)`${o.code==="new RegExp"?dz:(0,oz.useFunc)(t,o)}(${r}, ${n})`})}de.usePattern=fz;function pz(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,ye._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Ed.Type.Num},s),e.if((0,ye.not)(s),a)})}}de.validateArray=pz;function mz(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,Ed.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,ye._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ye.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}de.validateUnion=mz});var Iy=z(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.validateKeywordUsage=Lt.validSchemaType=Lt.funcKeywordCode=Lt.macroKeywordCode=void 0;var Je=W(),gn=sr(),hz=ht(),gz=is();function yz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Py(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Je.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Lt.macroKeywordCode=yz;function _z(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;xz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Py(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&&Ry(t),h(()=>t.error());else{let _=e.async?p():f();e.modifying&&Ry(t),h(()=>vz(t,_))}}function p(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,Je._)`await `),v=>n.assign(d,!1).if((0,Je._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,Je._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,Je._)`${l}.errors`;return n.assign(_,null),g(Je.nil),_}function g(_=e.async?(0,Je._)`await `:Je.nil){let v=c.opts.passContext?gn.default.this:gn.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Je._)`${_}${(0,hz.callValidateCode)(t,l,v,y)}`,e.modifying)}function h(_){var v;n.if((0,Je.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}Lt.funcKeywordCode=_z;function Ry(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Je._)`${n.parentData}[${n.parentDataProperty}]`))}function vz(t,e){let{gen:r}=t;r.if((0,Je._)`Array.isArray(${e})`,()=>{r.assign(gn.default.vErrors,(0,Je._)`${gn.default.vErrors} === null ? ${e} : ${gn.default.vErrors}.concat(${e})`).assign(gn.default.errors,(0,Je._)`${gn.default.vErrors}.length`),(0,gz.extendErrors)(t)},()=>t.error())}function xz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Py(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,Je.stringify)(r)})}function bz(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")}Lt.validSchemaType=bz;function wz({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)}}Lt.validateKeywordUsage=wz});var Ay=z(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.extendSubschemaMode=Er.extendSubschemaData=Er.getSubschema=void 0;var qt=W(),Cy=oe();function $z(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,qt._)`${t.schemaPath}${(0,qt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,qt._)`${t.schemaPath}${(0,qt.getProperty)(e)}${(0,qt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Cy.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')}Er.getSubschema=$z;function kz(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,qt._)`${e.data}${(0,qt.getProperty)(r)}`,!0);c(m),t.errorPath=(0,qt.str)`${u}${(0,Cy.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,qt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof qt.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]}}Er.extendSubschemaData=kz;function Sz(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}Er.extendSubschemaMode=Sz});var Pd=z((V4,Oy)=>{"use strict";Oy.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 My=z((J4,Ny)=>{"use strict";var zr=Ny.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(){};Gi(e,n,o,t,"",t)};zr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};zr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};zr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};zr.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 Gi(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 zr.arrayKeywords)for(var m=0;m<d.length;m++)Gi(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in zr.propsKeywords){if(d&&typeof d=="object")for(var p in d)Gi(t,e,r,d[p],o+"/"+l+"/"+Tz(p),s,o,l,n,p)}else(l in zr.keywords||t.allKeys&&!(l in zr.skipKeywords))&&Gi(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function Tz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var cs=z(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getSchemaRefs=rt.resolveUrl=rt.normalizeId=rt._getFullPath=rt.getFullPath=rt.inlineRef=void 0;var Ez=oe(),zz=Pd(),Rz=My(),Pz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Iz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Id(t):e?jy(t)<=e:!1}rt.inlineRef=Iz;var Cz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Id(t){for(let e in t){if(Cz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Id)||typeof r=="object"&&Id(r))return!0}return!1}function jy(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Pz.has(r)&&(typeof t[r]=="object"&&(0,Ez.eachItem)(t[r],n=>e+=jy(n)),e===1/0))return 1/0}return e}function Zy(t,e="",r){r!==!1&&(e=eo(e));let n=t.parse(e);return Dy(t,n)}rt.getFullPath=Zy;function Dy(t,e){return t.serialize(e).split("#")[0]+"#"}rt._getFullPath=Dy;var Az=/#\/?$/;function eo(t){return t?t.replace(Az,""):""}rt.normalizeId=eo;function Oz(t,e,r){return r=eo(r),t.resolve(e,r)}rt.resolveUrl=Oz;var Nz=/^[a-z_][-a-z0-9._]*$/i;function Mz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=eo(t[r]||e),s={"":o},i=Zy(n,o,!1),a={},c=new Set;return Rz(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=eo(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!==eo(g)&&(y[0]==="#"?(u(d,a[y],y),a[y]=d):this.refs[y]=g),y}function v(y){if(typeof y=="string"){if(!Nz.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(d,m,p){if(m!==void 0&&!zz(d,m))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}rt.getSchemaRefs=Mz});var ds=z(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.getData=Rr.KeywordCxt=Rr.validateFunctionCode=void 0;var Hy=vy(),Ly=as(),Ad=$d(),Xi=as(),jz=Ty(),ls=Iy(),Cd=Ay(),Z=W(),U=sr(),Zz=cs(),ir=oe(),us=is();function Dz(t){if(Jy(t)&&(Wy(t),Vy(t))){Fz(t);return}By(t,()=>(0,Hy.topBoolOrEmptySchema)(t))}Rr.validateFunctionCode=Dz;function By({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Z._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{t.code((0,Z._)`"use strict"; ${qy(r,o)}`),qz(t,o),t.code(s)}):t.func(e,(0,Z._)`${U.default.data}, ${Lz(o)}`,n.$async,()=>t.code(qy(r,o)).code(s))}function Lz(t){return(0,Z._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${t.dynamicRef?(0,Z._)`, ${U.default.dynamicAnchors}={}`:Z.nil}}={}`}function qz(t,e){t.if(U.default.valCxt,()=>{t.var(U.default.instancePath,(0,Z._)`${U.default.valCxt}.${U.default.instancePath}`),t.var(U.default.parentData,(0,Z._)`${U.default.valCxt}.${U.default.parentData}`),t.var(U.default.parentDataProperty,(0,Z._)`${U.default.valCxt}.${U.default.parentDataProperty}`),t.var(U.default.rootData,(0,Z._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,Z._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{t.var(U.default.instancePath,(0,Z._)`""`),t.var(U.default.parentData,(0,Z._)`undefined`),t.var(U.default.parentDataProperty,(0,Z._)`undefined`),t.var(U.default.rootData,U.default.data),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,Z._)`{}`)})}function Fz(t){let{schema:e,opts:r,gen:n}=t;By(t,()=>{r.$comment&&e.$comment&&Gy(t),Jz(t),n.let(U.default.vErrors,null),n.let(U.default.errors,0),r.unevaluated&&Uz(t),Ky(t),Gz(t)})}function Uz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Z._)`${r}.evaluated`),e.if((0,Z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Z._)`${t.evaluated}.props`,(0,Z._)`undefined`)),e.if((0,Z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Z._)`${t.evaluated}.items`,(0,Z._)`undefined`))}function qy(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Z._)`/*# sourceURL=${r} */`:Z.nil}function Hz(t,e){if(Jy(t)&&(Wy(t),Vy(t))){Bz(t,e);return}(0,Hy.boolOrEmptySchema)(t,e)}function Vy({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 Jy(t){return typeof t.schema!="boolean"}function Bz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Gy(t),Wz(t),Kz(t);let s=n.const("_errs",U.default.errors);Ky(t,s),n.var(e,(0,Z._)`${s} === ${U.default.errors}`)}function Wy(t){(0,ir.checkUnknownRules)(t),Vz(t)}function Ky(t,e){if(t.opts.jtd)return Fy(t,[],!1,e);let r=(0,Ly.getSchemaTypes)(t.schema),n=(0,Ly.coerceAndCheckDataType)(t,r);Fy(t,r,!n,e)}function Vz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ir.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Jz(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ir.checkStrictMode)(t,"default is ignored in the schema root")}function Wz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Zz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Kz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Gy({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Z._)`${U.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Z._)`${U.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Gz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Z._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,Z._)`new ${o}(${U.default.vErrors})`)):(e.assign((0,Z._)`${n}.errors`,U.default.vErrors),s.unevaluated&&Xz(t),e.return((0,Z._)`${U.default.errors} === 0`))}function Xz({gen:t,evaluated:e,props:r,items:n}){r instanceof Z.Name&&t.assign((0,Z._)`${e}.props`,r),n instanceof Z.Name&&t.assign((0,Z._)`${e}.items`,n)}function Fy(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,ir.schemaHasRulesButRef)(s,l))){o.block(()=>Yy(t,"$ref",l.all.$ref.definition));return}c.jtd||Yz(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,Ad.shouldUseGroup)(s,m)&&(m.type?(o.if((0,Xi.checkDataType)(m.type,i,c.strictNumbers)),Uy(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,Xi.reportTypeError)(t)),o.endIf()):Uy(t,m),a||o.if((0,Z._)`${U.default.errors} === ${n||0}`))}}function Uy(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,jz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Ad.shouldUseRule)(n,s)&&Yy(t,s.keyword,s.definition,e.type)})}function Yz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Qz(t,e),t.opts.allowUnionTypes||eR(t,e),tR(t,t.dataTypes))}function Qz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Xy(t.dataTypes,r)||Od(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),nR(t,e)}}function eR(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Od(t,"use allowUnionTypes to allow union type keyword")}function tR(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ad.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>rR(e,i))&&Od(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function rR(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Xy(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function nR(t,e){let r=[];for(let n of t.dataTypes)Xy(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Od(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ir.checkStrictMode)(t,e,t.opts.strictTypes)}var Yi=class{constructor(e,r,n){if((0,ls.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,ir.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",Qy(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ls.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,Z.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,Z.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,Z._)`${r} !== undefined && (${(0,Z.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?us.reportExtraError:us.reportError)(this,this.def.error,r)}$dataError(){(0,us.reportError)(this,this.def.$dataError||us.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,us.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=Z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Z.nil,r=Z.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Z.or)((0,Z._)`${o} === undefined`,r)),e!==Z.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Z.or)(i(),a());function i(){if(n.length){if(!(r instanceof Z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Z._)`${(0,Xi.checkDataTypes)(c,r,s.opts.strictNumbers,Xi.DataType.Wrong)}`}return Z.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Z._)`!${c}(${r})`}return Z.nil}}subschema(e,r){let n=(0,Cd.getSubschema)(this.it,e);(0,Cd.extendSubschemaData)(n,this.it,e),(0,Cd.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Hz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ir.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ir.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,Z.Name)),!0}};Rr.KeywordCxt=Yi;function Yy(t,e,r,n){let o=new Yi(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ls.funcKeywordCode)(o,r):"macro"in r?(0,ls.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ls.funcKeywordCode)(o,r)}var oR=/^\/(?:[^~]|~0|~1)*$/,sR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Qy(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return U.default.rootData;if(t[0]==="/"){if(!oR.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=U.default.rootData}else{let u=sR.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,Z._)`${s}${(0,Z.getProperty)((0,ir.unescapeJsonPointer)(u))}`,i=(0,Z._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Rr.getData=Qy});var Qi=z(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Nd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Md.default=Nd});var fs=z(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var jd=cs(),Zd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,jd.resolveUrl)(e,r,n),this.missingSchema=(0,jd.normalizeId)((0,jd.getFullPath)(e,this.missingRef))}};Dd.default=Zd});var ta=z(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.resolveSchema=gt.getCompilingSchema=gt.resolveRef=gt.compileSchema=gt.SchemaEnv=void 0;var Et=W(),iR=Qi(),yn=sr(),zt=cs(),e_=oe(),aR=ds(),to=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,zt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};gt.SchemaEnv=to;function qd(t){let e=t_.call(this,t);if(e)return e;let r=(0,zt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Et.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:iR.default,code:(0,Et._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:yn.default.data,parentData:yn.default.parentData,parentDataProperty:yn.default.parentDataProperty,dataNames:[yn.default.data],dataPathArr:[Et.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Et.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Et.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Et._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,aR.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(yn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${yn.default.self}`,`${yn.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 Et.Name?void 0:f,items:g instanceof Et.Name?void 0:g,dynamicProps:f instanceof Et.Name,dynamicItems:g instanceof Et.Name},p.source&&(p.source.evaluated=(0,Et.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)}}gt.compileSchema=qd;function cR(t,e,r){var n;r=(0,zt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=dR.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 to({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=uR.call(this,s)}gt.resolveRef=cR;function uR(t){return(0,zt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:qd.call(this,t)}function t_(t){for(let e of this._compilations)if(lR(e,t))return e}gt.getCompilingSchema=t_;function lR(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function dR(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ea.call(this,t,e)}function ea(t,e){let r=this.opts.uriResolver.parse(e),n=(0,zt._getFullPath)(this.opts.uriResolver,r),o=(0,zt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Ld.call(this,r,t);let s=(0,zt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ea.call(this,t,i);return typeof a?.schema!="object"?void 0:Ld.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||qd.call(this,i),s===(0,zt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,zt.resolveUrl)(this.opts.uriResolver,o,u)),new to({schema:a,schemaId:c,root:t,baseId:o})}return Ld.call(this,r,i)}}gt.resolveSchema=ea;var fR=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ld(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,e_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!fR.has(a)&&u&&(e=(0,zt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,e_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,zt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ea.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new to({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var r_=z((Q4,pR)=>{pR.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 Jd=z((eL,l_)=>{"use strict";var mR=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ud=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),hR=RegExp.prototype.test.bind(/^\d*$/u),_n=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Hd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Bd=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),gR=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),nt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)nt[e]="%"+t[e>>4]+t[e&15]}function qe(t){return t<2048?nt[192|t>>6]+nt[128|t&63]:t<65536?nt[224|t>>12]+nt[128|t>>6&63]+nt[128|t&63]:nt[240|t>>18]+nt[128|t>>12&63]+nt[128|t>>6&63]+nt[128|t&63]}function yR(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 _R=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),vR=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),xR=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),bR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function wR(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!xR(t[e])){if(t[e]==="%"&&e+2<t.length&&_n(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function n_(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 $R(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||!Ud(c))return;s+=2;continue}if(!_R(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:n_(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 n_(i)}function Fd(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&&vR(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(kR(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),!wR(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=$R(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function kR(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function s_(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("")}function SR(t){if(t===""||t[0]==="/")return s_(t);let e=t.split("/"),r=e.length-1,n=[],o=!1;for(let s=0;s<=r;s++){let i=e[s];i==="."||i===".."?(i===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),o=s===r):n.push(i)}return o&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var TR={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ER=/[@/?#:]/g,zR=/[@/?#]/g;function i_(t,e){let r=e?zR:ER;return r.lastIndex=0,t.replace(r,n=>TR[n])}function a_(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(_n(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Hd(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function RR(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(_n(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Hd(i)?e+=i:e+="%"+s,r+=2;continue}}if(o_(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=u_(o)?n:nt[o];else if(o<55296||o>57343)e+=qe(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=qe(65536+(o-55296<<10)+(s-56320)),r++):e+=qe(65533)}else e+=qe(65533)}}return e}function PR(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(_n(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),o_(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=nt[i];else if(i<55296||i>57343)r+=qe(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=qe(65536+(i-55296<<10)+(a-56320)),o++):r+=qe(65533)}else r+=qe(65533)}}return r}function Vd(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(_n(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=nt[s];else if(s<55296||s>57343)r+=qe(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=qe(65536+(s-55296<<10)+(i-56320)),n++):r+=qe(65533)}else r+=qe(65533)}}return r}function c_(t){return Vd(t,gR)}function IR(t){return Vd(t,Bd)}function CR(t){return Vd(t,Bd)}function u_(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 AR(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(_n(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Hd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Bd(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=u_(o)?n:nt[o];else if(o<55296||o>57343)e+=qe(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=qe(65536+(o-55296<<10)+(s-56320)),r++):e+=qe(65533)}else e+=qe(65533)}}return e}function OR(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(_n(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function NR(t){let e=[];if(t.userinfo!==void 0&&(e.push(c_(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!Ud(r)){let n=Fd(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=a_(r,!0),n=Fd(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=i_(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!hR(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}l_.exports={nonSimpleDomain:bR,recomposeAuthority:NR,reescapeHostDelimiters:i_,normalizePercentEncoding:a_,normalizePathEncoding:RR,serializePathEncoding:PR,normalizeQueryFragmentEncoding:AR,encodeUserinfo:c_,encodeQuery:IR,encodeFragment:CR,escapePreservingEscapes:OR,removeDotSegments:s_,removeDotSegmentsRelative:SR,isIPv4:Ud,isUUID:mR,normalizeIPv6:Fd,stringArrayToHexStripped:yR}});var h_=z((tL,m_)=>{"use strict";var{isUUID:MR}=Jd(),jR=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,ZR=["http","https","ws","wss","urn","urn:uuid"];function DR(t){return ZR.indexOf(t)!==-1}function Wd(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 d_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function f_(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 LR(t){return t.secure=Wd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function qR(t){if((t.port===(Wd(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 FR(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(jR);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=Kd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function UR(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=Kd(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 HR(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!MR(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function BR(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var p_={scheme:"http",domainHost:!0,parse:d_,serialize:f_},VR={scheme:"https",domainHost:p_.domainHost,parse:d_,serialize:f_},ra={scheme:"ws",domainHost:!0,parse:LR,serialize:qR},JR={scheme:"wss",domainHost:ra.domainHost,parse:ra.parse,serialize:ra.serialize},WR={scheme:"urn",parse:FR,serialize:UR,skipNormalize:!0},KR={scheme:"urn:uuid",parse:HR,serialize:BR,skipNormalize:!0},na={http:p_,https:VR,ws:ra,wss:JR,urn:WR,"urn:uuid":KR};Object.setPrototypeOf(na,null);function Kd(t){return t&&(na[t]||na[t.toLowerCase()])||void 0}m_.exports={wsIsSecure:Wd,SCHEMES:na,isValidSchemeName:DR,getSchemeHandler:Kd}});var P_=z((rL,ca)=>{"use strict";var{normalizeIPv6:x_,removeDotSegments:ms,removeDotSegmentsRelative:b_,recomposeAuthority:GR,normalizePercentEncoding:Gd,normalizePathEncoding:XR,serializePathEncoding:g_,normalizeQueryFragmentEncoding:y_,encodeQuery:YR,encodeFragment:QR,reescapeHostDelimiters:eP,isIPv4:w_,nonSimpleDomain:tP}=Jd(),{SCHEMES:$_,getSchemeHandler:Xd}=h_(),k_=/^[A-Za-z][A-Za-z0-9+.-]*$/u,S_="URI scheme is malformed.",oa="URI host is malformed.",rP=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function __(t){let e=String(t);if(!k_.test(e))throw new TypeError(S_);return e}function nP(t,e){return typeof t=="string"?t=fP(t,e):typeof t=="object"&&(t=ia(vn(t,e),e)),t}function oP(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}=sa(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:m,malformedSchemeSpecific:p,malformedHost:f,malformedScheme:g}=sa(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=T_(o,l,n,!0),_=Xd(r&&r.scheme||h.scheme),v=h.host,y=v!==void 0&&v!==""&&(w_(v)||x_(v).isIPV6);if(z_(h,r||{},_,y))throw new Error(oa);E_(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,vn(h,n)}function T_(t,e,r,n){let o={};if(n||(t=ia(vn(t,r),r),e=ia(vn(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=ms(e.path||""),o.query=e.query;else{if(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=ms(e.path||""),o.query=e.query;else{if(!e.path)o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query;else{if(e.path[0]==="/")o.path=ms(e.path);else{let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0;s&&!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=t.scheme===void 0&&!s&&o.path[0]!=="/"?b_(o.path):ms(o.path)}o.query=e.query}o.userinfo=t.userinfo,o.host=t.host,o.port=t.port}o.scheme=t.scheme}return o.fragment=e.fragment,o}function sP(t,e,r){let n=v_(t,r),o=v_(e,r);return n!==void 0&&o!==void 0&&n===o}function vn(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=__(r.scheme));let s=Xd(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=(r.scheme===void 0||n.reference==="suffix")&&!i,c=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=Gd(r.path):r.path=g_(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=__(r.scheme),o.push(r.scheme,":"));let u=GR(r);if(u!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(u),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let l=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=a&&l[0]!=="/"?b_(l):ms(l)),a&&(l=g_(l,!0)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),o.push(l)}return r.query!==void 0&&o.push("?",YR(r.query)),r.fragment!==void 0&&o.push("#",QR(r.fragment)),o.join("")}var iP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,aP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,cP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function uP(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 ps(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 aa(t){return t[0]==="["&&t[t.length-1]==="]"}function lP(t){let e=t[4];return ps(t[3])||e!==void 0&&!aa(e)&&ps(e)||ps(t[6])||ps(t[7])||ps(t[8])}function E_(t,e,r,n){if(z_(t,e,r,n))return t.error=t.error||oa,!0;if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!aa(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&tP(t.host)){let o;try{o=new URL("http://"+t.host)}catch(s){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!dP(o))return t.error=t.error||oa,!0;t.host=o.hostname}return!1}function z_(t,e,r,n){return!!(t.host&&n===!1&&!aa(t.host)&&(e.domainHost||r&&r.domainHost)&&rP.test(t.host))}function dP(t){return t.username===""&&t.password===""&&t.port===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&t.hostname!==""}function sa(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(aP);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let m=t.match(cP);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(iP);if(p){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&&(k_.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||S_,u=!0)),s=lP(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let f=uP(n,p);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(w_(n.host)===!1){let _=aa(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=x_(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||oa,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=Xd(r.scheme||n.scheme);if(c||(a=E_(n,r,g,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let h=l?n.host:Gd(n.host,!0);l||(h=Gd(h.toLowerCase())),n.host=l||r.scheme!=="null"?eP(h,l):h}(!g||g&&!g.skipNormalize)&&(n.path&&(n.path=XR(n.path)),n.query&&(n.query=y_(n.query)),n.fragment&&(n.fragment=y_(n.fragment))),g&&g.parse&&(g.parse(n,r),g===$_.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 ia(t,e){return sa(t,e).parsed}function fP(t,e){return R_(t,e).normalized}function R_(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=sa(t,e);return{normalized:n||o||s||i||a?t:vn(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function v_(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:vn(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=R_(r,e);return o||s||i||a||c?void 0:n}var Yd={SCHEMES:$_,normalize:nP,resolve:oP,resolveComponent:T_,equal:sP,serialize:vn,parse:ia};ca.exports=Yd;ca.exports.default=Yd;ca.exports.fastUri=Yd});var C_=z(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var I_=P_();I_.code='require("ajv/dist/runtime/uri").default';Qd.default=I_});var L_=z(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.CodeGen=Oe.Name=Oe.nil=Oe.stringify=Oe.str=Oe._=Oe.KeywordCxt=void 0;var pP=ds();Object.defineProperty(Oe,"KeywordCxt",{enumerable:!0,get:function(){return pP.KeywordCxt}});var ro=W();Object.defineProperty(Oe,"_",{enumerable:!0,get:function(){return ro._}});Object.defineProperty(Oe,"str",{enumerable:!0,get:function(){return ro.str}});Object.defineProperty(Oe,"stringify",{enumerable:!0,get:function(){return ro.stringify}});Object.defineProperty(Oe,"nil",{enumerable:!0,get:function(){return ro.nil}});Object.defineProperty(Oe,"Name",{enumerable:!0,get:function(){return ro.Name}});Object.defineProperty(Oe,"CodeGen",{enumerable:!0,get:function(){return ro.CodeGen}});var mP=Qi(),j_=fs(),hP=wd(),hs=ta(),gP=W(),gs=cs(),ua=as(),tf=oe(),A_=r_(),yP=C_(),Z_=(t,e)=>new RegExp(t,e);Z_.code="new RegExp";var _P=["removeAdditional","useDefaults","coerceTypes"],vP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),xP={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."},bP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},O_=200;function wP(t){var e,r,n,o,s,i,a,c,u,l,d,m,p,f,g,h,_,v,y,x,$,N,A,ce,ue;let ze=t.strict,H=(e=t.code)===null||e===void 0?void 0:e.optimize,ve=H===!0||H===void 0?1:H||0,At=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Z_,Dr=(o=t.uriResolver)!==null&&o!==void 0?o:yP.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:ze)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:ze)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:ze)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:ze)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:ze)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:ve,regExp:At}:{optimize:ve,regExp:At},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:O_,loopEnum:(h=t.loopEnum)!==null&&h!==void 0?h:O_,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:(N=t.validateSchema)!==null&&N!==void 0?N:!0,validateFormats:(A=t.validateFormats)!==null&&A!==void 0?A:!0,unicodeRegExp:(ce=t.unicodeRegExp)!==null&&ce!==void 0?ce:!0,int32range:(ue=t.int32range)!==null&&ue!==void 0?ue:!0,uriResolver:Dr}}var ys=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,...wP(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new gP.ValueScope({scope:{},prefixes:vP,es5:r,lines:n}),this.logger=zP(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,hP.getRules)(),N_.call(this,xP,e,"NOT SUPPORTED"),N_.call(this,bP,e,"DEPRECATED","warn"),this._metaOpts=TP.call(this),e.formats&&kP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&SP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),$P.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=A_;n==="id"&&(o={...A_},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 j_.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,gs.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=M_.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new hs.SchemaEnv({schema:{},schemaId:n});if(r=hs.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=M_.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,gs.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(PP.call(this,n,r),!r)return(0,tf.eachItem)(n,s=>ef.call(this,s)),this;CP.call(this,r);let o={...r,type:(0,ua.getJSONTypes)(r.type),schemaType:(0,ua.getJSONTypes)(r.schemaType)};return(0,tf.eachItem)(n,o.type.length===0?s=>ef.call(this,s,o):s=>o.type.forEach(i=>ef.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]=D_(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,gs.normalizeId)(i||n);let u=gs.getSchemaRefs.call(this,e,n);return c=new hs.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):hs.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{hs.compileSchema.call(this,e)}finally{this.opts=r}}};ys.ValidationError=mP.default;ys.MissingRefError=j_.default;Oe.default=ys;function N_(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 M_(t){return t=(0,gs.normalizeId)(t),this.schemas[t]||this.refs[t]}function $P(){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 kP(){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 TP(){let t={...this.opts};for(let e of _P)delete t[e];return t}var EP={log(){},warn(){},error(){}};function zP(t){if(t===!1)return EP;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 RP=/^[a-z_$][a-z0-9_$:-]*$/i;function PP(t,e){let{RULES:r}=this;if((0,tf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!RP.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 ef(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,ua.getJSONTypes)(e.type),schemaType:(0,ua.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 CP(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=D_(e)),t.validateSchema=this.compile(e,!0))}var AP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function D_(t){return{anyOf:[t,AP]}}});var q_=z(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var OP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};rf.default=OP});var B_=z(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.callRef=xn.getValidate=void 0;var NP=fs(),F_=ht(),ot=W(),no=sr(),U_=ta(),la=oe(),MP={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=U_.resolveRef.call(c,u,o,r);if(l===void 0)throw new NP.default(n.opts.uriResolver,o,r);if(l instanceof U_.SchemaEnv)return m(l);return p(l);function d(){if(s===u)return da(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return da(t,(0,ot._)`${f}.validate`,u,u.$async)}function m(f){let g=H_(t,f);da(t,g,f,f.$async)}function p(f){let g=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,ot.stringify)(f)}:{ref:f}),h=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:ot.nil,topSchemaRef:g,errSchemaPath:r},h);t.mergeEvaluated(_),t.ok(h)}}};function H_(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ot._)`${r.scopeValue("wrapper",{ref:e})}.validate`}xn.getValidate=H_;function da(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?no.default.this:ot.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,ot._)`await ${(0,F_.callValidateCode)(t,e,u)}`),p(e),i||o.assign(f,!0)},g=>{o.if((0,ot._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),m(g),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,F_.callValidateCode)(t,e,u),()=>p(e),()=>m(e))}function m(f){let g=(0,ot._)`${f}.errors`;o.assign(no.default.vErrors,(0,ot._)`${no.default.vErrors} === null ? ${g} : ${no.default.vErrors}.concat(${g})`),o.assign(no.default.errors,(0,ot._)`${no.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=la.mergeEvaluated.props(o,h.props,s.props));else{let _=o.var("props",(0,ot._)`${f}.evaluated.props`);s.props=la.mergeEvaluated.props(o,_,s.props,ot.Name)}if(s.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(s.items=la.mergeEvaluated.items(o,h.items,s.items));else{let _=o.var("items",(0,ot._)`${f}.evaluated.items`);s.items=la.mergeEvaluated.items(o,_,s.items,ot.Name)}}}xn.callRef=da;xn.default=MP});var V_=z(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var jP=q_(),ZP=B_(),DP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",jP.default,ZP.default];nf.default=DP});var J_=z(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var fa=W(),Pr=fa.operators,pa={maximum:{okStr:"<=",ok:Pr.LTE,fail:Pr.GT},minimum:{okStr:">=",ok:Pr.GTE,fail:Pr.LT},exclusiveMaximum:{okStr:"<",ok:Pr.LT,fail:Pr.GTE},exclusiveMinimum:{okStr:">",ok:Pr.GT,fail:Pr.LTE}},LP={message:({keyword:t,schemaCode:e})=>(0,fa.str)`must be ${pa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,fa._)`{comparison: ${pa[t].okStr}, limit: ${e}}`},qP={keyword:Object.keys(pa),type:"number",schemaType:"number",$data:!0,error:LP,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,fa._)`${r} ${pa[e].fail} ${n} || isNaN(${r})`)}};of.default=qP});var W_=z(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var _s=W(),FP={message:({schemaCode:t})=>(0,_s.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,_s._)`{multipleOf: ${t}}`},UP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:FP,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,_s._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,_s._)`${i} !== parseInt(${i})`;t.fail$data((0,_s._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};sf.default=UP});var G_=z(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});function K_(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}af.default=K_;K_.code='require("ajv/dist/runtime/ucs2length").default'});var X_=z(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var bn=W(),HP=oe(),BP=G_(),VP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,bn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,bn._)`{limit: ${t}}`},JP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:VP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?bn.operators.GT:bn.operators.LT,i=o.opts.unicode===!1?(0,bn._)`${r}.length`:(0,bn._)`${(0,HP.useFunc)(t.gen,BP.default)}(${r})`;t.fail$data((0,bn._)`${i} ${s} ${n}`)}};cf.default=JP});var Y_=z(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var WP=ht(),KP=oe(),oo=W(),GP={message:({schemaCode:t})=>(0,oo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,oo._)`{pattern: ${t}}`},XP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:GP,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,oo._)`new RegExp`:(0,KP.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,oo._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,oo._)`!${l}`)}else{let c=(0,WP.usePattern)(t,o);t.fail$data((0,oo._)`!${c}.test(${r})`)}}};uf.default=XP});var Q_=z(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var vs=W(),YP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,vs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,vs._)`{limit: ${t}}`},QP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:YP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?vs.operators.GT:vs.operators.LT;t.fail$data((0,vs._)`Object.keys(${r}).length ${o} ${n}`)}};lf.default=QP});var e0=z(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var xs=ht(),bs=W(),e1=oe(),t1={message:({params:{missingProperty:t}})=>(0,bs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,bs._)`{missingProperty: ${t}}`},r1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:t1,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,e1.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(bs.nil,d);else for(let p of r)(0,xs.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,xs.checkMissingProp)(t,r,p)),(0,xs.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,xs.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function m(p,f){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,xs.propertyInData)(e,o,p,a.ownProperties)),e.if((0,bs.not)(f),()=>{t.error(),e.break()})},bs.nil)}}};df.default=r1});var t0=z(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var ws=W(),n1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ws.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ws._)`{limit: ${t}}`},o1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:n1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ws.operators.GT:ws.operators.LT;t.fail$data((0,ws._)`${r}.length ${o} ${n}`)}};ff.default=o1});var ma=z(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var r0=Pd();r0.code='require("ajv/dist/runtime/equal").default';pf.default=r0});var n0=z(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var mf=as(),Ne=W(),s1=oe(),i1=ma(),a1={message:({params:{i:t,j:e}})=>(0,Ne.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ne._)`{i: ${t}, j: ${e}}`},c1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:a1,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,mf.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ne._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Ne._)`${r}.length`),g=e.let("j");t.setParams({i:f,j:g}),e.assign(c,!0),e.if((0,Ne._)`${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,mf.checkDataTypes)(u,h,a.opts.strictNumbers,mf.DataType.Wrong),v=e.const("indices",(0,Ne._)`{}`);e.for((0,Ne._)`;${f}--;`,()=>{e.let(h,(0,Ne._)`${r}[${f}]`),e.if(_,(0,Ne._)`continue`),u.length>1&&e.if((0,Ne._)`typeof ${h} == "string"`,(0,Ne._)`${h} += "_"`),e.if((0,Ne._)`typeof ${v}[${h}] == "number"`,()=>{e.assign(g,(0,Ne._)`${v}[${h}]`),t.error(),e.assign(c,!1).break()}).code((0,Ne._)`${v}[${h}] = ${f}`)})}function p(f,g){let h=(0,s1.useFunc)(e,i1.default),_=e.name("outer");e.label(_).for((0,Ne._)`;${f}--;`,()=>e.for((0,Ne._)`${g} = ${f}; ${g}--;`,()=>e.if((0,Ne._)`${h}(${r}[${f}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};hf.default=c1});var o0=z(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var gf=W(),u1=oe(),l1=ma(),d1={message:"must be equal to constant",params:({schemaCode:t})=>(0,gf._)`{allowedValue: ${t}}`},f1={keyword:"const",$data:!0,error:d1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,gf._)`!${(0,u1.useFunc)(e,l1.default)}(${r}, ${o})`):t.fail((0,gf._)`${s} !== ${r}`)}};yf.default=f1});var s0=z(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var $s=W(),p1=oe(),m1=ma(),h1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,$s._)`{allowedValues: ${t}}`},g1={keyword:"enum",schemaType:"array",$data:!0,error:h1,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,p1.useFunc)(e,m1.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,$s.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,$s._)`${u()}(${r}, ${p})`,()=>e.assign(l,!0).break()))}function m(p,f){let g=o[f];return typeof g=="object"&&g!==null?(0,$s._)`${u()}(${r}, ${p}[${f}])`:(0,$s._)`${r} === ${g}`}}};_f.default=g1});var i0=z(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var y1=J_(),_1=W_(),v1=X_(),x1=Y_(),b1=Q_(),w1=e0(),$1=t0(),k1=n0(),S1=o0(),T1=s0(),E1=[y1.default,_1.default,v1.default,x1.default,b1.default,w1.default,$1.default,k1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},S1.default,T1.default];vf.default=E1});var bf=z(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.validateAdditionalItems=void 0;var wn=W(),xf=oe(),z1={message:({params:{len:t}})=>(0,wn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,wn._)`{limit: ${t}}`},R1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:z1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,xf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}a0(t,n)}};function a0(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,wn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,wn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,xf.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,wn._)`${a} <= ${e.length}`);r.if((0,wn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:xf.Type.Num},u),i.allErrors||r.if((0,wn.not)(u),()=>r.break())})}}ks.validateAdditionalItems=a0;ks.default=R1});var wf=z(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.validateTuple=void 0;var c0=W(),ha=oe(),P1=ht(),I1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return u0(t,"additionalItems",e);r.items=!0,!(0,ha.alwaysValidSchema)(r,e)&&t.ok((0,P1.validateArray)(t))}};function u0(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=ha.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,c0._)`${s}.length`);r.forEach((d,m)=>{(0,ha.alwaysValidSchema)(a,d)||(n.if((0,c0._)`${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,ha.checkStrictMode)(a,h,m.strictTuples)}}}Ss.validateTuple=u0;Ss.default=I1});var l0=z($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var C1=wf(),A1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,C1.validateTuple)(t,"items")};$f.default=A1});var f0=z(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var d0=W(),O1=oe(),N1=ht(),M1=bf(),j1={message:({params:{len:t}})=>(0,d0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,d0._)`{limit: ${t}}`},Z1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:j1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,O1.alwaysValidSchema)(n,e)&&(o?(0,M1.validateAdditionalItems)(t,o):t.ok((0,N1.validateArray)(t)))}};kf.default=Z1});var p0=z(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var yt=W(),ga=oe(),D1={message:({params:{min:t,max:e}})=>e===void 0?(0,yt.str)`must contain at least ${t} valid item(s)`:(0,yt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,yt._)`{minContains: ${t}}`:(0,yt._)`{minContains: ${t}, maxContains: ${e}}`},L1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:D1,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,yt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ga.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ga.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ga.alwaysValidSchema)(s,r)){let g=(0,yt._)`${l} >= ${i}`;a!==void 0&&(g=(0,yt._)`${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,yt._)`${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:ga.Type.Num,compositeRule:!0},g),h()})}function f(g){e.code((0,yt._)`${g}++`),a===void 0?e.if((0,yt._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,yt._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,yt._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};Sf.default=L1});var g0=z(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.validateSchemaDeps=Ft.validatePropertyDeps=Ft.error=void 0;var Tf=W(),q1=oe(),Ts=ht();Ft.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Tf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Tf._)`{property: ${t},
|
|
30
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let p=n.external.registry.get(l[0])?.id;if(e!==l[0]&&p){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let m=this.seen.get(l),p=m.def??m.schema,f={...p};if(m.ref===null)return;let h=m.ref;if(m.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),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 qh=Q(()=>{});var He=Q(()=>{Dn();Zc();Cc();Rh();Qs();Hc();Ut();Ys();si();Au();Fc();Dh();Zh();Lh();qh()});var wl=Q(()=>{He()});var Uo={};To(Uo,{ZodISODate:()=>Bh,ZodISODateTime:()=>Hh,ZodISODuration:()=>Jh,ZodISOTime:()=>Vh,date:()=>kl,datetime:()=>$l,duration:()=>Tl,time:()=>Sl});function $l(t){return Ah(Hh,t)}function kl(t){return Ih(Bh,t)}function Sl(t){return Nh(Vh,t)}function Tl(t){return Mh(Jh,t)}var Hh,Bh,Vh,Jh,El=Q(()=>{He();zl();Hh=w("ZodISODateTime",(t,e)=>{kh.init(t,e),be.init(t,e)});Bh=w("ZodISODate",(t,e)=>{Sh.init(t,e),be.init(t,e)});Vh=w("ZodISOTime",(t,e)=>{Th.init(t,e),be.init(t,e)});Jh=w("ZodISODuration",(t,e)=>{Eh.init(t,e),be.init(t,e)})});var Wh,_Z,Fo,Rl=Q(()=>{He();He();Wh=(t,e)=>{Ks.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Pc(t,r)},flatten:{value:r=>Rc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},_Z=w("ZodError",Wh),Fo=w("ZodError",Wh,{Parent:Error})});var Gh,Kh,Xh,Yh,Pl=Q(()=>{He();Rl();Gh=Oc(Fo),Kh=Ic(Fo),Xh=Mc(Fo),Yh=jc(Fo)});function b(t){return Iu(qk,t)}function le(t){return rl(ng,t)}function eg(t){return nl(sS,t)}function Pe(t){return ol(iS,t)}function og(t){return sl(aS,t)}function we(){return il(cS)}function lS(t){return al(uS,t)}function ne(t,e){return jh(dS,t,e)}function C(t,e){let r={type:"object",get shape(){return re.assignProp(this,"shape",{...t}),this.shape},...re.normalizeParams(e)};return new sg(r)}function Be(t,e){return new sg({type:"object",get shape(){return re.assignProp(this,"shape",{...t}),this.shape},catchall:we(),...re.normalizeParams(e)})}function ye(t,e){return new ig({type:"union",options:t,...re.normalizeParams(e)})}function Al(t,e,r){return new fS({type:"union",options:e,discriminator:t,...re.normalizeParams(r)})}function gi(t,e){return new pS({type:"intersection",left:t,right:e})}function ge(t,e,r){return new mS({type:"record",keyType:t,valueType:e,...re.normalizeParams(r)})}function et(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Cl({type:"enum",entries:r,...re.normalizeParams(e)})}function M(t,e){return new hS({type:"literal",values:Array.isArray(t)?t:[t],...re.normalizeParams(e)})}function ag(t){return new gS({type:"transform",transform:t})}function $e(t){return new cg({type:"optional",innerType:t})}function tg(t){return new yS({type:"nullable",innerType:t})}function vS(t,e){return new _S({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function bS(t,e){return new xS({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function wS(t,e){return new ug({type:"nonoptional",innerType:t,...re.normalizeParams(e)})}function kS(t,e){return new $S({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Ol(t,e){return new SS({type:"pipe",in:t,out:e})}function ES(t){return new TS({type:"readonly",innerType:t})}function zS(t){let e=new Ae({check:"custom"});return e._zod.check=t,e}function dg(t,e){return _l(lg,t??(()=>!0),e)}function RS(t,e={}){return vl(lg,t,e)}function PS(t){let e=zS(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(re.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(re.issue(o))}},t(r.value,r)));return e}function Il(t,e){return Ol(ag(t),e)}var Se,rg,qk,be,Uk,Qh,hi,Fk,Hk,Bk,Vk,Jk,Wk,Gk,Kk,Xk,Yk,Qk,eS,tS,rS,nS,oS,ng,sS,iS,aS,cS,uS,dS,sg,ig,fS,pS,mS,Cl,hS,gS,cg,yS,_S,xS,ug,$S,SS,TS,lg,zl=Q(()=>{He();He();wl();El();Pl();Se=w("ZodType",(t,e)=>(de.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)=>ct(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Gh(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Xh(t,r,n),t.parseAsync=async(r,n)=>Kh(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Yh(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(RS(r,n)),t.superRefine=r=>t.check(PS(r)),t.overwrite=r=>t.check(dn(r)),t.optional=()=>$e(t),t.nullable=()=>tg(t),t.nullish=()=>$e(tg(t)),t.nonoptional=r=>wS(t,r),t.array=()=>ne(t),t.or=r=>ye([t,r]),t.and=r=>gi(t,r),t.transform=r=>Ol(t,ag(r)),t.default=r=>vS(t,r),t.prefault=r=>bS(t,r),t.catch=r=>kS(t,r),t.pipe=r=>Ol(t,r),t.readonly=()=>ES(t),t.describe=r=>{let n=t.clone();return br.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return br.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return br.get(t);let n=t.clone();return br.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),rg=w("_ZodString",(t,e)=>{Zo.init(t,e),Se.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(cl(...n)),t.includes=(...n)=>t.check(dl(...n)),t.startsWith=(...n)=>t.check(fl(...n)),t.endsWith=(...n)=>t.check(pl(...n)),t.min=(...n)=>t.check(Un(...n)),t.max=(...n)=>t.check(li(...n)),t.length=(...n)=>t.check(di(...n)),t.nonempty=(...n)=>t.check(Un(1,...n)),t.lowercase=n=>t.check(ul(n)),t.uppercase=n=>t.check(ll(n)),t.trim=()=>t.check(hl()),t.normalize=(...n)=>t.check(ml(...n)),t.toLowerCase=()=>t.check(gl()),t.toUpperCase=()=>t.check(yl())}),qk=w("ZodString",(t,e)=>{Zo.init(t,e),rg.init(t,e),t.email=r=>t.check(Nu(Uk,r)),t.url=r=>t.check(Lu(Fk,r)),t.jwt=r=>t.check(tl(oS,r)),t.emoji=r=>t.check(qu(Hk,r)),t.guid=r=>t.check(ii(Qh,r)),t.uuid=r=>t.check(Mu(hi,r)),t.uuidv4=r=>t.check(ju(hi,r)),t.uuidv6=r=>t.check(Zu(hi,r)),t.uuidv7=r=>t.check(Du(hi,r)),t.nanoid=r=>t.check(Uu(Bk,r)),t.guid=r=>t.check(ii(Qh,r)),t.cuid=r=>t.check(Fu(Vk,r)),t.cuid2=r=>t.check(Hu(Jk,r)),t.ulid=r=>t.check(Bu(Wk,r)),t.base64=r=>t.check(Yu(tS,r)),t.base64url=r=>t.check(Qu(rS,r)),t.xid=r=>t.check(Vu(Gk,r)),t.ksuid=r=>t.check(Ju(Kk,r)),t.ipv4=r=>t.check(Wu(Xk,r)),t.ipv6=r=>t.check(Gu(Yk,r)),t.cidrv4=r=>t.check(Ku(Qk,r)),t.cidrv6=r=>t.check(Xu(eS,r)),t.e164=r=>t.check(el(nS,r)),t.datetime=r=>t.check($l(r)),t.date=r=>t.check(kl(r)),t.time=r=>t.check(Sl(r)),t.duration=r=>t.check(Tl(r))});be=w("ZodStringFormat",(t,e)=>{he.init(t,e),rg.init(t,e)}),Uk=w("ZodEmail",(t,e)=>{Wc.init(t,e),be.init(t,e)}),Qh=w("ZodGUID",(t,e)=>{Vc.init(t,e),be.init(t,e)}),hi=w("ZodUUID",(t,e)=>{Jc.init(t,e),be.init(t,e)}),Fk=w("ZodURL",(t,e)=>{Gc.init(t,e),be.init(t,e)}),Hk=w("ZodEmoji",(t,e)=>{Kc.init(t,e),be.init(t,e)}),Bk=w("ZodNanoID",(t,e)=>{Xc.init(t,e),be.init(t,e)}),Vk=w("ZodCUID",(t,e)=>{Yc.init(t,e),be.init(t,e)}),Jk=w("ZodCUID2",(t,e)=>{Qc.init(t,e),be.init(t,e)}),Wk=w("ZodULID",(t,e)=>{eu.init(t,e),be.init(t,e)}),Gk=w("ZodXID",(t,e)=>{tu.init(t,e),be.init(t,e)}),Kk=w("ZodKSUID",(t,e)=>{ru.init(t,e),be.init(t,e)}),Xk=w("ZodIPv4",(t,e)=>{nu.init(t,e),be.init(t,e)}),Yk=w("ZodIPv6",(t,e)=>{ou.init(t,e),be.init(t,e)}),Qk=w("ZodCIDRv4",(t,e)=>{su.init(t,e),be.init(t,e)}),eS=w("ZodCIDRv6",(t,e)=>{iu.init(t,e),be.init(t,e)}),tS=w("ZodBase64",(t,e)=>{au.init(t,e),be.init(t,e)}),rS=w("ZodBase64URL",(t,e)=>{cu.init(t,e),be.init(t,e)}),nS=w("ZodE164",(t,e)=>{uu.init(t,e),be.init(t,e)}),oS=w("ZodJWT",(t,e)=>{lu.init(t,e),be.init(t,e)}),ng=w("ZodNumber",(t,e)=>{ri.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(ci(n,o)),t.gte=(n,o)=>t.check(qo(n,o)),t.min=(n,o)=>t.check(qo(n,o)),t.lt=(n,o)=>t.check(ai(n,o)),t.lte=(n,o)=>t.check(Lo(n,o)),t.max=(n,o)=>t.check(Lo(n,o)),t.int=n=>t.check(eg(n)),t.safe=n=>t.check(eg(n)),t.positive=n=>t.check(ci(0,n)),t.nonnegative=n=>t.check(qo(0,n)),t.negative=n=>t.check(ai(0,n)),t.nonpositive=n=>t.check(Lo(0,n)),t.multipleOf=(n,o)=>t.check(ui(n,o)),t.step=(n,o)=>t.check(ui(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});sS=w("ZodNumberFormat",(t,e)=>{du.init(t,e),ng.init(t,e)});iS=w("ZodBoolean",(t,e)=>{fu.init(t,e),Se.init(t,e)});aS=w("ZodNull",(t,e)=>{pu.init(t,e),Se.init(t,e)});cS=w("ZodUnknown",(t,e)=>{mu.init(t,e),Se.init(t,e)});uS=w("ZodNever",(t,e)=>{hu.init(t,e),Se.init(t,e)});dS=w("ZodArray",(t,e)=>{gu.init(t,e),Se.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Un(r,n)),t.nonempty=r=>t.check(Un(1,r)),t.max=(r,n)=>t.check(li(r,n)),t.length=(r,n)=>t.check(di(r,n)),t.unwrap=()=>t.element});sg=w("ZodObject",(t,e)=>{ni.init(t,e),Se.init(t,e),re.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>et(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:we()}),t.loose=()=>t.clone({...t._zod.def,catchall:we()}),t.strict=()=>t.clone({...t._zod.def,catchall:lS()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>re.extend(t,r),t.merge=r=>re.merge(t,r),t.pick=r=>re.pick(t,r),t.omit=r=>re.omit(t,r),t.partial=(...r)=>re.partial(cg,t,r[0]),t.required=(...r)=>re.required(ug,t,r[0])});ig=w("ZodUnion",(t,e)=>{oi.init(t,e),Se.init(t,e),t.options=e.options});fS=w("ZodDiscriminatedUnion",(t,e)=>{ig.init(t,e),yu.init(t,e)});pS=w("ZodIntersection",(t,e)=>{_u.init(t,e),Se.init(t,e)});mS=w("ZodRecord",(t,e)=>{vu.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Cl=w("ZodEnum",(t,e)=>{xu.init(t,e),Se.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 Cl({...e,checks:[],...re.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 Cl({...e,checks:[],...re.normalizeParams(o),entries:s})}});hS=w("ZodLiteral",(t,e)=>{bu.init(t,e),Se.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]}})});gS=w("ZodTransform",(t,e)=>{wu.init(t,e),Se.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(re.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(re.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});cg=w("ZodOptional",(t,e)=>{$u.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});yS=w("ZodNullable",(t,e)=>{ku.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});_S=w("ZodDefault",(t,e)=>{Su.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});xS=w("ZodPrefault",(t,e)=>{Tu.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});ug=w("ZodNonOptional",(t,e)=>{Eu.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});$S=w("ZodCatch",(t,e)=>{zu.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});SS=w("ZodPipe",(t,e)=>{Ru.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});TS=w("ZodReadonly",(t,e)=>{Pu.init(t,e),Se.init(t,e)});lg=w("ZodCustom",(t,e)=>{Cu.init(t,e),Se.init(t,e)})});var fg=Q(()=>{});var pg=Q(()=>{});var mg=Q(()=>{He();zl();wl();Rl();Pl();fg();He();Ch();si();El();pg();at(Ph())});var hg=Q(()=>{mg()});var gg=Q(()=>{hg()});function Cg(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Og(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ml,yg,Vn,kr,_i,ze,_g,vg,IZ,AS,IS,jl,ut,Ho,xg,Ie,pt,mt,Ne,vi,bg,or,wg,$g,Zl,sr,A,Dl,Jn,Bo,NZ,xi,NS,bi,MS,Vo,Bn,kg,jS,ZS,DS,LS,qS,US,wi,Ll,FS,HS,ql,$i,BS,VS,ki,JS,Jo,Wo,WS,Go,Wn,GS,Ko,Si,Ti,Ei,MZ,zi,Ri,Pi,Sg,Tg,Eg,Ul,zg,Xo,Gn,Rg,KS,Ci,XS,Oi,YS,Fl,QS,Ai,eT,tT,rT,nT,oT,sT,iT,aT,cT,uT,Ii,lT,dT,Ni,Hl,Bl,Vl,fT,pT,mT,Jl,hT,gT,yT,_T,vT,Pg,Mi,xT,ji,jZ,bT,Kn,wT,ZZ,Yo,$T,Wl,kT,ST,TT,ET,zT,RT,PT,yi,CT,OT,AT,Qo,Gl,IT,NT,MT,jT,ZT,DT,LT,qT,UT,FT,HT,BT,VT,JT,WT,GT,KT,XT,Xn,YT,QT,eE,Zi,tE,rE,nE,Kl,oE,DZ,LZ,qZ,UZ,FZ,HZ,O,Nl,Sr=Q(()=>{gg();Ml="2025-11-25",yg="2025-03-26",Vn=[Ml,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],kr="io.modelcontextprotocol/related-task",_i="2.0",ze=dg(t=>t!==null&&(typeof t=="object"||typeof t=="function")),_g=ye([b(),le().int()]),vg=b(),IZ=Be({ttl:le().optional(),pollInterval:le().optional()}),AS=C({ttl:le().optional()}),IS=C({taskId:b()}),jl=Be({progressToken:_g.optional(),[kr]:IS.optional()}),ut=C({_meta:jl.optional()}),Ho=ut.extend({task:AS.optional()}),xg=t=>Ho.safeParse(t).success,Ie=C({method:b(),params:ut.loose().optional()}),pt=C({_meta:jl.optional()}),mt=C({method:b(),params:pt.loose().optional()}),Ne=Be({_meta:jl.optional()}),vi=ye([b(),le().int()]),bg=C({jsonrpc:M(_i),id:vi,...Ie.shape}).strict(),or=t=>bg.safeParse(t).success,wg=C({jsonrpc:M(_i),...mt.shape}).strict(),$g=t=>wg.safeParse(t).success,Zl=C({jsonrpc:M(_i),id:vi,result:Ne}).strict(),sr=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={}));Dl=C({jsonrpc:M(_i),id:vi.optional(),error:C({code:le().int(),message:b(),data:we().optional()})}).strict(),Jn=t=>Dl.safeParse(t).success,Bo=ye([bg,wg,Zl,Dl]),NZ=ye([Zl,Dl]),xi=Ne.strict(),NS=pt.extend({requestId:vi.optional(),reason:b().optional()}),bi=mt.extend({method:M("notifications/cancelled"),params:NS}),MS=C({src:b(),mimeType:b().optional(),sizes:ne(b()).optional(),theme:et(["light","dark"]).optional()}),Vo=C({icons:ne(MS).optional()}),Bn=C({name:b(),title:b().optional()}),kg=Bn.extend({...Bn.shape,...Vo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),jS=gi(C({applyDefaults:Pe().optional()}),ge(b(),we())),ZS=Il(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,gi(C({form:jS.optional(),url:ze.optional()}),ge(b(),we()).optional())),DS=Be({list:ze.optional(),cancel:ze.optional(),requests:Be({sampling:Be({createMessage:ze.optional()}).optional(),elicitation:Be({create:ze.optional()}).optional()}).optional()}),LS=Be({list:ze.optional(),cancel:ze.optional(),requests:Be({tools:Be({call:ze.optional()}).optional()}).optional()}),qS=C({experimental:ge(b(),ze).optional(),sampling:C({context:ze.optional(),tools:ze.optional()}).optional(),elicitation:ZS.optional(),roots:C({listChanged:Pe().optional()}).optional(),tasks:DS.optional(),extensions:ge(b(),ze).optional()}),US=ut.extend({protocolVersion:b(),capabilities:qS,clientInfo:kg}),wi=Ie.extend({method:M("initialize"),params:US}),Ll=t=>wi.safeParse(t).success,FS=C({experimental:ge(b(),ze).optional(),logging:ze.optional(),completions:ze.optional(),prompts:C({listChanged:Pe().optional()}).optional(),resources:C({subscribe:Pe().optional(),listChanged:Pe().optional()}).optional(),tools:C({listChanged:Pe().optional()}).optional(),tasks:LS.optional(),extensions:ge(b(),ze).optional()}),HS=Ne.extend({protocolVersion:b(),capabilities:FS,serverInfo:kg,instructions:b().optional()}),ql=mt.extend({method:M("notifications/initialized"),params:pt.optional()}),$i=Ie.extend({method:M("ping"),params:ut.optional()}),BS=C({progress:le(),total:$e(le()),message:$e(b())}),VS=C({...pt.shape,...BS.shape,progressToken:_g}),ki=mt.extend({method:M("notifications/progress"),params:VS}),JS=ut.extend({cursor:vg.optional()}),Jo=Ie.extend({params:JS.optional()}),Wo=Ne.extend({nextCursor:vg.optional()}),WS=et(["working","input_required","completed","failed","cancelled"]),Go=C({taskId:b(),status:WS,ttl:ye([le(),og()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:$e(le()),statusMessage:$e(b())}),Wn=Ne.extend({task:Go}),GS=pt.merge(Go),Ko=mt.extend({method:M("notifications/tasks/status"),params:GS}),Si=Ie.extend({method:M("tasks/get"),params:ut.extend({taskId:b()})}),Ti=Ne.merge(Go),Ei=Ie.extend({method:M("tasks/result"),params:ut.extend({taskId:b()})}),MZ=Ne.loose(),zi=Jo.extend({method:M("tasks/list")}),Ri=Wo.extend({tasks:ne(Go)}),Pi=Ie.extend({method:M("tasks/cancel"),params:ut.extend({taskId:b()})}),Sg=Ne.merge(Go),Tg=C({uri:b(),mimeType:$e(b()),_meta:ge(b(),we()).optional()}),Eg=Tg.extend({text:b()}),Ul=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),zg=Tg.extend({blob:Ul}),Xo=et(["user","assistant"]),Gn=C({audience:ne(Xo).optional(),priority:le().min(0).max(1).optional(),lastModified:Uo.datetime({offset:!0}).optional()}),Rg=C({...Bn.shape,...Vo.shape,uri:b(),description:$e(b()),mimeType:$e(b()),size:$e(le()),annotations:Gn.optional(),_meta:$e(Be({}))}),KS=C({...Bn.shape,...Vo.shape,uriTemplate:b(),description:$e(b()),mimeType:$e(b()),annotations:Gn.optional(),_meta:$e(Be({}))}),Ci=Jo.extend({method:M("resources/list")}),XS=Wo.extend({resources:ne(Rg)}),Oi=Jo.extend({method:M("resources/templates/list")}),YS=Wo.extend({resourceTemplates:ne(KS)}),Fl=ut.extend({uri:b()}),QS=Fl,Ai=Ie.extend({method:M("resources/read"),params:QS}),eT=Ne.extend({contents:ne(ye([Eg,zg]))}),tT=mt.extend({method:M("notifications/resources/list_changed"),params:pt.optional()}),rT=Fl,nT=Ie.extend({method:M("resources/subscribe"),params:rT}),oT=Fl,sT=Ie.extend({method:M("resources/unsubscribe"),params:oT}),iT=pt.extend({uri:b()}),aT=mt.extend({method:M("notifications/resources/updated"),params:iT}),cT=C({name:b(),description:$e(b()),required:$e(Pe())}),uT=C({...Bn.shape,...Vo.shape,description:$e(b()),arguments:$e(ne(cT)),_meta:$e(Be({}))}),Ii=Jo.extend({method:M("prompts/list")}),lT=Wo.extend({prompts:ne(uT)}),dT=ut.extend({name:b(),arguments:ge(b(),b()).optional()}),Ni=Ie.extend({method:M("prompts/get"),params:dT}),Hl=C({type:M("text"),text:b(),annotations:Gn.optional(),_meta:ge(b(),we()).optional()}),Bl=C({type:M("image"),data:Ul,mimeType:b(),annotations:Gn.optional(),_meta:ge(b(),we()).optional()}),Vl=C({type:M("audio"),data:Ul,mimeType:b(),annotations:Gn.optional(),_meta:ge(b(),we()).optional()}),fT=C({type:M("tool_use"),name:b(),id:b(),input:ge(b(),we()),_meta:ge(b(),we()).optional()}),pT=C({type:M("resource"),resource:ye([Eg,zg]),annotations:Gn.optional(),_meta:ge(b(),we()).optional()}),mT=Rg.extend({type:M("resource_link")}),Jl=ye([Hl,Bl,Vl,mT,pT]),hT=C({role:Xo,content:Jl}),gT=Ne.extend({description:b().optional(),messages:ne(hT)}),yT=mt.extend({method:M("notifications/prompts/list_changed"),params:pt.optional()}),_T=C({title:b().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),vT=C({taskSupport:et(["required","optional","forbidden"]).optional()}),Pg=C({...Bn.shape,...Vo.shape,description:b().optional(),inputSchema:C({type:M("object"),properties:ge(b(),ze).optional(),required:ne(b()).optional()}).catchall(we()),outputSchema:C({type:M("object"),properties:ge(b(),ze).optional(),required:ne(b()).optional()}).catchall(we()).optional(),annotations:_T.optional(),execution:vT.optional(),_meta:ge(b(),we()).optional()}),Mi=Jo.extend({method:M("tools/list")}),xT=Wo.extend({tools:ne(Pg)}),ji=Ne.extend({content:ne(Jl).default([]),structuredContent:ge(b(),we()).optional(),isError:Pe().optional()}),jZ=ji.or(Ne.extend({toolResult:we()})),bT=Ho.extend({name:b(),arguments:ge(b(),we()).optional()}),Kn=Ie.extend({method:M("tools/call"),params:bT}),wT=mt.extend({method:M("notifications/tools/list_changed"),params:pt.optional()}),ZZ=C({autoRefresh:Pe().default(!0),debounceMs:le().int().nonnegative().default(300)}),Yo=et(["debug","info","notice","warning","error","critical","alert","emergency"]),$T=ut.extend({level:Yo}),Wl=Ie.extend({method:M("logging/setLevel"),params:$T}),kT=pt.extend({level:Yo,logger:b().optional(),data:we()}),ST=mt.extend({method:M("notifications/message"),params:kT}),TT=C({name:b().optional()}),ET=C({hints:ne(TT).optional(),costPriority:le().min(0).max(1).optional(),speedPriority:le().min(0).max(1).optional(),intelligencePriority:le().min(0).max(1).optional()}),zT=C({mode:et(["auto","required","none"]).optional()}),RT=C({type:M("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:ne(Jl).default([]),structuredContent:C({}).loose().optional(),isError:Pe().optional(),_meta:ge(b(),we()).optional()}),PT=Al("type",[Hl,Bl,Vl]),yi=Al("type",[Hl,Bl,Vl,fT,RT]),CT=C({role:Xo,content:ye([yi,ne(yi)]),_meta:ge(b(),we()).optional()}),OT=Ho.extend({messages:ne(CT),modelPreferences:ET.optional(),systemPrompt:b().optional(),includeContext:et(["none","thisServer","allServers"]).optional(),temperature:le().optional(),maxTokens:le().int(),stopSequences:ne(b()).optional(),metadata:ze.optional(),tools:ne(Pg).optional(),toolChoice:zT.optional()}),AT=Ie.extend({method:M("sampling/createMessage"),params:OT}),Qo=Ne.extend({model:b(),stopReason:$e(et(["endTurn","stopSequence","maxTokens"]).or(b())),role:Xo,content:PT}),Gl=Ne.extend({model:b(),stopReason:$e(et(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Xo,content:ye([yi,ne(yi)])}),IT=C({type:M("boolean"),title:b().optional(),description:b().optional(),default:Pe().optional()}),NT=C({type:M("string"),title:b().optional(),description:b().optional(),minLength:le().optional(),maxLength:le().optional(),format:et(["email","uri","date","date-time"]).optional(),default:b().optional()}),MT=C({type:et(["number","integer"]),title:b().optional(),description:b().optional(),minimum:le().optional(),maximum:le().optional(),default:le().optional()}),jT=C({type:M("string"),title:b().optional(),description:b().optional(),enum:ne(b()),default:b().optional()}),ZT=C({type:M("string"),title:b().optional(),description:b().optional(),oneOf:ne(C({const:b(),title:b()})),default:b().optional()}),DT=C({type:M("string"),title:b().optional(),description:b().optional(),enum:ne(b()),enumNames:ne(b()).optional(),default:b().optional()}),LT=ye([jT,ZT]),qT=C({type:M("array"),title:b().optional(),description:b().optional(),minItems:le().optional(),maxItems:le().optional(),items:C({type:M("string"),enum:ne(b())}),default:ne(b()).optional()}),UT=C({type:M("array"),title:b().optional(),description:b().optional(),minItems:le().optional(),maxItems:le().optional(),items:C({anyOf:ne(C({const:b(),title:b()}))}),default:ne(b()).optional()}),FT=ye([qT,UT]),HT=ye([DT,LT,FT]),BT=ye([HT,IT,NT,MT]),VT=Ho.extend({mode:M("form").optional(),message:b(),requestedSchema:C({type:M("object"),properties:ge(b(),BT),required:ne(b()).optional()})}),JT=Ho.extend({mode:M("url"),message:b(),elicitationId:b(),url:b().url()}),WT=ye([VT,JT]),GT=Ie.extend({method:M("elicitation/create"),params:WT}),KT=pt.extend({elicitationId:b()}),XT=mt.extend({method:M("notifications/elicitation/complete"),params:KT}),Xn=Ne.extend({action:et(["accept","decline","cancel"]),content:Il(t=>t===null?void 0:t,ge(b(),ye([b(),le(),Pe(),ne(b())])).optional())}),YT=C({type:M("ref/resource"),uri:b()}),QT=C({type:M("ref/prompt"),name:b()}),eE=ut.extend({ref:ye([QT,YT]),argument:C({name:b(),value:b()}),context:C({arguments:ge(b(),b()).optional()}).optional()}),Zi=Ie.extend({method:M("completion/complete"),params:eE});tE=Ne.extend({completion:Be({values:ne(b()).max(100),total:$e(le().int()),hasMore:$e(Pe())})}),rE=C({uri:b().startsWith("file://"),name:b().optional(),_meta:ge(b(),we()).optional()}),nE=Ie.extend({method:M("roots/list"),params:ut.optional()}),Kl=Ne.extend({roots:ne(rE)}),oE=mt.extend({method:M("notifications/roots/list_changed"),params:pt.optional()}),DZ=ye([$i,wi,Zi,Wl,Ni,Ii,Ci,Oi,Ai,nT,sT,Kn,Mi,Si,Ei,zi,Pi]),LZ=ye([bi,ki,ql,oE,Ko]),qZ=ye([xi,Qo,Gl,Xn,Kl,Ti,Ri,Wn]),UZ=ye([$i,AT,GT,nE,Si,Ei,zi,Pi]),FZ=ye([bi,ki,ST,aT,tT,wT,yT,Ko,XT]),HZ=ye([xi,HS,tE,gT,lT,XS,YS,eT,ji,xT,Ti,Ri,Wn]),O=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===A.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Nl(o.elicitations,r)}return new t(e,r,n)}},Nl=class extends O{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(A.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var ns=z(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.regexpCode=ue.getEsmExportName=ue.getProperty=ue.safeStringify=ue.stringify=ue.strConcat=ue.addCodeArg=ue.str=ue._=ue.nil=ue._Code=ue.Name=ue.IDENTIFIER=ue._CodeOrName=void 0;var ts=class{};ue._CodeOrName=ts;ue.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var mn=class extends ts{constructor(e){if(super(),!ue.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}}};ue.Name=mn;var ht=class extends ts{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 mn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ue._Code=ht;ue.nil=new ht("");function py(t,...e){let r=[t[0]],n=0;for(;n<e.length;)id(r,e[n]),r.push(t[++n]);return new ht(r)}ue._=py;var sd=new ht("+");function my(t,...e){let r=[rs(t[0])],n=0;for(;n<e.length;)r.push(sd),id(r,e[n]),r.push(sd,rs(t[++n]));return hE(r),new ht(r)}ue.str=my;function id(t,e){e instanceof ht?t.push(...e._items):e instanceof mn?t.push(e):t.push(_E(e))}ue.addCodeArg=id;function hE(t){let e=1;for(;e<t.length-1;){if(t[e]===sd){let r=gE(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function gE(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof mn||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 mn))return`"${t}${e.slice(1)}`}function yE(t,e){return e.emptyStr()?t:t.emptyStr()?e:my`${t}${e}`}ue.strConcat=yE;function _E(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:rs(Array.isArray(t)?t.join(","):t)}function vE(t){return new ht(rs(t))}ue.stringify=vE;function rs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ue.safeStringify=rs;function xE(t){return typeof t=="string"&&ue.IDENTIFIER.test(t)?new ht(`.${t}`):py`[${t}]`}ue.getProperty=xE;function bE(t){if(typeof t=="string"&&ue.IDENTIFIER.test(t))return new ht(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ue.getEsmExportName=bE;function wE(t){return new ht(t.toString())}ue.regexpCode=wE});var ud=z(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.ValueScope=rt.ValueScopeName=rt.Scope=rt.varKinds=rt.UsedValueState=void 0;var tt=ns(),ad=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Hi;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Hi||(rt.UsedValueState=Hi={}));rt.varKinds={const:new tt.Name("const"),let:new tt.Name("let"),var:new tt.Name("var")};var Bi=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof tt.Name?e:this.name(e)}name(e){return new tt.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}}};rt.Scope=Bi;var Vi=class extends tt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,tt._)`.${new tt.Name(r)}[${n}]`}};rt.ValueScopeName=Vi;var $E=(0,tt._)`\n`,cd=class extends Bi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?$E:tt.nil}}get(){return this._scope}name(e){return new Vi(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,tt._)`${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=tt.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,Hi.Started);let l=r(u);if(l){let d=this.opts.es5?rt.varKinds.var:rt.varKinds.const;s=(0,tt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,tt._)`${s}${l}${this.opts._n}`;else throw new ad(u);c.set(u,Hi.Completed)})}return s}};rt.ValueScope=cd});var G=z(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.or=X.and=X.not=X.CodeGen=X.operators=X.varKinds=X.ValueScopeName=X.ValueScope=X.Scope=X.Name=X.regexpCode=X.stringify=X.getProperty=X.nil=X.strConcat=X.str=X._=void 0;var se=ns(),zt=ud(),Er=ns();Object.defineProperty(X,"_",{enumerable:!0,get:function(){return Er._}});Object.defineProperty(X,"str",{enumerable:!0,get:function(){return Er.str}});Object.defineProperty(X,"strConcat",{enumerable:!0,get:function(){return Er.strConcat}});Object.defineProperty(X,"nil",{enumerable:!0,get:function(){return Er.nil}});Object.defineProperty(X,"getProperty",{enumerable:!0,get:function(){return Er.getProperty}});Object.defineProperty(X,"stringify",{enumerable:!0,get:function(){return Er.stringify}});Object.defineProperty(X,"regexpCode",{enumerable:!0,get:function(){return Er.regexpCode}});Object.defineProperty(X,"Name",{enumerable:!0,get:function(){return Er.Name}});var Ki=ud();Object.defineProperty(X,"Scope",{enumerable:!0,get:function(){return Ki.Scope}});Object.defineProperty(X,"ValueScope",{enumerable:!0,get:function(){return Ki.ValueScope}});Object.defineProperty(X,"ValueScopeName",{enumerable:!0,get:function(){return Ki.ValueScopeName}});Object.defineProperty(X,"varKinds",{enumerable:!0,get:function(){return Ki.varKinds}});X.operators={GT:new se._Code(">"),GTE:new se._Code(">="),LT:new se._Code("<"),LTE:new se._Code("<="),EQ:new se._Code("==="),NEQ:new se._Code("!=="),NOT:new se._Code("!"),OR:new se._Code("||"),AND:new se._Code("&&"),ADD:new se._Code("+")};var ir=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ld=class extends ir{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?zt.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=Qn(this.rhs,e,r)),this}get names(){return this.rhs instanceof se._CodeOrName?this.rhs.names:{}}},Ji=class extends ir{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 se.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Qn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof se.Name?{}:{...this.lhs.names};return Gi(e,this.rhs)}},dd=class extends Ji{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},fd=class extends ir{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},pd=class extends ir{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},md=class extends ir{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},hd=class extends ir{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=Qn(this.code,e,r),this}get names(){return this.code instanceof se._CodeOrName?this.code.names:{}}},os=class extends ir{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)||(kE(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>yn(e,r.names),{})}},ar=class extends os{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},gd=class extends os{},Yn=class extends ar{};Yn.kind="else";var hn=class t extends ar{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 Yn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(hy(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=Qn(this.condition,e,r),this}get names(){let e=super.names;return Gi(e,this.condition),this.else&&yn(e,this.else.names),e}};hn.kind="if";var gn=class extends ar{};gn.kind="for";var yd=class extends gn{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=Qn(this.iteration,e,r),this}get names(){return yn(super.names,this.iteration.names)}},_d=class extends gn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?zt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Gi(super.names,this.from);return Gi(e,this.to)}},Wi=class extends gn{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=Qn(this.iterable,e,r),this}get names(){return yn(super.names,this.iterable.names)}},ss=class extends ar{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)}};ss.kind="func";var is=class extends os{render(e){return"return "+super.render(e)}};is.kind="return";var vd=class extends ar{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&&yn(e,this.catch.names),this.finally&&yn(e,this.finally.names),e}},as=class extends ar{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};as.kind="catch";var cs=class extends ar{render(e){return"finally"+super.render(e)}};cs.kind="finally";var xd=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
31
|
+
`:""},this._extScope=e,this._scope=new zt.Scope({parent:e}),this._nodes=[new gd]}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 ld(e,s,n)),s}const(e,r,n){return this._def(zt.varKinds.const,e,r,n)}let(e,r,n){return this._def(zt.varKinds.let,e,r,n)}var(e,r,n){return this._def(zt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ji(e,r,n))}add(e,r){return this._leafNode(new dd(e,X.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==se.nil&&this._leafNode(new hd(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,se.addCodeArg)(r,o));return r.push("}"),new se._Code(r)}if(e,r,n){if(this._blockNode(new hn(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 hn(e))}else(){return this._elseNode(new Yn)}endIf(){return this._endBlockNode(hn,Yn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new yd(e),r)}forRange(e,r,n,o,s=this.opts.es5?zt.varKinds.var:zt.varKinds.let){let i=this._scope.toName(e);return this._for(new _d(s,i,r,n),()=>o(i))}forOf(e,r,n,o=zt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof se.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,se._)`${i}.length`,a=>{this.var(s,(0,se._)`${i}[${a}]`),n(s)})}return this._for(new Wi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?zt.varKinds.var:zt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,se._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Wi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(gn)}label(e){return this._leafNode(new fd(e))}break(e){return this._leafNode(new pd(e))}return(e){let r=new is;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(is)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new vd;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new as(s),r(s)}return n&&(this._currNode=o.finally=new cs,this.code(n)),this._endBlockNode(as,cs)}throw(e){return this._leafNode(new md(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=se.nil,n,o){return this._blockNode(new ss(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ss)}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 hn))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}};X.CodeGen=xd;function yn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Gi(t,e){return e instanceof se._CodeOrName?yn(t,e.names):t}function Qn(t,e,r){if(t instanceof se.Name)return n(t);if(!o(t))return t;return new se._Code(t._items.reduce((s,i)=>(i instanceof se.Name&&(i=n(i)),i instanceof se._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 se._Code&&s._items.some(i=>i instanceof se.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function kE(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function hy(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,se._)`!${bd(t)}`}X.not=hy;var SE=gy(X.operators.AND);function TE(...t){return t.reduce(SE)}X.and=TE;var EE=gy(X.operators.OR);function zE(...t){return t.reduce(EE)}X.or=zE;function gy(t){return(e,r)=>e===se.nil?r:r===se.nil?e:(0,se._)`${bd(e)} ${t} ${bd(r)}`}function bd(t){return t instanceof se.Name?t:(0,se._)`(${t})`}});var ae=z(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.checkStrictMode=Y.getErrorPath=Y.Type=Y.useFunc=Y.setEvaluated=Y.evaluatedPropsToName=Y.mergeEvaluated=Y.eachItem=Y.unescapeJsonPointer=Y.escapeJsonPointer=Y.escapeFragment=Y.unescapeFragment=Y.schemaRefOrVal=Y.schemaHasRulesButRef=Y.schemaHasRules=Y.checkUnknownRules=Y.alwaysValidSchema=Y.toHash=void 0;var pe=G(),RE=ns();function PE(t){let e={};for(let r of t)e[r]=!0;return e}Y.toHash=PE;function CE(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(vy(t,e),!xy(e,t.self.RULES.all))}Y.alwaysValidSchema=CE;function vy(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]||$y(t,`unknown keyword: "${s}"`)}Y.checkUnknownRules=vy;function xy(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}Y.schemaHasRules=xy;function OE(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}Y.schemaHasRulesButRef=OE;function AE({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,pe._)`${r}`}return(0,pe._)`${t}${e}${(0,pe.getProperty)(n)}`}Y.schemaRefOrVal=AE;function IE(t){return by(decodeURIComponent(t))}Y.unescapeFragment=IE;function NE(t){return encodeURIComponent($d(t))}Y.escapeFragment=NE;function $d(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}Y.escapeJsonPointer=$d;function by(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}Y.unescapeJsonPointer=by;function ME(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}Y.eachItem=ME;function yy({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof pe.Name?(s instanceof pe.Name?t(o,s,i):e(o,s,i),i):s instanceof pe.Name?(e(o,i,s),s):r(s,i);return a===pe.Name&&!(c instanceof pe.Name)?n(o,c):c}}Y.mergeEvaluated={props:yy({mergeNames:(t,e,r)=>t.if((0,pe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,pe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,pe._)`${r} || {}`).code((0,pe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,pe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,pe._)`${r} || {}`),kd(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:wy}),items:yy({mergeNames:(t,e,r)=>t.if((0,pe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,pe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,pe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,pe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function wy(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,pe._)`{}`);return e!==void 0&&kd(t,r,e),r}Y.evaluatedPropsToName=wy;function kd(t,e,r){Object.keys(r).forEach(n=>t.assign((0,pe._)`${e}${(0,pe.getProperty)(n)}`,!0))}Y.setEvaluated=kd;var _y={};function jE(t,e){return t.scopeValue("func",{ref:e,code:_y[e.code]||(_y[e.code]=new RE._Code(e.code))})}Y.useFunc=jE;var wd;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(wd||(Y.Type=wd={}));function ZE(t,e,r){if(t instanceof pe.Name){let n=e===wd.Num;return r?n?(0,pe._)`"[" + ${t} + "]"`:(0,pe._)`"['" + ${t} + "']"`:n?(0,pe._)`"/" + ${t}`:(0,pe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,pe.getProperty)(t).toString():"/"+$d(t)}Y.getErrorPath=ZE;function $y(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}Y.checkStrictMode=$y});var cr=z(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var De=G(),DE={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};Sd.default=DE});var us=z(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var ce=G(),Xi=ae(),Je=cr();Le.keywordError={message:({keyword:t})=>(0,ce.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ce.str)`"${t}" keyword must be ${e} ($data)`:(0,ce.str)`"${t}" keyword is invalid ($data)`};function LE(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Ty(t,e,r);n??(i||a)?ky(s,c):Sy(o,(0,ce._)`[${c}]`)}Le.reportError=LE;function qE(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Ty(t,e,r);ky(o,a),s||i||Sy(n,Je.default.vErrors)}Le.reportExtraError=qE;function UE(t,e){t.assign(Je.default.errors,e),t.if((0,ce._)`${Je.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ce._)`${Je.default.vErrors}.length`,e),()=>t.assign(Je.default.vErrors,null)))}Le.resetErrorsCount=UE;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,Je.default.errors,a=>{t.const(i,(0,ce._)`${Je.default.vErrors}[${a}]`),t.if((0,ce._)`${i}.instancePath === undefined`,()=>t.assign((0,ce._)`${i}.instancePath`,(0,ce.strConcat)(Je.default.instancePath,s.errorPath))),t.assign((0,ce._)`${i}.schemaPath`,(0,ce.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ce._)`${i}.schema`,r),t.assign((0,ce._)`${i}.data`,n))})}Le.extendErrors=FE;function ky(t,e){let r=t.const("err",e);t.if((0,ce._)`${Je.default.vErrors} === null`,()=>t.assign(Je.default.vErrors,(0,ce._)`[${r}]`),(0,ce._)`${Je.default.vErrors}.push(${r})`),t.code((0,ce._)`${Je.default.errors}++`)}function Sy(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ce._)`new ${t.ValidationError}(${e})`):(r.assign((0,ce._)`${n}.errors`,e),r.return(!1))}var _n={keyword:new ce.Name("keyword"),schemaPath:new ce.Name("schemaPath"),params:new ce.Name("params"),propertyName:new ce.Name("propertyName"),message:new ce.Name("message"),schema:new ce.Name("schema"),parentSchema:new ce.Name("parentSchema")};function Ty(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ce._)`{}`:HE(t,e,r)}function HE(t,e,r={}){let{gen:n,it:o}=t,s=[BE(o,r),VE(t,r)];return JE(t,e,s),n.object(...s)}function BE({errorPath:t},{instancePath:e}){let r=e?(0,ce.str)`${t}${(0,Xi.getErrorPath)(e,Xi.Type.Str)}`:t;return[Je.default.instancePath,(0,ce.strConcat)(Je.default.instancePath,r)]}function VE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ce.str)`${e}/${t}`;return r&&(o=(0,ce.str)`${o}${(0,Xi.getErrorPath)(r,Xi.Type.Str)}`),[_n.schemaPath,o]}function JE(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([_n.keyword,o],[_n.params,typeof e=="function"?e(t):e||(0,ce._)`{}`]),c.messages&&n.push([_n.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([_n.schema,i],[_n.parentSchema,(0,ce._)`${l}${d}`],[Je.default.data,s]),u&&n.push([_n.propertyName,u])}});var zy=z(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.boolOrEmptySchema=eo.topBoolOrEmptySchema=void 0;var WE=us(),GE=G(),KE=cr(),XE={message:"boolean schema is false"};function YE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ey(t,!1):typeof r=="object"&&r.$async===!0?e.return(KE.default.data):(e.assign((0,GE._)`${n}.errors`,null),e.return(!0))}eo.topBoolOrEmptySchema=YE;function QE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ey(t)):r.var(e,!0)}eo.boolOrEmptySchema=QE;function Ey(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,WE.reportError)(o,XE,void 0,e)}});var Td=z(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.getRules=to.isJSONType=void 0;var ez=["string","number","integer","boolean","null","object","array"],tz=new Set(ez);function rz(t){return typeof t=="string"&&tz.has(t)}to.isJSONType=rz;function nz(){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:{}}}to.getRules=nz});var Ed=z(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.shouldUseRule=zr.shouldUseGroup=zr.schemaHasRulesForType=void 0;function oz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Ry(t,n)}zr.schemaHasRulesForType=oz;function Ry(t,e){return e.rules.some(r=>Py(t,r))}zr.shouldUseGroup=Ry;function Py(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))}zr.shouldUseRule=Py});var ls=z(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.reportTypeError=qe.checkDataTypes=qe.checkDataType=qe.coerceAndCheckDataType=qe.getJSONTypes=qe.getSchemaTypes=qe.DataType=void 0;var sz=Td(),iz=Ed(),az=us(),J=G(),Cy=ae(),ro;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ro||(qe.DataType=ro={}));function cz(t){let e=Oy(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}qe.getSchemaTypes=cz;function Oy(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(sz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}qe.getJSONTypes=Oy;function uz(t,e){let{gen:r,data:n,opts:o}=t,s=lz(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,iz.schemaHasRulesForType)(t,e[0]));if(i){let a=Rd(e,n,o.strictNumbers,ro.Wrong);r.if(a,()=>{s.length?dz(t,e,s):Pd(t)})}return i}qe.coerceAndCheckDataType=uz;var Ay=new Set(["string","number","integer","boolean","null"]);function lz(t,e){return e?t.filter(r=>Ay.has(r)||e==="array"&&r==="array"):[]}function dz(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,J._)`typeof ${o}`),a=n.let("coerced",(0,J._)`undefined`);s.coerceTypes==="array"&&n.if((0,J._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,J._)`${o}[0]`).assign(i,(0,J._)`typeof ${o}`).if(Rd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,J._)`${a} !== undefined`);for(let u of r)(Ay.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Pd(t),n.endIf(),n.if((0,J._)`${a} !== undefined`,()=>{n.assign(o,a),fz(t,a)});function c(u){switch(u){case"string":n.elseIf((0,J._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,J._)`"" + ${o}`).elseIf((0,J._)`${o} === null`).assign(a,(0,J._)`""`);return;case"number":n.elseIf((0,J._)`${i} == "boolean" || ${o} === null
|
|
32
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,J._)`+${o}`);return;case"integer":n.elseIf((0,J._)`${i} === "boolean" || ${o} === null
|
|
33
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,J._)`+${o}`);return;case"boolean":n.elseIf((0,J._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,J._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,J._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,J._)`${i} === "string" || ${i} === "number"
|
|
34
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,J._)`[${o}]`)}}}function fz({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,J._)`${e} !== undefined`,()=>t.assign((0,J._)`${e}[${r}]`,n))}function zd(t,e,r,n=ro.Correct){let o=n===ro.Correct?J.operators.EQ:J.operators.NEQ,s;switch(t){case"null":return(0,J._)`${e} ${o} null`;case"array":s=(0,J._)`Array.isArray(${e})`;break;case"object":s=(0,J._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,J._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,J._)`typeof ${e} ${o} ${t}`}return n===ro.Correct?s:(0,J.not)(s);function i(a=J.nil){return(0,J.and)((0,J._)`typeof ${e} == "number"`,a,r?(0,J._)`isFinite(${e})`:J.nil)}}qe.checkDataType=zd;function Rd(t,e,r,n){if(t.length===1)return zd(t[0],e,r,n);let o,s=(0,Cy.toHash)(t);if(s.array&&s.object){let i=(0,J._)`typeof ${e} != "object"`;o=s.null?i:(0,J._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=J.nil;s.number&&delete s.integer;for(let i in s)o=(0,J.and)(o,zd(i,e,r,n));return o}qe.checkDataTypes=Rd;var pz={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,J._)`{type: ${t}}`:(0,J._)`{type: ${e}}`};function Pd(t){let e=mz(t);(0,az.reportError)(e,pz)}qe.reportTypeError=Pd;function mz(t){let{gen:e,data:r,schema:n}=t,o=(0,Cy.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Ny=z(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.assignDefaults=void 0;var no=G(),hz=ae();function gz(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Iy(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Iy(t,s,o.default))}Yi.assignDefaults=gz;function Iy(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,no._)`${s}${(0,no.getProperty)(e)}`;if(o){(0,hz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,no._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,no._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,no._)`${a} = ${(0,no.stringify)(r)}`)}});var gt=z(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.validateUnion=fe.validateArray=fe.usePattern=fe.callValidateCode=fe.schemaProperties=fe.allSchemaProperties=fe.noPropertyInData=fe.propertyInData=fe.isOwnProperty=fe.hasPropFunc=fe.reportMissingProp=fe.checkMissingProp=fe.checkReportMissingProp=void 0;var _e=G(),Cd=ae(),Rr=cr(),yz=ae();function _z(t,e){let{gen:r,data:n,it:o}=t;r.if(Ad(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,_e._)`${e}`},!0),t.error()})}fe.checkReportMissingProp=_z;function vz({gen:t,data:e,it:{opts:r}},n,o){return(0,_e.or)(...n.map(s=>(0,_e.and)(Ad(t,e,s,r.ownProperties),(0,_e._)`${o} = ${s}`)))}fe.checkMissingProp=vz;function xz(t,e){t.setParams({missingProperty:e},!0),t.error()}fe.reportMissingProp=xz;function My(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}fe.hasPropFunc=My;function Od(t,e,r){return(0,_e._)`${My(t)}.call(${e}, ${r})`}fe.isOwnProperty=Od;function bz(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} !== undefined`;return n?(0,_e._)`${o} && ${Od(t,e,r)}`:o}fe.propertyInData=bz;function Ad(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} === undefined`;return n?(0,_e.or)(o,(0,_e.not)(Od(t,e,r))):o}fe.noPropertyInData=Ad;function jy(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}fe.allSchemaProperties=jy;function wz(t,e){return jy(e).filter(r=>!(0,Cd.alwaysValidSchema)(t,e[r]))}fe.schemaProperties=wz;function $z({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,_e._)`${t}, ${e}, ${n}${o}`:e,d=[[Rr.default.instancePath,(0,_e.strConcat)(Rr.default.instancePath,s)],[Rr.default.parentData,i.parentData],[Rr.default.parentDataProperty,i.parentDataProperty],[Rr.default.rootData,Rr.default.rootData]];i.opts.dynamicRef&&d.push([Rr.default.dynamicAnchors,Rr.default.dynamicAnchors]);let m=(0,_e._)`${l}, ${r.object(...d)}`;return c!==_e.nil?(0,_e._)`${a}.call(${c}, ${m})`:(0,_e._)`${a}(${m})`}fe.callValidateCode=$z;var kz=(0,_e._)`new RegExp`;function Sz({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,_e._)`${o.code==="new RegExp"?kz:(0,yz.useFunc)(t,o)}(${r}, ${n})`})}fe.usePattern=Sz;function Tz(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,_e._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Cd.Type.Num},s),e.if((0,_e.not)(s),a)})}}fe.validateArray=Tz;function Ez(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,Cd.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,_e._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,_e.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}fe.validateUnion=Ez});var Ly=z(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.validateKeywordUsage=Ht.validSchemaType=Ht.funcKeywordCode=Ht.macroKeywordCode=void 0;var We=G(),vn=cr(),zz=gt(),Rz=us();function Pz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Dy(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:We.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ht.macroKeywordCode=Pz;function Cz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;Az(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Dy(n,o,u),d=n.let("valid");t.block$data(d,m),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function m(){if(e.errors===!1)h(),e.modifying&&Zy(t),g(()=>t.error());else{let _=e.async?p():f();e.modifying&&Zy(t),g(()=>Oz(t,_))}}function p(){let _=n.let("ruleErrs",null);return n.try(()=>h((0,We._)`await `),v=>n.assign(d,!1).if((0,We._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,We._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,We._)`${l}.errors`;return n.assign(_,null),h(We.nil),_}function h(_=e.async?(0,We._)`await `:We.nil){let v=c.opts.passContext?vn.default.this:vn.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,We._)`${_}${(0,zz.callValidateCode)(t,l,v,y)}`,e.modifying)}function g(_){var v;n.if((0,We.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}Ht.funcKeywordCode=Cz;function Zy(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}function Oz(t,e){let{gen:r}=t;r.if((0,We._)`Array.isArray(${e})`,()=>{r.assign(vn.default.vErrors,(0,We._)`${vn.default.vErrors} === null ? ${e} : ${vn.default.vErrors}.concat(${e})`).assign(vn.default.errors,(0,We._)`${vn.default.vErrors}.length`),(0,Rz.extendErrors)(t)},()=>t.error())}function Az({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Dy(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,We.stringify)(r)})}function Iz(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")}Ht.validSchemaType=Iz;function Nz({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)}}Ht.validateKeywordUsage=Nz});var Uy=z(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.extendSubschemaMode=Pr.extendSubschemaData=Pr.getSubschema=void 0;var Bt=G(),qy=ae();function Mz(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,Bt._)`${t.schemaPath}${(0,Bt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Bt._)`${t.schemaPath}${(0,Bt.getProperty)(e)}${(0,Bt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,qy.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')}Pr.getSubschema=Mz;function jz(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,Bt._)`${e.data}${(0,Bt.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Bt.str)`${u}${(0,qy.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Bt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Bt.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]}}Pr.extendSubschemaData=jz;function Zz(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}Pr.extendSubschemaMode=Zz});var Id=z((iL,Fy)=>{"use strict";Fy.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 By=z((aL,Hy)=>{"use strict";var Cr=Hy.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(){};Qi(e,n,o,t,"",t)};Cr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Cr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Cr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Cr.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 Qi(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 Cr.arrayKeywords)for(var m=0;m<d.length;m++)Qi(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in Cr.propsKeywords){if(d&&typeof d=="object")for(var p in d)Qi(t,e,r,d[p],o+"/"+l+"/"+Dz(p),s,o,l,n,p)}else(l in Cr.keywords||t.allKeys&&!(l in Cr.skipKeywords))&&Qi(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function Dz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ds=z(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.getSchemaRefs=nt.resolveUrl=nt.normalizeId=nt._getFullPath=nt.getFullPath=nt.inlineRef=void 0;var Lz=ae(),qz=Id(),Uz=By(),Fz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Hz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Nd(t):e?Vy(t)<=e:!1}nt.inlineRef=Hz;var Bz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Nd(t){for(let e in t){if(Bz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Nd)||typeof r=="object"&&Nd(r))return!0}return!1}function Vy(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,Lz.eachItem)(t[r],n=>e+=Vy(n)),e===1/0))return 1/0}return e}function Jy(t,e="",r){r!==!1&&(e=oo(e));let n=t.parse(e);return Wy(t,n)}nt.getFullPath=Jy;function Wy(t,e){return t.serialize(e).split("#")[0]+"#"}nt._getFullPath=Wy;var Vz=/#\/?$/;function oo(t){return t?t.replace(Vz,""):""}nt.normalizeId=oo;function Jz(t,e,r){return r=oo(r),t.resolve(e,r)}nt.resolveUrl=Jz;var Wz=/^[a-z_][-a-z0-9._]*$/i;function Gz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=oo(t[r]||e),s={"":o},i=Jy(n,o,!1),a={},c=new Set;return Uz(t,{allKeys:!0},(d,m,p,f)=>{if(f===void 0)return;let h=i+m,g=s[f];typeof d[r]=="string"&&(g=_.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[m]=g;function _(y){let x=this.opts.uriResolver.resolve;if(y=oo(g?x(g,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!==oo(h)&&(y[0]==="#"?(u(d,a[y],y),a[y]=d):this.refs[y]=h),y}function v(y){if(typeof y=="string"){if(!Wz.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(d,m,p){if(m!==void 0&&!qz(d,m))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}nt.getSchemaRefs=Gz});var ms=z(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.getData=Or.KeywordCxt=Or.validateFunctionCode=void 0;var Qy=zy(),Gy=ls(),jd=Ed(),ea=ls(),Kz=Ny(),ps=Ly(),Md=Uy(),j=G(),B=cr(),Xz=ds(),ur=ae(),fs=us();function Yz(t){if(r_(t)&&(n_(t),t_(t))){t1(t);return}e_(t,()=>(0,Qy.topBoolOrEmptySchema)(t))}Or.validateFunctionCode=Yz;function e_({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,j._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{t.code((0,j._)`"use strict"; ${Ky(r,o)}`),e1(t,o),t.code(s)}):t.func(e,(0,j._)`${B.default.data}, ${Qz(o)}`,n.$async,()=>t.code(Ky(r,o)).code(s))}function Qz(t){return(0,j._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${t.dynamicRef?(0,j._)`, ${B.default.dynamicAnchors}={}`:j.nil}}={}`}function e1(t,e){t.if(B.default.valCxt,()=>{t.var(B.default.instancePath,(0,j._)`${B.default.valCxt}.${B.default.instancePath}`),t.var(B.default.parentData,(0,j._)`${B.default.valCxt}.${B.default.parentData}`),t.var(B.default.parentDataProperty,(0,j._)`${B.default.valCxt}.${B.default.parentDataProperty}`),t.var(B.default.rootData,(0,j._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,j._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{t.var(B.default.instancePath,(0,j._)`""`),t.var(B.default.parentData,(0,j._)`undefined`),t.var(B.default.parentDataProperty,(0,j._)`undefined`),t.var(B.default.rootData,B.default.data),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,j._)`{}`)})}function t1(t){let{schema:e,opts:r,gen:n}=t;e_(t,()=>{r.$comment&&e.$comment&&s_(t),i1(t),n.let(B.default.vErrors,null),n.let(B.default.errors,0),r.unevaluated&&r1(t),o_(t),u1(t)})}function r1(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 Ky(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 n1(t,e){if(r_(t)&&(n_(t),t_(t))){o1(t,e);return}(0,Qy.boolOrEmptySchema)(t,e)}function t_({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 r_(t){return typeof t.schema!="boolean"}function o1(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&s_(t),a1(t),c1(t);let s=n.const("_errs",B.default.errors);o_(t,s),n.var(e,(0,j._)`${s} === ${B.default.errors}`)}function n_(t){(0,ur.checkUnknownRules)(t),s1(t)}function o_(t,e){if(t.opts.jtd)return Xy(t,[],!1,e);let r=(0,Gy.getSchemaTypes)(t.schema),n=(0,Gy.coerceAndCheckDataType)(t,r);Xy(t,r,!n,e)}function s1(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ur.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function i1(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ur.checkStrictMode)(t,"default is ignored in the schema root")}function a1(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Xz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function c1(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function s_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,j._)`${B.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._)`${B.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function u1(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,j._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,j._)`new ${o}(${B.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,B.default.vErrors),s.unevaluated&&l1(t),e.return((0,j._)`${B.default.errors} === 0`))}function l1({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 Xy(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,ur.schemaHasRulesButRef)(s,l))){o.block(()=>a_(t,"$ref",l.all.$ref.definition));return}c.jtd||d1(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,jd.shouldUseGroup)(s,m)&&(m.type?(o.if((0,ea.checkDataType)(m.type,i,c.strictNumbers)),Yy(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,ea.reportTypeError)(t)),o.endIf()):Yy(t,m),a||o.if((0,j._)`${B.default.errors} === ${n||0}`))}}function Yy(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,Kz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,jd.shouldUseRule)(n,s)&&a_(t,s.keyword,s.definition,e.type)})}function d1(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(f1(t,e),t.opts.allowUnionTypes||p1(t,e),m1(t,t.dataTypes))}function f1(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{i_(t.dataTypes,r)||Zd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),g1(t,e)}}function p1(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Zd(t,"use allowUnionTypes to allow union type keyword")}function m1(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,jd.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>h1(e,i))&&Zd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function h1(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function i_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function g1(t,e){let r=[];for(let n of t.dataTypes)i_(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,ur.checkStrictMode)(t,e,t.opts.strictTypes)}var ta=class{constructor(e,r,n){if((0,ps.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,ur.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",c_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ps.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",B.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?fs.reportExtraError:fs.reportError)(this,this.def.error,r)}$dataError(){(0,fs.reportError)(this,this.def.$dataError||fs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,fs.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,ea.checkDataTypes)(c,r,s.opts.strictNumbers,ea.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,Md.getSubschema)(this.it,e);(0,Md.extendSubschemaData)(n,this.it,e),(0,Md.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return n1(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ur.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ur.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}};Or.KeywordCxt=ta;function a_(t,e,r,n){let o=new ta(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ps.funcKeywordCode)(o,r):"macro"in r?(0,ps.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ps.funcKeywordCode)(o,r)}var y1=/^\/(?:[^~]|~0|~1)*$/,_1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function c_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return B.default.rootData;if(t[0]==="/"){if(!y1.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=B.default.rootData}else{let u=_1.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,ur.unescapeJsonPointer)(u))}`,i=(0,j._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Or.getData=c_});var ra=z(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Dd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Ld.default=Dd});var hs=z(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var qd=ds(),Ud=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,qd.resolveUrl)(e,r,n),this.missingSchema=(0,qd.normalizeId)((0,qd.getFullPath)(e,this.missingRef))}};Fd.default=Ud});var oa=z(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.resolveSchema=yt.getCompilingSchema=yt.resolveRef=yt.compileSchema=yt.SchemaEnv=void 0;var Rt=G(),v1=ra(),xn=cr(),Pt=ds(),u_=ae(),x1=ms(),so=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,Pt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};yt.SchemaEnv=so;function Bd(t){let e=l_.call(this,t);if(e)return e;let r=(0,Pt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Rt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:v1.default,code:(0,Rt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:xn.default.data,parentData:xn.default.parentData,parentDataProperty:xn.default.parentDataProperty,dataNames:[xn.default.data],dataPathArr:[Rt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Rt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Rt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Rt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,x1.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(xn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${xn.default.self}`,`${xn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:h}=u;p.evaluated={props:f instanceof Rt.Name?void 0:f,items:h instanceof Rt.Name?void 0:h,dynamicProps:f instanceof Rt.Name,dynamicItems:h instanceof Rt.Name},p.source&&(p.source.evaluated=(0,Rt.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)}}yt.compileSchema=Bd;function b1(t,e,r){var n;r=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=k1.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 so({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=w1.call(this,s)}yt.resolveRef=b1;function w1(t){return(0,Pt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Bd.call(this,t)}function l_(t){for(let e of this._compilations)if($1(e,t))return e}yt.getCompilingSchema=l_;function $1(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function k1(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||na.call(this,t,e)}function na(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pt._getFullPath)(this.opts.uriResolver,r),o=(0,Pt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Hd.call(this,r,t);let s=(0,Pt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=na.call(this,t,i);return typeof a?.schema!="object"?void 0:Hd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Bd.call(this,i),s===(0,Pt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Pt.resolveUrl)(this.opts.uriResolver,o,u)),new so({schema:a,schemaId:c,root:t,baseId:o})}return Hd.call(this,r,i)}}yt.resolveSchema=na;var S1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Hd(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,u_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!S1.has(a)&&u&&(e=(0,Pt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,u_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=na.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new so({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var d_=z((pL,T1)=>{T1.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 Xd=z((mL,v_)=>{"use strict";var E1=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),z1=RegExp.prototype.test.bind(/^\d*$/u),bn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Wd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),p_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Gd=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),R1=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ot=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)ot[e]="%"+t[e>>4]+t[e&15]}function Ue(t){return t<2048?ot[192|t>>6]+ot[128|t&63]:t<65536?ot[224|t>>12]+ot[128|t>>6&63]+ot[128|t&63]:ot[240|t>>18]+ot[128|t>>12&63]+ot[128|t>>6&63]+ot[128|t&63]}function P1(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 C1=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),O1=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),A1=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),I1=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function N1(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!A1(t[e])){if(t[e]==="%"&&e+2<t.length&&bn(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function f_(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 M1(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(!C1(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:f_(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 f_(i)}function Vd(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&&O1(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(j1(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),!N1(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=M1(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function j1(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function m_(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("")}function Z1(t){if(t===""||t[0]==="/")return m_(t);let e=t.split("/"),r=e.length-1,n=[],o=!1;for(let s=0;s<=r;s++){let i=e[s];i==="."||i===".."?(i===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),o=s===r):n.push(i)}return o&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var D1={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},L1=/[@/?#:]/g,q1=/[@/?#]/g;function h_(t,e){let r=e?q1:L1;return r.lastIndex=0,t.replace(r,n=>D1[n])}function g_(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(bn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Wd(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function U1(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(bn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Wd(i)?e+=i:e+="%"+s,r+=2;continue}}if(p_(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=__(o)?n:ot[o];else if(o<55296||o>57343)e+=Ue(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Ue(65536+(o-55296<<10)+(s-56320)),r++):e+=Ue(65533)}else e+=Ue(65533)}}return e}function F1(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(bn(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),p_(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=ot[i];else if(i<55296||i>57343)r+=Ue(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=Ue(65536+(i-55296<<10)+(a-56320)),o++):r+=Ue(65533)}else r+=Ue(65533)}}return r}function Kd(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(bn(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=ot[s];else if(s<55296||s>57343)r+=Ue(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Ue(65536+(s-55296<<10)+(i-56320)),n++):r+=Ue(65533)}else r+=Ue(65533)}}return r}function y_(t){return Kd(t,R1)}function H1(t){return Kd(t,Gd)}function B1(t){return Kd(t,Gd)}function __(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 V1(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(bn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Wd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Gd(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=__(o)?n:ot[o];else if(o<55296||o>57343)e+=Ue(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Ue(65536+(o-55296<<10)+(s-56320)),r++):e+=Ue(65533)}else e+=Ue(65533)}}return e}function J1(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(bn(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function W1(t){let e=[];if(t.userinfo!==void 0&&(e.push(y_(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!Jd(r)){let n=Vd(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=g_(r,!0),n=Vd(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=h_(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!z1(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}v_.exports={nonSimpleDomain:I1,recomposeAuthority:W1,reescapeHostDelimiters:h_,normalizePercentEncoding:g_,normalizePathEncoding:U1,serializePathEncoding:F1,normalizeQueryFragmentEncoding:V1,encodeUserinfo:y_,encodeQuery:H1,encodeFragment:B1,escapePreservingEscapes:J1,removeDotSegments:m_,removeDotSegmentsRelative:Z1,isIPv4:Jd,isUUID:E1,normalizeIPv6:Vd,stringArrayToHexStripped:P1}});var k_=z((hL,$_)=>{"use strict";var{isUUID:G1}=Xd(),K1=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,X1=["http","https","ws","wss","urn","urn:uuid"];function Y1(t){return X1.indexOf(t)!==-1}function Yd(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 x_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function b_(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 Q1(t){return t.secure=Yd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function eR(t){if((t.port===(Yd(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 tR(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(K1);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=Qd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function rR(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=Qd(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 nR(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!G1(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function oR(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var w_={scheme:"http",domainHost:!0,parse:x_,serialize:b_},sR={scheme:"https",domainHost:w_.domainHost,parse:x_,serialize:b_},sa={scheme:"ws",domainHost:!0,parse:Q1,serialize:eR},iR={scheme:"wss",domainHost:sa.domainHost,parse:sa.parse,serialize:sa.serialize},aR={scheme:"urn",parse:tR,serialize:rR,skipNormalize:!0},cR={scheme:"urn:uuid",parse:nR,serialize:oR,skipNormalize:!0},ia={http:w_,https:sR,ws:sa,wss:iR,urn:aR,"urn:uuid":cR};Object.setPrototypeOf(ia,null);function Qd(t){return t&&(ia[t]||ia[t.toLowerCase()])||void 0}$_.exports={wsIsSecure:Yd,SCHEMES:ia,isValidSchemeName:Y1,getSchemeHandler:Qd}});var D_=z((gL,da)=>{"use strict";var{normalizeIPv6:R_,removeDotSegments:ys,removeDotSegmentsRelative:P_,recomposeAuthority:uR,normalizePercentEncoding:ef,normalizePathEncoding:lR,serializePathEncoding:S_,normalizeQueryFragmentEncoding:T_,encodeQuery:dR,encodeFragment:fR,reescapeHostDelimiters:pR,isIPv4:C_,nonSimpleDomain:mR}=Xd(),{SCHEMES:O_,getSchemeHandler:tf}=k_(),A_=/^[A-Za-z][A-Za-z0-9+.-]*$/u,I_="URI scheme is malformed.",aa="URI host is malformed.",hR=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function E_(t){let e=String(t);if(!A_.test(e))throw new TypeError(I_);return e}function gR(t,e){return typeof t=="string"?t=SR(t,e):typeof t=="object"&&(t=ua(wn(t,e),e)),t}function yR(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}=ca(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:m,malformedSchemeSpecific:p,malformedHost:f,malformedScheme:h}=ca(e,n);if(s||d||i||m||a||p||c||f||u||h)throw new Error(o.error||l.error||"URI is malformed.");let g=N_(o,l,n,!0),_=tf(r&&r.scheme||g.scheme),v=g.host,y=v!==void 0&&v!==""&&(C_(v)||R_(v).isIPV6);if(j_(g,r||{},_,y))throw new Error(aa);M_(g,r||{},_,y);let x=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(g.error&&!x)throw new Error(g.error);return n.skipEscape=!0,wn(g,n)}function N_(t,e,r,n){let o={};if(n||(t=ua(wn(t,r),r),e=ua(wn(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=ys(e.path||""),o.query=e.query;else{if(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=ys(e.path||""),o.query=e.query;else{if(!e.path)o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query;else{if(e.path[0]==="/")o.path=ys(e.path);else{let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0;s&&!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=t.scheme===void 0&&!s&&o.path[0]!=="/"?P_(o.path):ys(o.path)}o.query=e.query}o.userinfo=t.userinfo,o.host=t.host,o.port=t.port}o.scheme=t.scheme}return o.fragment=e.fragment,o}function _R(t,e,r){let n=z_(t,r),o=z_(e,r);return n!==void 0&&o!==void 0&&n===o}function wn(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=E_(r.scheme));let s=tf(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=(r.scheme===void 0||n.reference==="suffix")&&!i,c=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=ef(r.path):r.path=S_(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=E_(r.scheme),o.push(r.scheme,":"));let u=uR(r);if(u!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(u),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let l=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=a&&l[0]!=="/"?P_(l):ys(l)),a&&(l=S_(l,!0)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),o.push(l)}return r.query!==void 0&&o.push("?",dR(r.query)),r.fragment!==void 0&&o.push("#",fR(r.fragment)),o.join("")}var vR=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,xR=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,bR=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function wR(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 gs(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 la(t){return t[0]==="["&&t[t.length-1]==="]"}function $R(t){let e=t[4];return gs(t[3])||e!==void 0&&!la(e)&&gs(e)||gs(t[6])||gs(t[7])||gs(t[8])}function M_(t,e,r,n){if(j_(t,e,r,n))return t.error=t.error||aa,!0;if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!la(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&mR(t.host)){let o;try{o=new URL("http://"+t.host)}catch(s){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!kR(o))return t.error=t.error||aa,!0;t.host=o.hostname}return!1}function j_(t,e,r,n){return!!(t.host&&n===!1&&!la(t.host)&&(e.domainHost||r&&r.domainHost)&&hR.test(t.host))}function kR(t){return t.username===""&&t.password===""&&t.port===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&t.hostname!==""}function ca(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(xR);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let m=t.match(bR);if(m!==null){let f=m[1],h=f.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let p=t.match(vR);if(p){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&&(A_.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||I_,u=!0)),s=$R(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let f=wR(n,p);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(C_(n.host)===!1){let _=la(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=R_(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||aa,o=!0)}else l=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let h=tf(r.scheme||n.scheme);if(c||(a=M_(n,r,h,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let g=l?n.host:ef(n.host,!0);l||(g=ef(g.toLowerCase())),n.host=l||r.scheme!=="null"?pR(g,l):g}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=lR(n.path)),n.query&&(n.query=T_(n.query)),n.fragment&&(n.fragment=T_(n.fragment))),h&&h.parse&&(h.parse(n,r),h===O_.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 ua(t,e){return ca(t,e).parsed}function SR(t,e){return Z_(t,e).normalized}function Z_(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=ca(t,e);return{normalized:n||o||s||i||a?t:wn(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function z_(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:wn(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=Z_(r,e);return o||s||i||a||c?void 0:n}var rf={SCHEMES:O_,normalize:gR,resolve:yR,resolveComponent:N_,equal:_R,serialize:wn,parse:ua};da.exports=rf;da.exports.default=rf;da.exports.fastUri=rf});var q_=z(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var L_=D_();L_.code='require("ajv/dist/runtime/uri").default';nf.default=L_});var G_=z(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.CodeGen=Me.Name=Me.nil=Me.stringify=Me.str=Me._=Me.KeywordCxt=void 0;var TR=ms();Object.defineProperty(Me,"KeywordCxt",{enumerable:!0,get:function(){return TR.KeywordCxt}});var io=G();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return io._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return io.str}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return io.stringify}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return io.nil}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return io.Name}});Object.defineProperty(Me,"CodeGen",{enumerable:!0,get:function(){return io.CodeGen}});var ER=ra(),V_=hs(),zR=Td(),_s=oa(),RR=G(),vs=ds(),fa=ls(),sf=ae(),U_=d_(),PR=q_(),J_=(t,e)=>new RegExp(t,e);J_.code="new RegExp";var CR=["removeAdditional","useDefaults","coerceTypes"],OR=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),AR={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."},IR={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},F_=200;function NR(t){var e,r,n,o,s,i,a,c,u,l,d,m,p,f,h,g,_,v,y,x,$,I,U,H,ie;let Re=t.strict,D=(e=t.code)===null||e===void 0?void 0:e.optimize,xe=D===!0||D===void 0?1:D||0,jt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:J_,Ur=(o=t.uriResolver)!==null&&o!==void 0?o:PR.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Re)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Re)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Re)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:Re)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:Re)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:xe,regExp:jt}:{optimize:xe,regExp:jt},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:F_,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:F_,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:(I=t.validateSchema)!==null&&I!==void 0?I:!0,validateFormats:(U=t.validateFormats)!==null&&U!==void 0?U:!0,unicodeRegExp:(H=t.unicodeRegExp)!==null&&H!==void 0?H:!0,int32range:(ie=t.int32range)!==null&&ie!==void 0?ie:!0,uriResolver:Ur}}var xs=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,...NR(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new RR.ValueScope({scope:{},prefixes:OR,es5:r,lines:n}),this.logger=qR(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,zR.getRules)(),H_.call(this,AR,e,"NOT SUPPORTED"),H_.call(this,IR,e,"DEPRECATED","warn"),this._metaOpts=DR.call(this),e.formats&&jR.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ZR.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),MR.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=U_;n==="id"&&(o={...U_},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 V_.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,vs.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=B_.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new _s.SchemaEnv({schema:{},schemaId:n});if(r=_s.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=B_.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,vs.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(FR.call(this,n,r),!r)return(0,sf.eachItem)(n,s=>of.call(this,s)),this;BR.call(this,r);let o={...r,type:(0,fa.getJSONTypes)(r.type),schemaType:(0,fa.getJSONTypes)(r.schemaType)};return(0,sf.eachItem)(n,o.type.length===0?s=>of.call(this,s,o):s=>o.type.forEach(i=>of.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]=W_(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,vs.normalizeId)(i||n);let u=vs.getSchemaRefs.call(this,e,n);return c=new _s.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):_s.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{_s.compileSchema.call(this,e)}finally{this.opts=r}}};xs.ValidationError=ER.default;xs.MissingRefError=V_.default;Me.default=xs;function H_(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 B_(t){return t=(0,vs.normalizeId)(t),this.schemas[t]||this.refs[t]}function MR(){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 jR(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function ZR(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 DR(){let t={...this.opts};for(let e of CR)delete t[e];return t}var LR={log(){},warn(){},error(){}};function qR(t){if(t===!1)return LR;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 UR=/^[a-z_$][a-z0-9_$:-]*$/i;function FR(t,e){let{RULES:r}=this;if((0,sf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!UR.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 of(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,fa.getJSONTypes)(e.type),schemaType:(0,fa.getJSONTypes)(e.schemaType)}};e.before?HR.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 HR(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 BR(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=W_(e)),t.validateSchema=this.compile(e,!0))}var VR={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function W_(t){return{anyOf:[t,VR]}}});var K_=z(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var JR={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};af.default=JR});var e0=z($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.callRef=$n.getValidate=void 0;var WR=hs(),X_=gt(),st=G(),ao=cr(),Y_=oa(),pa=ae(),GR={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=Y_.resolveRef.call(c,u,o,r);if(l===void 0)throw new WR.default(n.opts.uriResolver,o,r);if(l instanceof Y_.SchemaEnv)return m(l);return p(l);function d(){if(s===u)return ma(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return ma(t,(0,st._)`${f}.validate`,u,u.$async)}function m(f){let h=Q_(t,f);ma(t,h,f,f.$async)}function p(f){let h=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,st.stringify)(f)}:{ref:f}),g=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:st.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(_),t.ok(g)}}};function Q_(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,st._)`${r.scopeValue("wrapper",{ref:e})}.validate`}$n.getValidate=Q_;function ma(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ao.default.this:st.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,st._)`await ${(0,X_.callValidateCode)(t,e,u)}`),p(e),i||o.assign(f,!0)},h=>{o.if((0,st._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),m(h),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,X_.callValidateCode)(t,e,u),()=>p(e),()=>m(e))}function m(f){let h=(0,st._)`${f}.errors`;o.assign(ao.default.vErrors,(0,st._)`${ao.default.vErrors} === null ? ${h} : ${ao.default.vErrors}.concat(${h})`),o.assign(ao.default.errors,(0,st._)`${ao.default.vErrors}.length`)}function p(f){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=pa.mergeEvaluated.props(o,g.props,s.props));else{let _=o.var("props",(0,st._)`${f}.evaluated.props`);s.props=pa.mergeEvaluated.props(o,_,s.props,st.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=pa.mergeEvaluated.items(o,g.items,s.items));else{let _=o.var("items",(0,st._)`${f}.evaluated.items`);s.items=pa.mergeEvaluated.items(o,_,s.items,st.Name)}}}$n.callRef=ma;$n.default=GR});var t0=z(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var KR=K_(),XR=e0(),YR=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",KR.default,XR.default];cf.default=YR});var r0=z(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var ha=G(),Ar=ha.operators,ga={maximum:{okStr:"<=",ok:Ar.LTE,fail:Ar.GT},minimum:{okStr:">=",ok:Ar.GTE,fail:Ar.LT},exclusiveMaximum:{okStr:"<",ok:Ar.LT,fail:Ar.GTE},exclusiveMinimum:{okStr:">",ok:Ar.GT,fail:Ar.LTE}},QR={message:({keyword:t,schemaCode:e})=>(0,ha.str)`must be ${ga[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ha._)`{comparison: ${ga[t].okStr}, limit: ${e}}`},eP={keyword:Object.keys(ga),type:"number",schemaType:"number",$data:!0,error:QR,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ha._)`${r} ${ga[e].fail} ${n} || isNaN(${r})`)}};uf.default=eP});var n0=z(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var bs=G(),tP={message:({schemaCode:t})=>(0,bs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,bs._)`{multipleOf: ${t}}`},rP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:tP,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,bs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,bs._)`${i} !== parseInt(${i})`;t.fail$data((0,bs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};lf.default=rP});var s0=z(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});function o0(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}df.default=o0;o0.code='require("ajv/dist/runtime/ucs2length").default'});var i0=z(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var kn=G(),nP=ae(),oP=s0(),sP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,kn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,kn._)`{limit: ${t}}`},iP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:sP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?kn.operators.GT:kn.operators.LT,i=o.opts.unicode===!1?(0,kn._)`${r}.length`:(0,kn._)`${(0,nP.useFunc)(t.gen,oP.default)}(${r})`;t.fail$data((0,kn._)`${i} ${s} ${n}`)}};ff.default=iP});var a0=z(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var aP=gt(),cP=ae(),co=G(),uP={message:({schemaCode:t})=>(0,co.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,co._)`{pattern: ${t}}`},lP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:uP,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,co._)`new RegExp`:(0,cP.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,co._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,co._)`!${l}`)}else{let c=(0,aP.usePattern)(t,o);t.fail$data((0,co._)`!${c}.test(${r})`)}}};pf.default=lP});var c0=z(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var ws=G(),dP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ws.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ws._)`{limit: ${t}}`},fP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:dP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ws.operators.GT:ws.operators.LT;t.fail$data((0,ws._)`Object.keys(${r}).length ${o} ${n}`)}};mf.default=fP});var u0=z(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var $s=gt(),ks=G(),pP=ae(),mP={message:({params:{missingProperty:t}})=>(0,ks.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ks._)`{missingProperty: ${t}}`},hP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:mP,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:f}=t.it;for(let h of r)if(p?.[h]===void 0&&!f.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,pP.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ks.nil,d);else for(let p of r)(0,$s.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,$s.checkMissingProp)(t,r,p)),(0,$s.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,$s.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function m(p,f){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,$s.propertyInData)(e,o,p,a.ownProperties)),e.if((0,ks.not)(f),()=>{t.error(),e.break()})},ks.nil)}}};hf.default=hP});var l0=z(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var Ss=G(),gP={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ss.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ss._)`{limit: ${t}}`},yP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:gP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ss.operators.GT:Ss.operators.LT;t.fail$data((0,Ss._)`${r}.length ${o} ${n}`)}};gf.default=yP});var ya=z(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var d0=Id();d0.code='require("ajv/dist/runtime/equal").default';yf.default=d0});var f0=z(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var _f=ls(),je=G(),_P=ae(),vP=ya(),xP={message:({params:{i:t,j:e}})=>(0,je.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,je._)`{i: ${t}, j: ${e}}`},bP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:xP,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,_f.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,je._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,je._)`${r}.length`),h=e.let("j");t.setParams({i:f,j:h}),e.assign(c,!0),e.if((0,je._)`${f} > 1`,()=>(d()?m:p)(f,h))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function m(f,h){let g=e.name("item"),_=(0,_f.checkDataTypes)(u,g,a.opts.strictNumbers,_f.DataType.Wrong),v=e.const("indices",(0,je._)`{}`);e.for((0,je._)`;${f}--;`,()=>{e.let(g,(0,je._)`${r}[${f}]`),e.if(_,(0,je._)`continue`),u.length>1&&e.if((0,je._)`typeof ${g} == "string"`,(0,je._)`${g} += "_"`),e.if((0,je._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(h,(0,je._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,je._)`${v}[${g}] = ${f}`)})}function p(f,h){let g=(0,_P.useFunc)(e,vP.default),_=e.name("outer");e.label(_).for((0,je._)`;${f}--;`,()=>e.for((0,je._)`${h} = ${f}; ${h}--;`,()=>e.if((0,je._)`${g}(${r}[${f}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};vf.default=bP});var p0=z(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var xf=G(),wP=ae(),$P=ya(),kP={message:"must be equal to constant",params:({schemaCode:t})=>(0,xf._)`{allowedValue: ${t}}`},SP={keyword:"const",$data:!0,error:kP,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,xf._)`!${(0,wP.useFunc)(e,$P.default)}(${r}, ${o})`):t.fail((0,xf._)`${s} !== ${r}`)}};bf.default=SP});var m0=z(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var Ts=G(),TP=ae(),EP=ya(),zP={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ts._)`{allowedValues: ${t}}`},RP={keyword:"enum",schemaType:"array",$data:!0,error:zP,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,TP.useFunc)(e,EP.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,Ts.or)(...o.map((f,h)=>m(p,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,p=>e.if((0,Ts._)`${u()}(${r}, ${p})`,()=>e.assign(l,!0).break()))}function m(p,f){let h=o[f];return typeof h=="object"&&h!==null?(0,Ts._)`${u()}(${r}, ${p}[${f}])`:(0,Ts._)`${r} === ${h}`}}};wf.default=RP});var h0=z($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var PP=r0(),CP=n0(),OP=i0(),AP=a0(),IP=c0(),NP=u0(),MP=l0(),jP=f0(),ZP=p0(),DP=m0(),LP=[PP.default,CP.default,OP.default,AP.default,IP.default,NP.default,MP.default,jP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},ZP.default,DP.default];$f.default=LP});var Sf=z(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.validateAdditionalItems=void 0;var Sn=G(),kf=ae(),qP={message:({params:{len:t}})=>(0,Sn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Sn._)`{limit: ${t}}`},UP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:qP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,kf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}g0(t,n)}};function g0(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Sn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Sn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,kf.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Sn._)`${a} <= ${e.length}`);r.if((0,Sn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:kf.Type.Num},u),i.allErrors||r.if((0,Sn.not)(u),()=>r.break())})}}Es.validateAdditionalItems=g0;Es.default=UP});var Tf=z(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.validateTuple=void 0;var y0=G(),_a=ae(),FP=gt(),HP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return _0(t,"additionalItems",e);r.items=!0,!(0,_a.alwaysValidSchema)(r,e)&&t.ok((0,FP.validateArray)(t))}};function _0(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=_a.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,y0._)`${s}.length`);r.forEach((d,m)=>{(0,_a.alwaysValidSchema)(a,d)||(n.if((0,y0._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function l(d){let{opts:m,errSchemaPath:p}=a,f=r.length,h=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(m.strictTuples&&!h){let g=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,_a.checkStrictMode)(a,g,m.strictTuples)}}}zs.validateTuple=_0;zs.default=HP});var v0=z(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var BP=Tf(),VP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,BP.validateTuple)(t,"items")};Ef.default=VP});var b0=z(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var x0=G(),JP=ae(),WP=gt(),GP=Sf(),KP={message:({params:{len:t}})=>(0,x0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,x0._)`{limit: ${t}}`},XP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:KP,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,JP.alwaysValidSchema)(n,e)&&(o?(0,GP.validateAdditionalItems)(t,o):t.ok((0,WP.validateArray)(t)))}};zf.default=XP});var w0=z(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var _t=G(),va=ae(),YP={message:({params:{min:t,max:e}})=>e===void 0?(0,_t.str)`must contain at least ${t} valid item(s)`:(0,_t.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,_t._)`{minContains: ${t}}`:(0,_t._)`{minContains: ${t}, maxContains: ${e}}`},QP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:YP,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,_t._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,va.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,va.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,va.alwaysValidSchema)(s,r)){let h=(0,_t._)`${l} >= ${i}`;a!==void 0&&(h=(0,_t._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?p(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,_t._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let h=e.name("_valid"),g=e.let("count",0);p(h,()=>e.if(h,()=>f(g)))}function p(h,g){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:va.Type.Num,compositeRule:!0},h),g()})}function f(h){e.code((0,_t._)`${h}++`),a===void 0?e.if((0,_t._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,_t._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,_t._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};Rf.default=QP});var S0=z(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.validateSchemaDeps=Vt.validatePropertyDeps=Vt.error=void 0;var Pf=G(),eC=ae(),Rs=gt();Vt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Pf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Pf._)`{property: ${t},
|
|
35
35
|
missingProperty: ${n},
|
|
36
36
|
depsCount: ${e},
|
|
37
|
-
deps: ${r}}`};var F1={keyword:"dependencies",type:"object",schemaType:"object",error:Ft.error,code(t){let[e,r]=U1(t);m0(t,e),h0(t,r)}};function U1({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 m0(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,Ts.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,Ts.checkReportMissingProp)(t,u)}):(r.if((0,Tf._)`${c} && (${(0,Ts.checkMissingProp)(t,a,s)})`),(0,Ts.reportMissingProp)(t,s),r.else())}}Ft.validatePropertyDeps=m0;function h0(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,q1.alwaysValidSchema)(s,e[a])||(r.if((0,Ts.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))}Ft.validateSchemaDeps=h0;Ft.default=F1});var _0=z(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var y0=W(),H1=oe(),B1={message:"property name must be valid",params:({params:t})=>(0,y0._)`{propertyName: ${t.propertyName}}`},V1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:B1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,H1.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,y0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ef.default=V1});var Rf=z(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var ya=ht(),Rt=W(),J1=sr(),_a=oe(),W1={message:"must NOT have additional properties",params:({params:t})=>(0,Rt._)`{additionalProperty: ${t.additionalProperty}}`},K1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:W1,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,_a.alwaysValidSchema)(i,r))return;let u=(0,ya.allSchemaProperties)(n.properties),l=(0,ya.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Rt._)`${s} === ${J1.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,_a.schemaRefOrVal)(i,n.properties,"properties");_=(0,ya.isOwnProperty)(e,v,h)}else u.length?_=(0,Rt.or)(...u.map(v=>(0,Rt._)`${h} === ${v}`)):_=Rt.nil;return l.length&&(_=(0,Rt.or)(_,...l.map(v=>(0,Rt._)`${(0,ya.usePattern)(t,v)}.test(${h})`))),(0,Rt.not)(_)}function p(h){e.code((0,Rt._)`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,_a.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(h,_,!1),e.if((0,Rt.not)(_),()=>{t.reset(),p(h)})):(g(h,_),a||e.if((0,Rt.not)(_),()=>e.break()))}}function g(h,_,v){let y={keyword:"additionalProperties",dataProp:h,dataPropType:_a.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};zf.default=K1});var b0=z(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var G1=ds(),v0=ht(),Pf=oe(),x0=Rf(),X1={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&&x0.default.code(new G1.KeywordCxt(s,x0.default,"additionalProperties"));let i=(0,v0.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Pf.mergeEvaluated.props(e,(0,Pf.toHash)(i),s.props));let a=i.filter(d=>!(0,Pf.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,v0.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)}}};If.default=X1});var S0=z(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var w0=ht(),va=W(),$0=oe(),k0=oe(),Y1={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,w0.allSchemaProperties)(r),c=a.filter(g=>(0,$0.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 va.Name)&&(s.props=(0,k0.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,$0.checkStrictMode)(s,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){e.forIn("key",n,h=>{e.if((0,va._)`${(0,w0.usePattern)(t,g)}.test(${h})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:k0.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,va._)`${d}[${h}]`,!0):!_&&!s.allErrors&&e.if((0,va.not)(l),()=>e.break())})})}}};Cf.default=Y1});var T0=z(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var Q1=oe(),eI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Q1.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"}};Af.default=eI});var E0=z(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var tI=ht(),rI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:tI.validateUnion,error:{message:"must match a schema in anyOf"}};Of.default=rI});var z0=z(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var xa=W(),nI=oe(),oI={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,xa._)`{passingSchemas: ${t.passing}}`},sI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:oI,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,nI.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,xa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,xa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,xa.Name)})})}}};Nf.default=sI});var R0=z(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var iI=oe(),aI={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,iI.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Mf.default=aI});var C0=z(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var ba=W(),I0=oe(),cI={message:({params:t})=>(0,ba.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ba._)`{failingKeyword: ${t.ifClause}}`},uI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:cI,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,I0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=P0(n,"then"),s=P0(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,ba.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,ba._)`${l}`):t.setParams({ifClause:l})}}}};function P0(t,e){let r=t.schema[e];return r!==void 0&&!(0,I0.alwaysValidSchema)(t,r)}jf.default=uI});var A0=z(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var lI=oe(),dI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,lI.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Zf.default=dI});var O0=z(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var fI=bf(),pI=l0(),mI=wf(),hI=f0(),gI=p0(),yI=g0(),_I=_0(),vI=Rf(),xI=b0(),bI=S0(),wI=T0(),$I=E0(),kI=z0(),SI=R0(),TI=C0(),EI=A0();function zI(t=!1){let e=[wI.default,$I.default,kI.default,SI.default,TI.default,EI.default,_I.default,vI.default,yI.default,xI.default,bI.default];return t?e.push(pI.default,hI.default):e.push(fI.default,mI.default),e.push(gI.default),e}Df.default=zI});var N0=z(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var Se=W(),RI={message:({schemaCode:t})=>(0,Se.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Se._)`{format: ${t}}`},PI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:RI,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,Se._)`${f}[${i}]`),h=r.let("fType"),_=r.let("format");r.if((0,Se._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,Se._)`${g}.type || "string"`).assign(_,(0,Se._)`${g}.validate`),()=>r.assign(h,(0,Se._)`"string"`).assign(_,g)),t.fail$data((0,Se.or)(v(),y()));function v(){return c.strictSchema===!1?Se.nil:(0,Se._)`${i} && !${_}`}function y(){let x=l.$async?(0,Se._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,Se._)`${_}(${n})`,$=(0,Se._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,Se._)`${_} && ${_} !== 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 N=$ instanceof RegExp?(0,Se.regexpCode)($):c.code.formats?(0,Se._)`${c.code.formats}${(0,Se.getProperty)(s)}`:void 0,A=r.scopeValue("formats",{key:s,ref:$,code:N});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Se._)`${A}.validate`]:["string",$,A]}function x(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Se._)`await ${_}(${n})`}return typeof h=="function"?(0,Se._)`${_}(${n})`:(0,Se._)`${_}.test(${n})`}}}};Lf.default=PI});var M0=z(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var II=N0(),CI=[II.default];qf.default=CI});var j0=z(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.contentVocabulary=so.metadataVocabulary=void 0;so.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];so.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var D0=z(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var AI=V_(),OI=i0(),NI=O0(),MI=M0(),Z0=j0(),jI=[AI.default,OI.default,(0,NI.default)(),MI.default,Z0.metadataVocabulary,Z0.contentVocabulary];Ff.default=jI});var q0=z(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.DiscrError=void 0;var L0;(function(t){t.Tag="tag",t.Mapping="mapping"})(L0||(wa.DiscrError=L0={}))});var U0=z(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var io=W(),Uf=q0(),F0=ta(),ZI=fs(),DI=oe(),LI={message:({params:{discrError:t,tagName:e}})=>t===Uf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,io._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},qI={keyword:"discriminator",type:"object",schemaType:"object",error:LI,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,io._)`${r}${(0,io.getProperty)(a)}`);e.if((0,io._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Uf.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,io._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:Uf.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,io.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,DI.schemaHasRulesButRef)($,s.self.RULES)){let A=$.$ref;if($=F0.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,A),$ instanceof F0.SchemaEnv&&($=$.schema),$===void 0)throw new ZI.default(s.opts.uriResolver,s.baseId,A)}let N=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);h=h&&(g||_($)),v(N,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 N of x.enum)y(N,$);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]=$}}}};Hf.default=qI});var H0=z((HL,FI)=>{FI.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 Vf=z((_e,Bf)=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.MissingRefError=_e.ValidationError=_e.CodeGen=_e.Name=_e.nil=_e.stringify=_e.str=_e._=_e.KeywordCxt=_e.Ajv=void 0;var UI=L_(),HI=D0(),BI=U0(),B0=H0(),VI=["/properties"],$a="http://json-schema.org/draft-07/schema",ao=class extends UI.default{_addVocabularies(){super._addVocabularies(),HI.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(BI.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(B0,VI):B0;this.addMetaSchema(e,$a,!1),this.refs["http://json-schema.org/schema"]=$a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema($a)?$a:void 0)}};_e.Ajv=ao;Bf.exports=_e=ao;Bf.exports.Ajv=ao;Object.defineProperty(_e,"__esModule",{value:!0});_e.default=ao;var JI=ds();Object.defineProperty(_e,"KeywordCxt",{enumerable:!0,get:function(){return JI.KeywordCxt}});var co=W();Object.defineProperty(_e,"_",{enumerable:!0,get:function(){return co._}});Object.defineProperty(_e,"str",{enumerable:!0,get:function(){return co.str}});Object.defineProperty(_e,"stringify",{enumerable:!0,get:function(){return co.stringify}});Object.defineProperty(_e,"nil",{enumerable:!0,get:function(){return co.nil}});Object.defineProperty(_e,"Name",{enumerable:!0,get:function(){return co.Name}});Object.defineProperty(_e,"CodeGen",{enumerable:!0,get:function(){return co.CodeGen}});var WI=Qi();Object.defineProperty(_e,"ValidationError",{enumerable:!0,get:function(){return WI.default}});var KI=fs();Object.defineProperty(_e,"MissingRefError",{enumerable:!0,get:function(){return KI.default}})});var Q0=z(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.formatNames=Ht.fastFormats=Ht.fullFormats=void 0;function Ut(t,e){return{validate:t,compare:e}}Ht.fullFormats={date:Ut(K0,Gf),time:Ut(Wf(!0),Xf),"date-time":Ut(V0(!0),X0),"iso-time":Ut(Wf(),G0),"iso-date-time":Ut(V0(),Y0),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:tC,"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:cC,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:rC,int32:{type:"number",validate:sC},int64:{type:"number",validate:iC},float:{type:"number",validate:W0},double:{type:"number",validate:W0},password:!0,binary:!0};Ht.fastFormats={...Ht.fullFormats,date:Ut(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Gf),time:Ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Xf),"date-time":Ut(/^\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,X0),"iso-time":Ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,G0),"iso-date-time":Ut(/^\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,Y0),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};Ht.formatNames=Object.keys(Ht.fullFormats);function GI(t){return t%4===0&&(t%100!==0||t%400===0)}var XI=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,YI=[0,31,28,31,30,31,30,31,31,30,31,30,31];function K0(t){let e=XI.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&&GI(r)?29:YI[n])}function Gf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Jf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Wf(t){return function(r){let n=Jf.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 Xf(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 G0(t,e){if(!(t&&e))return;let r=Jf.exec(t),n=Jf.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 Kf=/t|\s/i;function V0(t){let e=Wf(t);return function(n){let o=n.split(Kf);return o.length===2&&K0(o[0])&&e(o[1])}}function X0(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Y0(t,e){if(!(t&&e))return;let[r,n]=t.split(Kf),[o,s]=e.split(Kf),i=Gf(r,o);if(i!==void 0)return i||Xf(n,s)}var QI=/\/|:/,eC=/^(?:[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 tC(t){return QI.test(t)&&eC.test(t)}var J0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function rC(t){return J0.lastIndex=0,J0.test(t)}var nC=-(2**31),oC=2**31-1;function sC(t){return Number.isInteger(t)&&t<=oC&&t>=nC}function iC(t){return Number.isInteger(t)}function W0(){return!0}var aC=/[^\\]\\Z/;function cC(t){if(aC.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var ev=z(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.formatLimitDefinition=void 0;var uC=Vf(),Pt=W(),Ir=Pt.operators,ka={formatMaximum:{okStr:"<=",ok:Ir.LTE,fail:Ir.GT},formatMinimum:{okStr:">=",ok:Ir.GTE,fail:Ir.LT},formatExclusiveMaximum:{okStr:"<",ok:Ir.LT,fail:Ir.GTE},formatExclusiveMinimum:{okStr:">",ok:Ir.GT,fail:Ir.LTE}},lC={message:({keyword:t,schemaCode:e})=>(0,Pt.str)`should be ${ka[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Pt._)`{comparison: ${ka[t].okStr}, limit: ${e}}`};uo.formatLimitDefinition={keyword:Object.keys(ka),type:"string",schemaType:"string",$data:!0,error:lC,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 uC.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,Pt._)`${m}[${c.schemaCode}]`);t.fail$data((0,Pt.or)((0,Pt._)`typeof ${p} != "object"`,(0,Pt._)`${p} instanceof RegExp`,(0,Pt._)`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,Pt._)`${i.code.formats}${(0,Pt.getProperty)(m)}`:void 0});t.fail$data(d(f))}function d(m){return(0,Pt._)`${m}.compare(${r}, ${n}) ${ka[o].fail} 0`}},dependencies:["format"]};var dC=t=>(t.addKeyword(uo.formatLimitDefinition),t);uo.default=dC});var ov=z((Es,nv)=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var lo=Q0(),fC=ev(),Yf=W(),tv=new Yf.Name("fullFormats"),pC=new Yf.Name("fastFormats"),Qf=(t,e={keywords:!0})=>{if(Array.isArray(e))return rv(t,e,lo.fullFormats,tv),t;let[r,n]=e.mode==="fast"?[lo.fastFormats,pC]:[lo.fullFormats,tv],o=e.formats||lo.formatNames;return rv(t,o,r,n),e.keywords&&(0,fC.default)(t),t};Qf.get=(t,e="full")=>{let n=(e==="fast"?lo.fastFormats:lo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function rv(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Yf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}nv.exports=Es=Qf;Object.defineProperty(Es,"__esModule",{value:!0});Es.default=Qf});var ix={};$o(ix,{findEmbeddingModel:()=>sx,ollamaUrl:()=>xp,semanticRerank:()=>XA});import{createHash as LA}from"node:crypto";import{existsSync as qA,mkdirSync as FA,readFileSync as UA,writeFileSync as HA}from"node:fs";import{homedir as BA}from"node:os";import{join as vp}from"node:path";function xp(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 ox(t,e,r=6e4){let n=await fetch(xp()+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 sx(t){let r=((await ox("/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=>VA.test(n))}function Fa(){return vp(process.env.XDG_CACHE_HOME??vp(BA(),".cache"),"context-doctor","embeddings.json")}function JA(){try{return qA(Fa())?JSON.parse(UA(Fa(),"utf8")):{}}catch{return{}}}function WA(t){try{let e=Object.keys(t);if(e.length>nx)for(let r of e.slice(0,e.length-nx))delete t[r];FA(vp(Fa(),".."),{recursive:!0}),HA(Fa(),JSON.stringify(t))}catch{}}async function KA(t,e){let r=[];for(let n=0;n<e.length;n+=rx){let o=await ox("/api/embed",{model:t,input:e.slice(n,n+rx),truncate:!0});r.push(...o.embeddings)}return r}function GA(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 XA(t,e,r={}){let n;try{n=await sx(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${xp()} (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=JA(),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 KA(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&&WA(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:GA(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 VA,rx,nx,ax=X(()=>{"use strict";VA=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,rx=64,nx=5e4});var tb,rb=X(()=>{tb="x-hono-already-sent"});var nb,ob=X(()=>{nb=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{STATUS_CODES as RF,ServerResponse as PN,createServer as PF}from"node:http";import{Http2ServerRequest as dr,constants as IN}from"node:http2";import{Readable as sb}from"node:stream";async function rM(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function bb(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 fb(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:bb(t.getReader(),e)}var Ct,CN,AN,ec,ib,ab,Bp,mb,Vp,hb,ON,NN,MN,Zp,jN,ZN,DN,bo,gb,LN,qN,Mp,Dp,yb,Jp,cb,rc,ub,FN,Zr,ur,wo,Ns,_b,vb,As,Lp,qp,jr,tc,fr,lb,Os,nc,Ms,UN,HN,BN,VN,JN,WN,KN,Wp,GN,db,XN,Kt,YN,Sn,Fp,xo,lr,oc,Wt,QN,eM,tM,Up,sc,pb,nM,oM,wb,sM,iM,aM,$b,ic,Hp,kb,jp,Sb,Tb,cM,Kp,uM,lM,dM,fM,pM,OF,Eb=X(()=>{rb();ob();Ct=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},CN=new Set(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","server","user-agent"]),AN=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,ec=t=>t===9||t===10||t===13||t===32,ib=t=>{if(!ec(t.charCodeAt(0))&&!ec(t.charCodeAt(t.length-1)))return t;let e=0,r=t.length;for(;e<r&&ec(t.charCodeAt(e));)e++;for(;r>e&&ec(t.charCodeAt(r-1));)r--;return t.slice(e,r)},ab=/[\0\r\n]/,Bp=globalThis.Headers,mb=(t,e=Bp)=>{let r=new e;for(let n=0;n<t.length;n+=2){let o=t[n];o.startsWith(":")||r.append(o,t[n+1])}return r},Vp=class{#e;#t;#n;#o;constructor(t){this.#e=t,t instanceof dr&&(this.#t=t.rawHeaders.slice())}get#s(){return this.#t??=this.#e.rawHeaders.slice()}get#r(){return this.#n||(this.#n=mb(this.#s),this.#t=void 0),this.#n}#i(t){if(typeof t=="string"){if(!AN.test(t))throw new TypeError(`Invalid header name: ${t}`);return t.toLowerCase()}}#a(t){let e=this.#e instanceof dr?void 0:this.#e.headers;if(!e||CN.has(t)||t==="set-cookie"||t==="__proto__")return;if(!Object.hasOwn(e,t))return null;let r=e[t];if(typeof r=="string"){let n=ib(r);return ab.test(n)?void 0:n}}#c(t,e){let r=e==="cookie"?"; ":", ",n=null;for(let o=0;o<t.length;o+=2){let s=t[o];if(s.length===e.length&&s.toLowerCase()===e){let i=ib(t[o+1]);if(ab.test(i)){this.#o=!0;return}n=n===null?i:n+r+i}}return n}append(t,e){this.#r.append(t,e)}delete(t){this.#r.delete(t)}get(t){let e=this.#i(t);if(e&&!this.#n&&!this.#o){let r=this.#a(e);if(r!==void 0)return r;let n=this.#c(this.#s,e);if(n!==void 0)return n}return this.#r.get(t)}has(t){let e=this.#i(t);if(e&&!this.#n&&!this.#o){let r=this.#a(e);if(r!==void 0)return r!==null;let n=this.#c(this.#s,e);if(n!==void 0)return n!==null}return this.#r.has(t)}set(t,e){this.#r.set(t,e)}getSetCookie(){return this.#r.getSetCookie()}keys(){return this.#r.keys()}values(){return this.#r.values()}entries(){return this.#r.entries()}forEach(t,e){this.#r.forEach((r,n)=>{t.call(e,r,n,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Vp.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Headers (lightweight) ${r(Object.fromEntries(this),{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Vp.prototype,Bp.prototype);hb=t=>globalThis.Headers===Bp?new Vp(t):mb(t.rawHeaders,globalThis.Headers),ON=/^\/[!#$&-;=?-\[\]_a-z~]*$/,NN=/\/\.\.?(?:[/?#]|$)/,MN=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,Zp=t=>{let e=t.indexOf("\\");if(e!==-1){let r=t.indexOf("?");if(r===-1||e<r)throw new Ct("Backslash in request path")}},jN=(t,e,r)=>{let n=`${t}://${e}${r}`;if(MN.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Ct("Invalid URL");return!ON.test(r)||NN.test(r)?(Zp(r),new URL(n).href):n}else{Zp(r);let o=new URL(n);if(o.hostname.length!==e.length&&o.hostname!==(e.includes(":")?e.replace(/:\d+$/,""):e).toLowerCase())throw new Ct("Invalid host header");return o.href}},ZN=t=>t instanceof Ct?t:new Ct(t.message,{cause:t}),DN=global.Request,bo=class extends DN{constructor(t,e){if(typeof t=="object"&&Zr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[fr]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[Zr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},gb=Symbol("wrapBodyStream"),LN=new Set(["latin1","binary","hex","base64","base64url"]),qN=t=>t===null||LN.has(t),Mp=Symbol("bodyBufferedBeforeDisconnect"),Dp=Symbol("bodyBufferedLengthBeforeDisconnect"),yb=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Jp=t=>!(t instanceof dr)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&qN(t.readableEncoding),cb=t=>{if(t.readableDidRead||!Jp(t))return;let e=t;e[Dp]??=t.readableLength},rc=(t,e)=>{if(t.readableDidRead&&!e||!Jp(t))return;let r=t;if(r[Mp]!==void 0)return r[Mp];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Dp]!==void 0&&t.readableLength!==r[Dp])n=nc();else{let s=e??[],i=t.read();i!==null&&s.push(yb(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=nc())}}return r[Mp]=n,n},ub=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},FN=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new bo(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[gb]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=rc(n);if(l!==void 0){ub(a,l);return}}i||=sb.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=rc(n);i!==void 0?s.body=new ReadableStream({start(a){ub(a,i)}}):s.body=sb.toWeb(n)}return new bo(e,s)},Zr=Symbol("getRequestCache"),ur=Symbol("requestCache"),wo=Symbol("incomingKey"),Ns=Symbol("urlKey"),_b=Symbol("methodKey"),vb=Symbol("headersKey"),As=Symbol("abortControllerKey"),Lp=Symbol("getAbortController"),qp=Symbol("abortRequest"),jr=Symbol("bodyBuffer"),tc=Symbol("bodyReadPromise"),fr=Symbol("bodyConsumedDirectly"),lb=Symbol("bodyLockReader"),Os=Symbol("abortReason"),nc=()=>new TypeError("Body is unusable"),Ms=()=>Promise.reject(nc()),UN=new TextDecoder,HN=t=>{if(t[fr])return Ms();t[fr]=!0},BN=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),VN=t=>(t[vb]||=hb(t[wo])).get("content-type")||"",JN=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,WN=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}},KN=t=>{if(!JN.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.`)},Wp=(t,e,r)=>{if(t[fr])return Ms();let n=t.method;if(n==="GET"||n==="HEAD")return t[Zr]()[e]();let o=KN(n);if(o)return Promise.reject(o);if(t[ur]&&n!=="TRACE")return t[ur][e]();let s=HN(t);if(s)return s;let i=GN(t);if(i){let a=Promise.resolve(r(i,t));return t[jr]=void 0,a}return XN(t).then(a=>{let c=r(a,t);return t[jr]=void 0,c})},GN=t=>{let e=t[wo];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},db=(t,e)=>{if(e.errored)return e.errored;let r=t[Os];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},XN=t=>{if(t[jr])return Promise.resolve(t[jr]);if(t[tc])return t[tc];let e=t[wo];if(e.readableDidRead)return Ms();let r=rc(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[jr]=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!Jp(e)||h&&h.code!=="ECONNRESET"?!1:(c(()=>{let _=rc(e,i);_ instanceof Error?s(_):_===void 0?s(g??db(t,e)):(t[jr]=_,o(_))}),!0)},l=g=>{i.push(yb(g,e.readableEncoding))},d=()=>{c(()=>{let g=i.length===1?i[0]:Buffer.concat(i);t[jr]=g,o(g)})},m=g=>{u(g)||c(()=>{s(g)})},p=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(db(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",m),e.off("close",p),t[tc]=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[tc]=n,n},Kt={get method(){return this[_b]},get url(){return this[Ns]},get headers(){return this[vb]||=hb(this[wo])},[qp](t){this[Os]===void 0&&(this[Os]=t);let e=this[As];e&&!e.signal.aborted&&e.abort(t)},[Lp](){return this[As]||=new AbortController,this[Os]!==void 0&&!this[As].signal.aborted&&this[As].abort(this[Os]),this[As]},[Zr](){let t=this[Lp]();if(this[ur])return this[ur];let e=this.method;if(this[fr]&&!(e==="GET"||e==="HEAD")){this[jr]=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 bo(this[Ns],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[ur]=n}return this[ur]=FN(this.method,this[Ns],this.headers,this[wo],t)},get body(){if(!this[fr])return this[Zr]().body;let t=this[Zr]();return!this[lb]&&t.body&&(this[lb]=t.body.getReader()),t.body},get bodyUsed(){return this[fr]?!0:this[ur]?this[ur].bodyUsed:!1}};Object.defineProperty(Kt,"signal",{get(){return this[Lp]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(Kt,t,{get(){return this[Zr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(Kt,t,{value:function(){if(this[fr]){if(t==="clone")throw nc();return Ms()}return this[Zr]()[t]()}})});Object.defineProperty(Kt,"text",{value:function(){return Wp(this,"text",t=>UN.decode(t))}});Object.defineProperty(Kt,"arrayBuffer",{value:function(){return Wp(this,"arrayBuffer",t=>BN(t))}});Object.defineProperty(Kt,"blob",{value:function(){return Wp(this,"blob",(t,e)=>{let r=VN(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(Kt,"json",{value:function(){return this[fr]?Ms():this.text().then(JSON.parse)}});Object.defineProperty(Kt,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[ur]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Kt,bo.prototype);YN=(t,e)=>{let r=Object.create(Kt);r[wo]=t,r[_b]=WN(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof dr)throw new Ct("Absolute URL for :path is not allowed in HTTP/2");try{Zp(n),r[Ns]=new URL(n).href}catch(i){throw new Ct("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof dr?t.authority:t.headers.host)||e;if(!o)throw new Ct("Missing host header");let s;if(t instanceof dr){if(s=t.scheme,!(s==="http"||s==="https"))throw new Ct("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[Ns]=jN(s,o,n)}catch(i){throw i instanceof Ct?i:new Ct("Invalid URL",{cause:i})}return r},Sn="text/plain; charset=UTF-8",Fp=Symbol("responseCache"),xo=Symbol("getResponseCache"),lr=Symbol("cache"),oc=global.Response,Wt=class xb{#e;#t;[xo](){let e=this[lr],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[lr],this[Fp]||=new oc(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 oc){let o=r[Fp];if(o){this.#t=o,this[xo]();return}this.#t=r instanceof xb?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[lr]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[lr];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Sn}))),e[2]):this[xo]().headers}get status(){return this[lr]?.[0]??this[xo]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Wt.prototype,t,{get(){return this[xo]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Wt.prototype,t,{value:function(){return this[xo]()[t]()}})});Object.defineProperty(Wt.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[Fp]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Wt,oc);Object.setPrototypeOf(Wt.prototype,oc.prototype);QN=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,eM=t=>t instanceof URL?t.href:QN.test(t)?t:new URL(t).href,tM=new Set([301,302,303,307,308]);Object.defineProperty(Wt,"redirect",{value:function(e,r=302){if(!tM.has(r))throw new RangeError("Invalid status code");return new Wt(null,{status:r,headers:{location:eM(e)}})},writable:!0,configurable:!0});Object.defineProperty(Wt,"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 Wt(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});Up=(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},sc=Symbol("outgoingEnded"),pb=Symbol("incomingDraining"),nM=500,oM=64*1024*1024,wb=t=>{let e=t;if(t.destroyed||e[pb])return;if(e[pb]=!0,t instanceof dr){try{t.stream?.close?.(IN.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,nM);s.unref?.();let i=a=>{r+=a.length,r>oM&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},sM=(t,e,r,n)=>()=>{e.errored?(cb(e),t[qp](e.errored.toString())):(!r.writableFinished||e instanceof dr&&e.aborted)&&(cb(e),t[qp]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{wb(e)})})},iM=t=>{if(!(lr in t))return!1;let e=t[lr][1];return e===null||typeof e=="string"||e instanceof Uint8Array},aM=()=>new Response(null,{status:400}),$b=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),ic=(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 instanceof PN&&(e._contentLength=null),e.writeHead(500,{"Content-Type":"text/plain"})),e.end(`Error: ${r.message}`),e.destroy(r))},Hp=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},kb=(t,e,r)=>{let n=t;return n._contentLength===null&&n._hasBody&&n.useChunkedEncodingByDefault&&!n._removedContLen&&e>=200&&e!==204&&e!==304&&!t.hasHeader("content-length")&&!t.hasHeader("transfer-encoding")&&!t.hasHeader("trailer")?(n._contentLength=r,!0):!1},jp=(t,e,r)=>{kb(t,e,r)?t.writeHead(e,{"Content-Type":Sn}):t.writeHead(e,{"Content-Type":Sn,"Content-Length":r})},Sb=async(t,e)=>{let[r,n,o]=t[lr];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(jp(e,r,Buffer.byteLength(n)),e.end(n)):n instanceof Uint8Array?(jp(e,r,n.byteLength),e.end(n)):n instanceof Blob?(jp(e,r,n.size),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":Sn}),Hp(e),await fb(n,e)?.catch(c=>ic(c,e))),e[sc]?.();return}let s=!1,i=!1,a=!0;if(o instanceof Headers)s=o.has("content-length"),o=Up(o,n===null?void 0:Sn);else if(Array.isArray(o)){let c=new Headers(o);s=c.has("content-length"),o=Up(c,n===null?void 0:Sn)}else{i=!0;for(let c in o){if(c.length===14&&c.toLowerCase()==="content-length"){s=!0;break}(c.length===17&&c.toLowerCase()==="transfer-encoding"||c.length===7&&c.toLowerCase()==="trailer")&&(a=!1)}}if(!s){let c;typeof n=="string"?c=Buffer.byteLength(n):n instanceof Uint8Array?c=n.byteLength:n instanceof Blob&&(c=n.size),c!==void 0&&(!i||!a||!kb(e,r,c))&&(i&&(o={...o}),o["Content-Length"]=c)}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())):(Hp(e),await fb(n,e)?.catch(c=>ic(c,e))),e[sc]?.()},Tb=t=>typeof t.then=="function",cM=async(t,e,r={})=>{if(Tb(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($b);if(lr in t)return Sb(t,e);let n=Up(t.headers,t.body===null?void 0:Sn);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 rM(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&&Hp(e),await bb(o,e,a))}else n[tb]||(e.writeHead(t.status,n),e.end());e[sc]?.()},Kp=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==bo&&(Object.defineProperty(global,"Request",{value:bo}),Object.defineProperty(global,"Response",{value:Wt})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",sM(i,n,o,a)))};try{if(i=YN(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[gb]=!0,n instanceof dr&&(o[sc]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!Tb(s)&&iM(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||wb(n)}),Sb(s,o);u()}catch(l){if(s)return ic(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:ZN(l)),!s)return}else i?s=$b(l):s=aM()}try{return await cM(s,o,e)}catch(l){return ic(l,o)}}},uM=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??""}},lM=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}},dM=()=>Symbol("connection"),fM=Symbol("CONNECTION_SYMBOL_KEY"),pM=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),OF=nb(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[pM];if(!o||!n.incoming)return new Response(null,{status:500});let s=dM();return n[fM]=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 uM("close",{code:d,reason:m.toString()}),u)}catch(p){(r?.onError??console.error)(p)}}),i.on("error",d=>{try{e?.onError?.(new lM("error",{error:d}),u)}catch(m){(r?.onError??console.error)(m)}})})(),new Response})});var Ib=z(Gp=>{"use strict";var zb=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,mM=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Rb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,hM=/\\([\u000b\u0020-\u00ff])/g,gM=/([\\"])/g,Pb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Gp.format=yM;Gp.parse=_M;function yM(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!Pb.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],!Rb.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+xM(e[o])}return n}function _M(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?vM(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(!Pb.test(n))throw new TypeError("invalid media type");var o=new bM(n.toLowerCase());if(r!==-1){var s,i,a;for(zb.lastIndex=r;i=zb.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(hM,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function vM(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 xM(t){var e=String(t);if(Rb.test(e))return e;if(e.length>0&&!mM.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(gM,"\\$1")+'"'}function bM(t){this.parameters=Object.create(null),this.type=t}});function wM(t){if(t)try{return Cb.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function Ab(t){return t==="application/json"?!0:wM(t)==="application/json"}var Cb,Ob=X(()=>{Cb=lc(Ib(),1)});function Nb(t){return`Payload Too Large: Request body must not exceed ${t} bytes`}function Mb(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 jb(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 Zb=X(()=>{});function Db(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var Lb=X(()=>{});var ac,qb=X(()=>{Ob();Zb();Lb();wr();ac=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=Mb(e.maxRequestBodySize)}startKeepAlive(e,r){if(this._closed)return;let n=Db(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
|
|
37
|
+
deps: ${r}}`};var tC={keyword:"dependencies",type:"object",schemaType:"object",error:Vt.error,code(t){let[e,r]=rC(t);$0(t,e),k0(t,r)}};function rC({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 $0(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,Rs.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,Rs.checkReportMissingProp)(t,u)}):(r.if((0,Pf._)`${c} && (${(0,Rs.checkMissingProp)(t,a,s)})`),(0,Rs.reportMissingProp)(t,s),r.else())}}Vt.validatePropertyDeps=$0;function k0(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,eC.alwaysValidSchema)(s,e[a])||(r.if((0,Rs.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))}Vt.validateSchemaDeps=k0;Vt.default=tC});var E0=z(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var T0=G(),nC=ae(),oC={message:"property name must be valid",params:({params:t})=>(0,T0._)`{propertyName: ${t.propertyName}}`},sC={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:oC,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,nC.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)}};Cf.default=sC});var Af=z(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var xa=gt(),Ct=G(),iC=cr(),ba=ae(),aC={message:"must NOT have additional properties",params:({params:t})=>(0,Ct._)`{additionalProperty: ${t.additionalProperty}}`},cC={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:aC,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,ba.alwaysValidSchema)(i,r))return;let u=(0,xa.allSchemaProperties)(n.properties),l=(0,xa.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Ct._)`${s} === ${iC.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?f(g):e.if(m(g),()=>f(g))})}function m(g){let _;if(u.length>8){let v=(0,ba.schemaRefOrVal)(i,n.properties,"properties");_=(0,xa.isOwnProperty)(e,v,g)}else u.length?_=(0,Ct.or)(...u.map(v=>(0,Ct._)`${g} === ${v}`)):_=Ct.nil;return l.length&&(_=(0,Ct.or)(_,...l.map(v=>(0,Ct._)`${(0,xa.usePattern)(t,v)}.test(${g})`))),(0,Ct.not)(_)}function p(g){e.code((0,Ct._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ba.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(h(g,_,!1),e.if((0,Ct.not)(_),()=>{t.reset(),p(g)})):(h(g,_),a||e.if((0,Ct.not)(_),()=>e.break()))}}function h(g,_,v){let y={keyword:"additionalProperties",dataProp:g,dataPropType:ba.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};Of.default=cC});var P0=z(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var uC=ms(),z0=gt(),If=ae(),R0=Af(),lC={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&&R0.default.code(new uC.KeywordCxt(s,R0.default,"additionalProperties"));let i=(0,z0.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=If.mergeEvaluated.props(e,(0,If.toHash)(i),s.props));let a=i.filter(d=>!(0,If.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,z0.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)}}};Nf.default=lC});var I0=z(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var C0=gt(),wa=G(),O0=ae(),A0=ae(),dC={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,C0.allSchemaProperties)(r),c=a.filter(h=>(0,O0.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof wa.Name)&&(s.props=(0,A0.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let h of a)u&&p(h),s.allErrors?f(h):(e.var(l,!0),f(h),e.if(l))}function p(h){for(let g in u)new RegExp(h).test(g)&&(0,O0.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",n,g=>{e.if((0,wa._)`${(0,C0.usePattern)(t,h)}.test(${g})`,()=>{let _=c.includes(h);_||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:A0.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,wa._)`${d}[${g}]`,!0):!_&&!s.allErrors&&e.if((0,wa.not)(l),()=>e.break())})})}}};Mf.default=dC});var N0=z(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var fC=ae(),pC={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,fC.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"}};jf.default=pC});var M0=z(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var mC=gt(),hC={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:mC.validateUnion,error:{message:"must match a schema in anyOf"}};Zf.default=hC});var j0=z(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var $a=G(),gC=ae(),yC={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,$a._)`{passingSchemas: ${t.passing}}`},_C={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:yC,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,gC.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,$a._)`${c} && ${i}`).assign(i,!1).assign(a,(0,$a._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,$a.Name)})})}}};Df.default=_C});var Z0=z(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var vC=ae(),xC={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,vC.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Lf.default=xC});var q0=z(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var ka=G(),L0=ae(),bC={message:({params:t})=>(0,ka.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ka._)`{failingKeyword: ${t.ifClause}}`},wC={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:bC,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,L0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=D0(n,"then"),s=D0(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,ka.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,ka._)`${l}`):t.setParams({ifClause:l})}}}};function D0(t,e){let r=t.schema[e];return r!==void 0&&!(0,L0.alwaysValidSchema)(t,r)}qf.default=wC});var U0=z(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var $C=ae(),kC={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,$C.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Uf.default=kC});var F0=z(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var SC=Sf(),TC=v0(),EC=Tf(),zC=b0(),RC=w0(),PC=S0(),CC=E0(),OC=Af(),AC=P0(),IC=I0(),NC=N0(),MC=M0(),jC=j0(),ZC=Z0(),DC=q0(),LC=U0();function qC(t=!1){let e=[NC.default,MC.default,jC.default,ZC.default,DC.default,LC.default,CC.default,OC.default,PC.default,AC.default,IC.default];return t?e.push(TC.default,zC.default):e.push(SC.default,EC.default),e.push(RC.default),e}Ff.default=qC});var H0=z(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var Te=G(),UC={message:({schemaCode:t})=>(0,Te.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Te._)`{format: ${t}}`},FC={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:UC,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?m():p();function m(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,Te._)`${f}[${i}]`),g=r.let("fType"),_=r.let("format");r.if((0,Te._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Te._)`${h}.type || "string"`).assign(_,(0,Te._)`${h}.validate`),()=>r.assign(g,(0,Te._)`"string"`).assign(_,h)),t.fail$data((0,Te.or)(v(),y()));function v(){return c.strictSchema===!1?Te.nil:(0,Te._)`${i} && !${_}`}function y(){let x=l.$async?(0,Te._)`(${h}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,Te._)`${_}(${n})`,$=(0,Te._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,Te._)`${_} && ${_} !== true && ${g} === ${e} && !${$}`}}function p(){let f=d.formats[s];if(!f){v();return}if(f===!0)return;let[h,g,_]=y(f);h===e&&t.pass(x());function v(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function y($){let I=$ instanceof RegExp?(0,Te.regexpCode)($):c.code.formats?(0,Te._)`${c.code.formats}${(0,Te.getProperty)(s)}`:void 0,U=r.scopeValue("formats",{key:s,ref:$,code:I});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Te._)`${U}.validate`]:["string",$,U]}function x(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Te._)`await ${_}(${n})`}return typeof g=="function"?(0,Te._)`${_}(${n})`:(0,Te._)`${_}.test(${n})`}}}};Hf.default=FC});var B0=z(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var HC=H0(),BC=[HC.default];Bf.default=BC});var V0=z(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.contentVocabulary=uo.metadataVocabulary=void 0;uo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];uo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var W0=z(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var VC=t0(),JC=h0(),WC=F0(),GC=B0(),J0=V0(),KC=[VC.default,JC.default,(0,WC.default)(),GC.default,J0.metadataVocabulary,J0.contentVocabulary];Vf.default=KC});var K0=z(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.DiscrError=void 0;var G0;(function(t){t.Tag="tag",t.Mapping="mapping"})(G0||(Sa.DiscrError=G0={}))});var Y0=z(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var lo=G(),Jf=K0(),X0=oa(),XC=hs(),YC=ae(),QC={message:({params:{discrError:t,tagName:e}})=>t===Jf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,lo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},eO={keyword:"discriminator",type:"object",schemaType:"object",error:QC,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,lo._)`${r}${(0,lo.getProperty)(a)}`);e.if((0,lo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Jf.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,lo._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:Jf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(h,lo.Name),f}function m(){var p;let f={},h=_(o),g=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,YC.schemaHasRulesButRef)($,s.self.RULES)){let U=$.$ref;if($=X0.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,U),$ instanceof X0.SchemaEnv&&($=$.schema),$===void 0)throw new XC.default(s.opts.uriResolver,s.baseId,U)}let I=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||_($)),v(I,x)}if(!g)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 I of x.enum)y(I,$);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]=$}}}};Wf.default=eO});var Q0=z((oq,tO)=>{tO.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 Kf=z((ve,Gf)=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.MissingRefError=ve.ValidationError=ve.CodeGen=ve.Name=ve.nil=ve.stringify=ve.str=ve._=ve.KeywordCxt=ve.Ajv=void 0;var rO=G_(),nO=W0(),oO=Y0(),ev=Q0(),sO=["/properties"],Ta="http://json-schema.org/draft-07/schema",fo=class extends rO.default{_addVocabularies(){super._addVocabularies(),nO.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(oO.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ev,sO):ev;this.addMetaSchema(e,Ta,!1),this.refs["http://json-schema.org/schema"]=Ta}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ta)?Ta:void 0)}};ve.Ajv=fo;Gf.exports=ve=fo;Gf.exports.Ajv=fo;Object.defineProperty(ve,"__esModule",{value:!0});ve.default=fo;var iO=ms();Object.defineProperty(ve,"KeywordCxt",{enumerable:!0,get:function(){return iO.KeywordCxt}});var po=G();Object.defineProperty(ve,"_",{enumerable:!0,get:function(){return po._}});Object.defineProperty(ve,"str",{enumerable:!0,get:function(){return po.str}});Object.defineProperty(ve,"stringify",{enumerable:!0,get:function(){return po.stringify}});Object.defineProperty(ve,"nil",{enumerable:!0,get:function(){return po.nil}});Object.defineProperty(ve,"Name",{enumerable:!0,get:function(){return po.Name}});Object.defineProperty(ve,"CodeGen",{enumerable:!0,get:function(){return po.CodeGen}});var aO=ra();Object.defineProperty(ve,"ValidationError",{enumerable:!0,get:function(){return aO.default}});var cO=hs();Object.defineProperty(ve,"MissingRefError",{enumerable:!0,get:function(){return cO.default}})});var cv=z(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.formatNames=Wt.fastFormats=Wt.fullFormats=void 0;function Jt(t,e){return{validate:t,compare:e}}Wt.fullFormats={date:Jt(ov,ep),time:Jt(Yf(!0),tp),"date-time":Jt(tv(!0),iv),"iso-time":Jt(Yf(),sv),"iso-date-time":Jt(tv(),av),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:mO,"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:bO,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:hO,int32:{type:"number",validate:_O},int64:{type:"number",validate:vO},float:{type:"number",validate:nv},double:{type:"number",validate:nv},password:!0,binary:!0};Wt.fastFormats={...Wt.fullFormats,date:Jt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ep),time:Jt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,tp),"date-time":Jt(/^\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,iv),"iso-time":Jt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,sv),"iso-date-time":Jt(/^\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,av),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};Wt.formatNames=Object.keys(Wt.fullFormats);function uO(t){return t%4===0&&(t%100!==0||t%400===0)}var lO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,dO=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ov(t){let e=lO.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&&uO(r)?29:dO[n])}function ep(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Xf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Yf(t){return function(r){let n=Xf.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 tp(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 sv(t,e){if(!(t&&e))return;let r=Xf.exec(t),n=Xf.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 tv(t){let e=Yf(t);return function(n){let o=n.split(Qf);return o.length===2&&ov(o[0])&&e(o[1])}}function iv(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function av(t,e){if(!(t&&e))return;let[r,n]=t.split(Qf),[o,s]=e.split(Qf),i=ep(r,o);if(i!==void 0)return i||tp(n,s)}var fO=/\/|:/,pO=/^(?:[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 mO(t){return fO.test(t)&&pO.test(t)}var rv=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function hO(t){return rv.lastIndex=0,rv.test(t)}var gO=-(2**31),yO=2**31-1;function _O(t){return Number.isInteger(t)&&t<=yO&&t>=gO}function vO(t){return Number.isInteger(t)}function nv(){return!0}var xO=/[^\\]\\Z/;function bO(t){if(xO.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var uv=z(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.formatLimitDefinition=void 0;var wO=Kf(),Ot=G(),Ir=Ot.operators,Ea={formatMaximum:{okStr:"<=",ok:Ir.LTE,fail:Ir.GT},formatMinimum:{okStr:">=",ok:Ir.GTE,fail:Ir.LT},formatExclusiveMaximum:{okStr:"<",ok:Ir.LT,fail:Ir.GTE},formatExclusiveMinimum:{okStr:">",ok:Ir.GT,fail:Ir.LTE}},$O={message:({keyword:t,schemaCode:e})=>(0,Ot.str)`should be ${Ea[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ot._)`{comparison: ${Ea[t].okStr}, limit: ${e}}`};mo.formatLimitDefinition={keyword:Object.keys(Ea),type:"string",schemaType:"string",$data:!0,error:$O,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 wO.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,Ot._)`${m}[${c.schemaCode}]`);t.fail$data((0,Ot.or)((0,Ot._)`typeof ${p} != "object"`,(0,Ot._)`${p} instanceof RegExp`,(0,Ot._)`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,Ot._)`${i.code.formats}${(0,Ot.getProperty)(m)}`:void 0});t.fail$data(d(f))}function d(m){return(0,Ot._)`${m}.compare(${r}, ${n}) ${Ea[o].fail} 0`}},dependencies:["format"]};var kO=t=>(t.addKeyword(mo.formatLimitDefinition),t);mo.default=kO});var pv=z((Ps,fv)=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var ho=cv(),SO=uv(),rp=G(),lv=new rp.Name("fullFormats"),TO=new rp.Name("fastFormats"),np=(t,e={keywords:!0})=>{if(Array.isArray(e))return dv(t,e,ho.fullFormats,lv),t;let[r,n]=e.mode==="fast"?[ho.fastFormats,TO]:[ho.fullFormats,lv],o=e.formats||ho.formatNames;return dv(t,o,r,n),e.keywords&&(0,SO.default)(t),t};np.get=(t,e="full")=>{let n=(e==="fast"?ho.fastFormats:ho.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function dv(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,rp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}fv.exports=Ps=np;Object.defineProperty(Ps,"__esModule",{value:!0});Ps.default=np});var yx={};To(yx,{findEmbeddingModel:()=>gx,ollamaUrl:()=>Ep,semanticRerank:()=>lI});import{createHash as QA}from"node:crypto";import{existsSync as eI,mkdirSync as tI,readFileSync as rI,writeFileSync as nI}from"node:fs";import{homedir as oI}from"node:os";import{join as Tp}from"node:path";function Ep(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 hx(t,e,r=6e4){let n=await fetch(Ep()+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 gx(t){let r=((await hx("/api/tags",void 0,2e3)).models??[]).map(n=>String(n.name));return t?r.find(n=>n===t||n.startsWith(t+":"))??t:r.find(n=>sI.test(n))}function Ba(){return Tp(process.env.XDG_CACHE_HOME??Tp(oI(),".cache"),"context-doctor","embeddings.json")}function iI(){try{return eI(Ba())?JSON.parse(rI(Ba(),"utf8")):{}}catch{return{}}}function aI(t){try{let e=Object.keys(t);if(e.length>mx)for(let r of e.slice(0,e.length-mx))delete t[r];tI(Tp(Ba(),".."),{recursive:!0}),nI(Ba(),JSON.stringify(t))}catch{}}async function cI(t,e){let r=[];for(let n=0;n<e.length;n+=px){let o=await hx("/api/embed",{model:t,input:e.slice(n,n+px),truncate:!0});r.push(...o.embeddings)}return r}function uI(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 lI(t,e,r={}){let n;try{n=await gx(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${Ep()} (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=iI(),s=f=>QA("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 cI(n,[e,...a]);u=f[0],a.forEach((h,g)=>o[s(h)]=f[g+1]),c=i.map(h=>o[s(h)])}catch(f){return{used:!1,model:n,note:`semantic ranking off: ${n} failed (${f.message}); keyword ranking only`}}a.length&&aI(o);let l=60,d=new Map([...t].filter(f=>f.score>0).sort((f,h)=>h.score-f.score).map((f,h)=>[f,h])),m=t.map((f,h)=>({c:f,s:uI(u,c[h])})).sort((f,h)=>h.s-f.s),p=new Map(m.map((f,h)=>[f.c,h]));for(let f of t){let h=d.get(f);f.score=(h===void 0?0:1/(l+h))+1/(l+p.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var sI,px,mx,_x=Q(()=>{"use strict";sI=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,px=64,mx=5e4});var mb,hb=Q(()=>{mb="x-hono-already-sent"});var gb,yb=Q(()=>{gb=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{STATUS_CODES as aF,ServerResponse as HN,createServer as cF}from"node:http";import{Http2ServerRequest as mr,constants as BN}from"node:http2";import{Readable as _b}from"node:stream";async function gM(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Ib(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 Sb(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:Ib(t.getReader(),e)}var Mt,VN,JN,oc,vb,xb,em,Eb,tm,zb,WN,GN,KN,Jp,XN,YN,QN,ko,Rb,eM,tM,Bp,Wp,Pb,rm,bb,ic,wb,rM,qr,fr,So,Zs,Cb,Ob,Ms,Gp,Kp,Lr,sc,hr,$b,js,ac,Ds,nM,oM,sM,iM,aM,cM,uM,nm,lM,kb,dM,Yt,fM,Rn,Xp,$o,pr,cc,Xt,pM,mM,hM,Yp,uc,Tb,yM,_M,Nb,vM,xM,bM,Mb,lc,Qp,jb,Vp,Zb,Db,wM,om,$M,kM,SM,TM,EM,fF,Lb=Q(()=>{hb();yb();Mt=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},VN=new Set(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","server","user-agent"]),JN=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,oc=t=>t===9||t===10||t===13||t===32,vb=t=>{if(!oc(t.charCodeAt(0))&&!oc(t.charCodeAt(t.length-1)))return t;let e=0,r=t.length;for(;e<r&&oc(t.charCodeAt(e));)e++;for(;r>e&&oc(t.charCodeAt(r-1));)r--;return t.slice(e,r)},xb=/[\0\r\n]/,em=globalThis.Headers,Eb=(t,e=em)=>{let r=new e;for(let n=0;n<t.length;n+=2){let o=t[n];o.startsWith(":")||r.append(o,t[n+1])}return r},tm=class{#e;#t;#n;#o;constructor(t){this.#e=t,t instanceof mr&&(this.#t=t.rawHeaders.slice())}get#s(){return this.#t??=this.#e.rawHeaders.slice()}get#r(){return this.#n||(this.#n=Eb(this.#s),this.#t=void 0),this.#n}#i(t){if(typeof t=="string"){if(!JN.test(t))throw new TypeError(`Invalid header name: ${t}`);return t.toLowerCase()}}#a(t){let e=this.#e instanceof mr?void 0:this.#e.headers;if(!e||VN.has(t)||t==="set-cookie"||t==="__proto__")return;if(!Object.hasOwn(e,t))return null;let r=e[t];if(typeof r=="string"){let n=vb(r);return xb.test(n)?void 0:n}}#c(t,e){let r=e==="cookie"?"; ":", ",n=null;for(let o=0;o<t.length;o+=2){let s=t[o];if(s.length===e.length&&s.toLowerCase()===e){let i=vb(t[o+1]);if(xb.test(i)){this.#o=!0;return}n=n===null?i:n+r+i}}return n}append(t,e){this.#r.append(t,e)}delete(t){this.#r.delete(t)}get(t){let e=this.#i(t);if(e&&!this.#n&&!this.#o){let r=this.#a(e);if(r!==void 0)return r;let n=this.#c(this.#s,e);if(n!==void 0)return n}return this.#r.get(t)}has(t){let e=this.#i(t);if(e&&!this.#n&&!this.#o){let r=this.#a(e);if(r!==void 0)return r!==null;let n=this.#c(this.#s,e);if(n!==void 0)return n!==null}return this.#r.has(t)}set(t,e){this.#r.set(t,e)}getSetCookie(){return this.#r.getSetCookie()}keys(){return this.#r.keys()}values(){return this.#r.values()}entries(){return this.#r.entries()}forEach(t,e){this.#r.forEach((r,n)=>{t.call(e,r,n,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(tm.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Headers (lightweight) ${r(Object.fromEntries(this),{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(tm.prototype,em.prototype);zb=t=>globalThis.Headers===em?new tm(t):Eb(t.rawHeaders,globalThis.Headers),WN=/^\/[!#$&-;=?-\[\]_a-z~]*$/,GN=/\/\.\.?(?:[/?#]|$)/,KN=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,Jp=t=>{let e=t.indexOf("\\");if(e!==-1){let r=t.indexOf("?");if(r===-1||e<r)throw new Mt("Backslash in request path")}},XN=(t,e,r)=>{let n=`${t}://${e}${r}`;if(KN.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Mt("Invalid URL");return!WN.test(r)||GN.test(r)?(Jp(r),new URL(n).href):n}else{Jp(r);let o=new URL(n);if(o.hostname.length!==e.length&&o.hostname!==(e.includes(":")?e.replace(/:\d+$/,""):e).toLowerCase())throw new Mt("Invalid host header");return o.href}},YN=t=>t instanceof Mt?t:new Mt(t.message,{cause:t}),QN=global.Request,ko=class extends QN{constructor(t,e){if(typeof t=="object"&&qr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[hr]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[qr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Rb=Symbol("wrapBodyStream"),eM=new Set(["latin1","binary","hex","base64","base64url"]),tM=t=>t===null||eM.has(t),Bp=Symbol("bodyBufferedBeforeDisconnect"),Wp=Symbol("bodyBufferedLengthBeforeDisconnect"),Pb=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),rm=t=>!(t instanceof mr)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&tM(t.readableEncoding),bb=t=>{if(t.readableDidRead||!rm(t))return;let e=t;e[Wp]??=t.readableLength},ic=(t,e)=>{if(t.readableDidRead&&!e||!rm(t))return;let r=t;if(r[Bp]!==void 0)return r[Bp];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Wp]!==void 0&&t.readableLength!==r[Wp])n=ac();else{let s=e??[],i=t.read();i!==null&&s.push(Pb(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=ac())}}return r[Bp]=n,n},wb=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},rM=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new ko(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[Rb]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=ic(n);if(l!==void 0){wb(a,l);return}}i||=_b.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=ic(n);i!==void 0?s.body=new ReadableStream({start(a){wb(a,i)}}):s.body=_b.toWeb(n)}return new ko(e,s)},qr=Symbol("getRequestCache"),fr=Symbol("requestCache"),So=Symbol("incomingKey"),Zs=Symbol("urlKey"),Cb=Symbol("methodKey"),Ob=Symbol("headersKey"),Ms=Symbol("abortControllerKey"),Gp=Symbol("getAbortController"),Kp=Symbol("abortRequest"),Lr=Symbol("bodyBuffer"),sc=Symbol("bodyReadPromise"),hr=Symbol("bodyConsumedDirectly"),$b=Symbol("bodyLockReader"),js=Symbol("abortReason"),ac=()=>new TypeError("Body is unusable"),Ds=()=>Promise.reject(ac()),nM=new TextDecoder,oM=t=>{if(t[hr])return Ds();t[hr]=!0},sM=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),iM=t=>(t[Ob]||=zb(t[So])).get("content-type")||"",aM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,cM=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}},uM=t=>{if(!aM.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.`)},nm=(t,e,r)=>{if(t[hr])return Ds();let n=t.method;if(n==="GET"||n==="HEAD")return t[qr]()[e]();let o=uM(n);if(o)return Promise.reject(o);if(t[fr]&&n!=="TRACE")return t[fr][e]();let s=oM(t);if(s)return s;let i=lM(t);if(i){let a=Promise.resolve(r(i,t));return t[Lr]=void 0,a}return dM(t).then(a=>{let c=r(a,t);return t[Lr]=void 0,c})},lM=t=>{let e=t[So];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},kb=(t,e)=>{if(e.errored)return e.errored;let r=t[js];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},dM=t=>{if(t[Lr])return Promise.resolve(t[Lr]);if(t[sc])return t[sc];let e=t[So];if(e.readableDidRead)return Ds();let r=ic(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[Lr]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=h=>{a||(a=!0,f(),h())},u=h=>{let g=e.errored??h;return!rm(e)||g&&g.code!=="ECONNRESET"?!1:(c(()=>{let _=ic(e,i);_ instanceof Error?s(_):_===void 0?s(h??kb(t,e)):(t[Lr]=_,o(_))}),!0)},l=h=>{i.push(Pb(h,e.readableEncoding))},d=()=>{c(()=>{let h=i.length===1?i[0]:Buffer.concat(i);t[Lr]=h,o(h)})},m=h=>{u(h)||c(()=>{s(h)})},p=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(kb(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",m),e.off("close",p),t[sc]=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[sc]=n,n},Yt={get method(){return this[Cb]},get url(){return this[Zs]},get headers(){return this[Ob]||=zb(this[So])},[Kp](t){this[js]===void 0&&(this[js]=t);let e=this[Ms];e&&!e.signal.aborted&&e.abort(t)},[Gp](){return this[Ms]||=new AbortController,this[js]!==void 0&&!this[Ms].signal.aborted&&this[Ms].abort(this[js]),this[Ms]},[qr](){let t=this[Gp]();if(this[fr])return this[fr];let e=this.method;if(this[hr]&&!(e==="GET"||e==="HEAD")){this[Lr]=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 ko(this[Zs],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[fr]=n}return this[fr]=rM(this.method,this[Zs],this.headers,this[So],t)},get body(){if(!this[hr])return this[qr]().body;let t=this[qr]();return!this[$b]&&t.body&&(this[$b]=t.body.getReader()),t.body},get bodyUsed(){return this[hr]?!0:this[fr]?this[fr].bodyUsed:!1}};Object.defineProperty(Yt,"signal",{get(){return this[Gp]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(Yt,t,{get(){return this[qr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(Yt,t,{value:function(){if(this[hr]){if(t==="clone")throw ac();return Ds()}return this[qr]()[t]()}})});Object.defineProperty(Yt,"text",{value:function(){return nm(this,"text",t=>nM.decode(t))}});Object.defineProperty(Yt,"arrayBuffer",{value:function(){return nm(this,"arrayBuffer",t=>sM(t))}});Object.defineProperty(Yt,"blob",{value:function(){return nm(this,"blob",(t,e)=>{let r=iM(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(Yt,"json",{value:function(){return this[hr]?Ds():this.text().then(JSON.parse)}});Object.defineProperty(Yt,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[fr]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Yt,ko.prototype);fM=(t,e)=>{let r=Object.create(Yt);r[So]=t,r[Cb]=cM(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof mr)throw new Mt("Absolute URL for :path is not allowed in HTTP/2");try{Jp(n),r[Zs]=new URL(n).href}catch(i){throw new Mt("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof mr?t.authority:t.headers.host)||e;if(!o)throw new Mt("Missing host header");let s;if(t instanceof mr){if(s=t.scheme,!(s==="http"||s==="https"))throw new Mt("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[Zs]=XN(s,o,n)}catch(i){throw i instanceof Mt?i:new Mt("Invalid URL",{cause:i})}return r},Rn="text/plain; charset=UTF-8",Xp=Symbol("responseCache"),$o=Symbol("getResponseCache"),pr=Symbol("cache"),cc=global.Response,Xt=class Ab{#e;#t;[$o](){let e=this[pr],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[pr],this[Xp]||=new cc(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 cc){let o=r[Xp];if(o){this.#t=o,this[$o]();return}this.#t=r instanceof Ab?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[pr]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[pr];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Rn}))),e[2]):this[$o]().headers}get status(){return this[pr]?.[0]??this[$o]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Xt.prototype,t,{get(){return this[$o]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Xt.prototype,t,{value:function(){return this[$o]()[t]()}})});Object.defineProperty(Xt.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[Xp]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Xt,cc);Object.setPrototypeOf(Xt.prototype,cc.prototype);pM=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,mM=t=>t instanceof URL?t.href:pM.test(t)?t:new URL(t).href,hM=new Set([301,302,303,307,308]);Object.defineProperty(Xt,"redirect",{value:function(e,r=302){if(!hM.has(r))throw new RangeError("Invalid status code");return new Xt(null,{status:r,headers:{location:mM(e)}})},writable:!0,configurable:!0});Object.defineProperty(Xt,"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 Xt(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});Yp=(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},uc=Symbol("outgoingEnded"),Tb=Symbol("incomingDraining"),yM=500,_M=64*1024*1024,Nb=t=>{let e=t;if(t.destroyed||e[Tb])return;if(e[Tb]=!0,t instanceof mr){try{t.stream?.close?.(BN.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,yM);s.unref?.();let i=a=>{r+=a.length,r>_M&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},vM=(t,e,r,n)=>()=>{e.errored?(bb(e),t[Kp](e.errored.toString())):(!r.writableFinished||e instanceof mr&&e.aborted)&&(bb(e),t[Kp]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{Nb(e)})})},xM=t=>{if(!(pr in t))return!1;let e=t[pr][1];return e===null||typeof e=="string"||e instanceof Uint8Array},bM=()=>new Response(null,{status:400}),Mb=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),lc=(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 instanceof HN&&(e._contentLength=null),e.writeHead(500,{"Content-Type":"text/plain"})),e.end(`Error: ${r.message}`),e.destroy(r))},Qp=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},jb=(t,e,r)=>{let n=t;return n._contentLength===null&&n._hasBody&&n.useChunkedEncodingByDefault&&!n._removedContLen&&e>=200&&e!==204&&e!==304&&!t.hasHeader("content-length")&&!t.hasHeader("transfer-encoding")&&!t.hasHeader("trailer")?(n._contentLength=r,!0):!1},Vp=(t,e,r)=>{jb(t,e,r)?t.writeHead(e,{"Content-Type":Rn}):t.writeHead(e,{"Content-Type":Rn,"Content-Length":r})},Zb=async(t,e)=>{let[r,n,o]=t[pr];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(Vp(e,r,Buffer.byteLength(n)),e.end(n)):n instanceof Uint8Array?(Vp(e,r,n.byteLength),e.end(n)):n instanceof Blob?(Vp(e,r,n.size),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":Rn}),Qp(e),await Sb(n,e)?.catch(c=>lc(c,e))),e[uc]?.();return}let s=!1,i=!1,a=!0;if(o instanceof Headers)s=o.has("content-length"),o=Yp(o,n===null?void 0:Rn);else if(Array.isArray(o)){let c=new Headers(o);s=c.has("content-length"),o=Yp(c,n===null?void 0:Rn)}else{i=!0;for(let c in o){if(c.length===14&&c.toLowerCase()==="content-length"){s=!0;break}(c.length===17&&c.toLowerCase()==="transfer-encoding"||c.length===7&&c.toLowerCase()==="trailer")&&(a=!1)}}if(!s){let c;typeof n=="string"?c=Buffer.byteLength(n):n instanceof Uint8Array?c=n.byteLength:n instanceof Blob&&(c=n.size),c!==void 0&&(!i||!a||!jb(e,r,c))&&(i&&(o={...o}),o["Content-Length"]=c)}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())):(Qp(e),await Sb(n,e)?.catch(c=>lc(c,e))),e[uc]?.()},Db=t=>typeof t.then=="function",wM=async(t,e,r={})=>{if(Db(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(Mb);if(pr in t)return Zb(t,e);let n=Yp(t.headers,t.body===null?void 0:Rn);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 gM(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&&Qp(e),await Ib(o,e,a))}else n[mb]||(e.writeHead(t.status,n),e.end());e[uc]?.()},om=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==ko&&(Object.defineProperty(global,"Request",{value:ko}),Object.defineProperty(global,"Response",{value:Xt})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",vM(i,n,o,a)))};try{if(i=fM(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[Rb]=!0,n instanceof mr&&(o[uc]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!Db(s)&&xM(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||Nb(n)}),Zb(s,o);u()}catch(l){if(s)return lc(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:YN(l)),!s)return}else i?s=Mb(l):s=bM()}try{return await wM(s,o,e)}catch(l){return lc(l,o)}}},$M=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??""}},kM=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}},SM=()=>Symbol("connection"),TM=Symbol("CONNECTION_SYMBOL_KEY"),EM=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),fF=gb(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[EM];if(!o||!n.incoming)return new Response(null,{status:500});let s=SM();return n[TM]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,m)=>{a.push([d,m])};i.on("message",c);let u={binaryType:"arraybuffer",close(d,m){i.close(d,m)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,m){i.send(d,{compress:m?.compress})},url:new URL(t.req.url)};try{e?.onOpen?.(new Event("open"),u)}catch(d){(r?.onError??console.error)(d)}let l=(d,m)=>{let p=Array.isArray(d)?d:[d];for(let f of p)try{e?.onMessage?.(new MessageEvent("message",{data:m?f instanceof ArrayBuffer?f:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength):typeof f=="string"?f:Buffer.from(f).toString("utf-8")}),u)}catch(h){(r?.onError??console.error)(h)}};i.off("message",c);for(let d of a)l(...d);i.on("message",(d,m)=>{l(d,m)}),i.on("close",(d,m)=>{try{e?.onClose?.(new $M("close",{code:d,reason:m.toString()}),u)}catch(p){(r?.onError??console.error)(p)}}),i.on("error",d=>{try{e?.onError?.(new kM("error",{error:d}),u)}catch(m){(r?.onError??console.error)(m)}})})(),new Response})});var Hb=z(sm=>{"use strict";var qb=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,zM=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Ub=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,RM=/\\([\u000b\u0020-\u00ff])/g,PM=/([\\"])/g,Fb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;sm.format=CM;sm.parse=OM;function CM(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],!Ub.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+IM(e[o])}return n}function OM(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?AM(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 NM(n.toLowerCase());if(r!==-1){var s,i,a;for(qb.lastIndex=r;i=qb.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(RM,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function AM(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 IM(t){var e=String(t);if(Ub.test(e))return e;if(e.length>0&&!zM.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(PM,"\\$1")+'"'}function NM(t){this.parameters=Object.create(null),this.type=t}});function MM(t){if(t)try{return Bb.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function Vb(t){return t==="application/json"?!0:MM(t)==="application/json"}var Bb,Jb=Q(()=>{Bb=mc(Hb(),1)});function Wb(t){return`Payload Too Large: Request body must not exceed ${t} bytes`}function Gb(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 Kb(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=Q(()=>{});function Yb(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var Qb=Q(()=>{});var dc,ew=Q(()=>{Jb();Xb();Qb();Sr();dc=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=Gb(e.maxRequestBodySize)}startKeepAlive(e,r){if(this._closed)return;let n=Yb(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(!Ab(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 jb(e,this._maxRequestBodySize);if(v.tooLarge){let y=Nb(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=>Fo.parse(v)):a=[Fo.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(Ml);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(tr)){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=>Ml(v)),m=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??cg;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let y of a)tr(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)tr(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;tr(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)tr(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&&!Fn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Fn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Fn.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((rr(e)||Un(e))&&(n=e.id),n===void 0){if(rr(e)||Un(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(rr(e)||Un(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 Fb={};$o(Fb,{StreamableHTTPServerTransport:()=>Yp});var Yp,Ub=X(()=>{Eb();qb();Yp=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new ac(e),this._requestListener=Kp(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 Kp(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 D={};$o(D,{BRAND:()=>Sw,DIRTY:()=>qr,EMPTY_PATH:()=>nw,INVALID:()=>L,NEVER:()=>c$,OK:()=>je,ParseStatus:()=>Pe,Schema:()=>J,ZodAny:()=>hr,ZodArray:()=>Qt,ZodBigInt:()=>Ur,ZodBoolean:()=>Hr,ZodBranded:()=>So,ZodCatch:()=>tn,ZodDate:()=>Br,ZodDefault:()=>en,ZodDiscriminatedUnion:()=>Ls,ZodEffects:()=>dt,ZodEnum:()=>Yr,ZodError:()=>Ge,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Fs,ZodIntersection:()=>Kr,ZodIssueCode:()=>k,ZodLazy:()=>Gr,ZodLiteral:()=>Xr,ZodMap:()=>Cn,ZodNaN:()=>On,ZodNativeEnum:()=>Qr,ZodNever:()=>wt,ZodNull:()=>Jr,ZodNullable:()=>Mt,ZodNumber:()=>Fr,ZodObject:()=>Ye,ZodOptional:()=>Xe,ZodParsedType:()=>P,ZodPipeline:()=>To,ZodPromise:()=>gr,ZodReadonly:()=>rn,ZodRecord:()=>qs,ZodSchema:()=>J,ZodSet:()=>An,ZodString:()=>mr,ZodSymbol:()=>Pn,ZodTransformer:()=>dt,ZodTuple:()=>Nt,ZodType:()=>J,ZodUndefined:()=>Vr,ZodUnion:()=>Wr,ZodUnknown:()=>Yt,ZodVoid:()=>In,addIssueToContext:()=>E,any:()=>Ow,array:()=>Zw,bigint:()=>Rw,boolean:()=>dm,coerce:()=>a$,custom:()=>cm,date:()=>Pw,datetimeRegex:()=>im,defaultErrorMap:()=>Gt,discriminatedUnion:()=>qw,effect:()=>Qw,enum:()=>Gw,function:()=>Jw,getErrorMap:()=>En,getParsedType:()=>Ot,instanceof:()=>Ew,intersection:()=>Fw,isAborted:()=>Zs,isAsync:()=>zn,isDirty:()=>Ds,isValid:()=>pr,late:()=>Tw,lazy:()=>Ww,literal:()=>Kw,makeIssue:()=>ko,map:()=>Bw,nan:()=>zw,nativeEnum:()=>Xw,never:()=>Mw,null:()=>Aw,nullable:()=>t$,number:()=>lm,object:()=>mc,objectUtil:()=>dc,oboolean:()=>i$,onumber:()=>s$,optional:()=>e$,ostring:()=>o$,pipeline:()=>n$,preprocess:()=>r$,promise:()=>Yw,quotelessJson:()=>ew,record:()=>Hw,set:()=>Vw,setErrorMap:()=>rw,strictObject:()=>Dw,string:()=>um,symbol:()=>Iw,transformer:()=>Qw,tuple:()=>Uw,undefined:()=>Cw,union:()=>Lw,unknown:()=>Nw,util:()=>Y,void:()=>jw});var Y;(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})(Y||(Y={}));var dc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(dc||(dc={}));var P=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ot=t=>{switch(typeof t){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(t)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(t)?P.array:t===null?P.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?P.promise:typeof Map<"u"&&t instanceof Map?P.map:typeof Set<"u"&&t instanceof Set?P.set:typeof Date<"u"&&t instanceof Date?P.date:P.object;default:return P.unknown}};var k=Y.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"]),ew=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ge=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,Y.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()}};Ge.create=t=>new Ge(t);var tw=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===P.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Y.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${Y.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}"`:Y.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,Y.assertNever(t)}return{message:r}},Gt=tw;var tm=Gt;function rw(t){tm=t}function En(){return tm}var ko=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}},nw=[];function E(t,e){let r=En(),n=ko({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Gt?void 0:Gt].filter(o=>!!o)});t.common.issues.push(n)}var Pe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return L;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 L;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}}},L=Object.freeze({status:"aborted"}),qr=t=>({status:"dirty",value:t}),je=t=>({status:"valid",value:t}),Zs=t=>t.status==="aborted",Ds=t=>t.status==="dirty",pr=t=>t.status==="valid",zn=t=>typeof Promise<"u"&&t instanceof Promise;var M;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(M||(M={}));var lt=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}},rm=(t,e)=>{if(pr(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 Ge(t.common.issues);return this._error=r,this._error}}};function B(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 J=class{get description(){return this._def.description}_getType(e){return Ot(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Pe,ctx:{common:e.parent.common,data:e.data,parsedType:Ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(zn(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:Ot(e)},o=this._parseSync({data:e,path:n.path,parent:n});return rm(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ot(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return pr(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=>pr(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:Ot(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(zn(o)?o:Promise.resolve(o));return rm(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 dt({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 Xe.create(this,this._def)}nullable(){return Mt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qt.create(this)}promise(){return gr.create(this,this._def)}or(e){return Wr.create([this,e],this._def)}and(e){return Kr.create(this,e,this._def)}transform(e){return new dt({...B(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new en({...B(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new So({typeName:S.ZodBranded,type:this,...B(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new tn({...B(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 To.create(this,e)}readonly(){return rn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ow=/^c[^\s-]{8,}$/i,sw=/^[0-9a-z]+$/,iw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,aw=/^[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,cw=/^[a-z0-9_-]{21}$/i,uw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,lw=/^[-+]?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)?)??$/,dw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,fw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",fc,pw=/^(?:(?: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])$/,mw=/^(?:(?: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])$/,hw=/^(([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]))$/,gw=/^(([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])$/,yw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_w=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,om="((\\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])))",vw=new RegExp(`^${om}$`);function sm(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 xw(t){return new RegExp(`^${sm(t)}$`)}function im(t){let e=`${om}T${sm(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 bw(t,e){return!!((e==="v4"||!e)&&pw.test(t)||(e==="v6"||!e)&&hw.test(t))}function ww(t,e){if(!uw.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 $w(t,e){return!!((e==="v4"||!e)&&mw.test(t)||(e==="v6"||!e)&&gw.test(t))}var mr=class t extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.string){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.string,received:s.parsedType}),L}let n=new Pe,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")dw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")fc||(fc=new RegExp(fw,"u")),fc.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")aw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")cw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")ow.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")sw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")iw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),E(o,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?im(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?vw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?xw(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?lw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?bw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?ww(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?$w(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?yw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?_w.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):Y.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,...M.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...M.errToObj(e)})}url(e){return this._addCheck({kind:"url",...M.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...M.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...M.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...M.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...M.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...M.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...M.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...M.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...M.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...M.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...M.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...M.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,...M.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,...M.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...M.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...M.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...M.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...M.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...M.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...M.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...M.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...M.errToObj(r)})}nonempty(e){return this.min(1,M.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}};mr.create=t=>new mr({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...B(t)});function kw(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 Fr=class t extends J{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)!==P.number){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.number,received:s.parsedType}),L}let n,o=new Pe;for(let s of this._def.checks)s.kind==="int"?Y.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?kw(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_finite,message:s.message}),o.dirty()):Y.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,M.toString(r))}gt(e,r){return this.setLimit("min",e,!1,M.toString(r))}lte(e,r){return this.setLimit("max",e,!0,M.toString(r))}lt(e,r){return this.setLimit("max",e,!1,M.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:M.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:M.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:M.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:M.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.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"&&Y.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)}};Fr.create=t=>new Fr({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...B(t)});var Ur=class t extends J{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)!==P.bigint)return this._getInvalidInput(e);let n,o=new Pe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):Y.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:P.bigint,received:r.parsedType}),L}gte(e,r){return this.setLimit("min",e,!0,M.toString(r))}gt(e,r){return this.setLimit("min",e,!1,M.toString(r))}lte(e,r){return this.setLimit("max",e,!0,M.toString(r))}lt(e,r){return this.setLimit("max",e,!1,M.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:M.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:M.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:M.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}};Ur.create=t=>new Ur({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...B(t)});var Hr=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.boolean){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.boolean,received:n.parsedType}),L}return je(e.data)}};Hr.create=t=>new Hr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...B(t)});var Br=class t extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.date){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.date,received:s.parsedType}),L}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_date}),L}let n=new Pe,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Y.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:M.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:M.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}};Br.create=t=>new Br({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...B(t)});var Pn=class extends J{_parse(e){if(this._getType(e)!==P.symbol){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.symbol,received:n.parsedType}),L}return je(e.data)}};Pn.create=t=>new Pn({typeName:S.ZodSymbol,...B(t)});var Vr=class extends J{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.undefined,received:n.parsedType}),L}return je(e.data)}};Vr.create=t=>new Vr({typeName:S.ZodUndefined,...B(t)});var Jr=class extends J{_parse(e){if(this._getType(e)!==P.null){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.null,received:n.parsedType}),L}return je(e.data)}};Jr.create=t=>new Jr({typeName:S.ZodNull,...B(t)});var hr=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return je(e.data)}};hr.create=t=>new hr({typeName:S.ZodAny,...B(t)});var Yt=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return je(e.data)}};Yt.create=t=>new Yt({typeName:S.ZodUnknown,...B(t)});var wt=class extends J{_parse(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:P.never,received:r.parsedType}),L}};wt.create=t=>new wt({typeName:S.ZodNever,...B(t)});var In=class extends J{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.void,received:n.parsedType}),L}return je(e.data)}};In.create=t=>new In({typeName:S.ZodVoid,...B(t)});var Qt=class t extends J{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==P.array)return E(r,{code:k.invalid_type,expected:P.array,received:r.parsedType}),L;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(E(r,{code:i?k.too_big:k.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(E(r,{code:k.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(E(r,{code:k.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new lt(r,i,r.path,a)))).then(i=>Pe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new lt(r,i,r.path,a)));return Pe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:M.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:M.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:M.toString(r)}})}nonempty(e){return this.min(1,e)}};Qt.create=(t,e)=>new Qt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...B(e)});function Rn(t){if(t instanceof Ye){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Xe.create(Rn(n))}return new Ye({...t._def,shape:()=>e})}else return t instanceof Qt?new Qt({...t._def,type:Rn(t.element)}):t instanceof Xe?Xe.create(Rn(t.unwrap())):t instanceof Mt?Mt.create(Rn(t.unwrap())):t instanceof Nt?Nt.create(t.items.map(e=>Rn(e))):t}var Ye=class t extends J{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=Y.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==P.object){let u=this._getOrReturnCtx(e);return E(u,{code:k.invalid_type,expected:P.object,received:u.parsedType}),L}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof wt&&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 lt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof wt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(E(o,{code:k.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new lt(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=>Pe.mergeObjectSync(n,u)):Pe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return M.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:M.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 Y.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 Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Rn(this)}partial(e){let r={};for(let n of Y.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 Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Xe;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return am(Y.objectKeys(this.shape))}};Ye.create=(t,e)=>new Ye({shape:()=>t,unknownKeys:"strip",catchall:wt.create(),typeName:S.ZodObject,...B(e)});Ye.strictCreate=(t,e)=>new Ye({shape:()=>t,unknownKeys:"strict",catchall:wt.create(),typeName:S.ZodObject,...B(e)});Ye.lazycreate=(t,e)=>new Ye({shape:t,unknownKeys:"strip",catchall:wt.create(),typeName:S.ZodObject,...B(e)});var Wr=class extends J{_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 Ge(a.ctx.common.issues));return E(r,{code:k.invalid_union,unionErrors:i}),L}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 Ge(c));return E(r,{code:k.invalid_union,unionErrors:a}),L}}get options(){return this._def.options}};Wr.create=(t,e)=>new Wr({options:t,typeName:S.ZodUnion,...B(e)});var Xt=t=>t instanceof Gr?Xt(t.schema):t instanceof dt?Xt(t.innerType()):t instanceof Xr?[t.value]:t instanceof Yr?t.options:t instanceof Qr?Y.objectValues(t.enum):t instanceof en?Xt(t._def.innerType):t instanceof Vr?[void 0]:t instanceof Jr?[null]:t instanceof Xe?[void 0,...Xt(t.unwrap())]:t instanceof Mt?[null,...Xt(t.unwrap())]:t instanceof So||t instanceof rn?Xt(t.unwrap()):t instanceof tn?Xt(t._def.innerType):[],Ls=class t extends J{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.object)return E(r,{code:k.invalid_type,expected:P.object,received:r.parsedType}),L;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(E(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),L)}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=Xt(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,...B(n)})}};function pc(t,e){let r=Ot(t),n=Ot(e);if(t===e)return{valid:!0,data:t};if(r===P.object&&n===P.object){let o=Y.objectKeys(e),s=Y.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=pc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===P.array&&n===P.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=pc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===P.date&&n===P.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Kr=class extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Zs(s)||Zs(i))return L;let a=pc(s.value,i.value);return a.valid?((Ds(s)||Ds(i))&&r.dirty(),{status:r.value,value:a.data}):(E(n,{code:k.invalid_intersection_types}),L)};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}))}};Kr.create=(t,e,r)=>new Kr({left:t,right:e,typeName:S.ZodIntersection,...B(r)});var Nt=class t extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.array)return E(n,{code:k.invalid_type,expected:P.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return E(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&(E(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new lt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Pe.mergeArray(r,i)):Pe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Nt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nt({items:t,typeName:S.ZodTuple,rest:null,...B(e)})};var qs=class t extends J{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!==P.object)return E(n,{code:k.invalid_type,expected:P.object,received:n.parsedType}),L;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new lt(n,a,n.path,a)),value:i._parse(new lt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Pe.mergeObjectAsync(r,o):Pe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof J?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...B(n)}):new t({keyType:mr.create(),valueType:e,typeName:S.ZodRecord,...B(r)})}},Cn=class extends J{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!==P.map)return E(n,{code:k.invalid_type,expected:P.map,received:n.parsedType}),L;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new lt(n,a,n.path,[u,"key"])),value:s._parse(new lt(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 L;(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 L;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Cn.create=(t,e,r)=>new Cn({valueType:e,keyType:t,typeName:S.ZodMap,...B(r)});var An=class t extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.set)return E(n,{code:k.invalid_type,expected:P.set,received:n.parsedType}),L;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(E(n,{code:k.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(E(n,{code:k.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return L;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 lt(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:M.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:M.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};An.create=(t,e)=>new An({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...B(e)});var Fs=class t extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.function)return E(r,{code:k.invalid_type,expected:P.function,received:r.parsedType}),L;function n(a,c){return ko({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,En(),Gt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return ko({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,En(),Gt].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 gr){let a=this;return je(async function(...c){let u=new Ge([]),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 je(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ge([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ge([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:Nt.create(e).rest(Yt.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||Nt.create([]).rest(Yt.create()),returns:r||Yt.create(),typeName:S.ZodFunction,...B(n)})}},Gr=class extends J{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})}};Gr.create=(t,e)=>new Gr({getter:t,typeName:S.ZodLazy,...B(e)});var Xr=class extends J{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return E(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};Xr.create=(t,e)=>new Xr({value:t,typeName:S.ZodLiteral,...B(e)});function am(t,e){return new Yr({values:t,typeName:S.ZodEnum,...B(e)})}var Yr=class t extends J{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{expected:Y.joinValues(n),received:r.parsedType,code:k.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{received:r.data,code:k.invalid_enum_value,options:n}),L}return je(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})}};Yr.create=am;var Qr=class extends J{_parse(e){let r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==P.string&&n.parsedType!==P.number){let o=Y.objectValues(r);return E(n,{expected:Y.joinValues(o),received:n.parsedType,code:k.invalid_type}),L}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=Y.objectValues(r);return E(n,{received:n.data,code:k.invalid_enum_value,options:o}),L}return je(e.data)}get enum(){return this._def.values}};Qr.create=(t,e)=>new Qr({values:t,typeName:S.ZodNativeEnum,...B(e)});var gr=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.promise&&r.common.async===!1)return E(r,{code:k.invalid_type,expected:P.promise,received:r.parsedType}),L;let n=r.parsedType===P.promise?r.data:Promise.resolve(r.data);return je(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};gr.create=(t,e)=>new gr({type:t,typeName:S.ZodPromise,...B(e)});var dt=class extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{E(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return L;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?L:c.status==="dirty"?qr(c.value):r.value==="dirty"?qr(c.value):c});{if(r.value==="aborted")return L;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?L:a.status==="dirty"?qr(a.value):r.value==="dirty"?qr(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"?L:(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"?L:(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(!pr(i))return L;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=>pr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):L);Y.assertNever(o)}};dt.create=(t,e,r)=>new dt({schema:t,typeName:S.ZodEffects,effect:e,...B(r)});dt.createWithPreprocess=(t,e,r)=>new dt({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...B(r)});var Xe=class extends J{_parse(e){return this._getType(e)===P.undefined?je(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Xe.create=(t,e)=>new Xe({innerType:t,typeName:S.ZodOptional,...B(e)});var Mt=class extends J{_parse(e){return this._getType(e)===P.null?je(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mt.create=(t,e)=>new Mt({innerType:t,typeName:S.ZodNullable,...B(e)});var en=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===P.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};en.create=(t,e)=>new en({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});var tn=class extends J{_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 zn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ge(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ge(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};tn.create=(t,e)=>new tn({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});var On=class extends J{_parse(e){if(this._getType(e)!==P.nan){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};On.create=t=>new On({typeName:S.ZodNaN,...B(t)});var Sw=Symbol("zod_brand"),So=class extends J{_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}},To=class t extends J{_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"?L:s.status==="dirty"?(r.dirty(),qr(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"?L: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})}},rn=class extends J{_parse(e){let r=this._def.innerType._parse(e),n=o=>(pr(o)&&(o.value=Object.freeze(o.value)),o);return zn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};rn.create=(t,e)=>new rn({innerType:t,typeName:S.ZodReadonly,...B(e)});function nm(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function cm(t,e={},r){return t?hr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=nm(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=nm(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):hr.create()}var Tw={object:Ye.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 Ew=(t,e={message:`Input not instance of ${t.name}`})=>cm(r=>r instanceof t,e),um=mr.create,lm=Fr.create,zw=On.create,Rw=Ur.create,dm=Hr.create,Pw=Br.create,Iw=Pn.create,Cw=Vr.create,Aw=Jr.create,Ow=hr.create,Nw=Yt.create,Mw=wt.create,jw=In.create,Zw=Qt.create,mc=Ye.create,Dw=Ye.strictCreate,Lw=Wr.create,qw=Ls.create,Fw=Kr.create,Uw=Nt.create,Hw=qs.create,Bw=Cn.create,Vw=An.create,Jw=Fs.create,Ww=Gr.create,Kw=Xr.create,Gw=Yr.create,Xw=Qr.create,Yw=gr.create,Qw=dt.create,e$=Xe.create,t$=Mt.create,r$=dt.createWithPreprocess,n$=To.create,o$=()=>um().optional(),s$=()=>lm().optional(),i$=()=>dm().optional(),a$={string:(t=>mr.create({...t,coerce:!0})),number:(t=>Fr.create({...t,coerce:!0})),boolean:(t=>Hr.create({...t,coerce:!0})),bigint:(t=>Ur.create({...t,coerce:!0})),date:(t=>Br.create({...t,coerce:!0}))};var c$=L;Ue();Ue();Ue();Ue();var yk=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");le.init(t,e),t.def=e,t.parse=(r,n)=>Rc(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>sn(t,r,n),t.parseAsync=async(r,n)=>Ic(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>an(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)=>at(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var _k=w("ZodMiniObject",(t,e)=>{ei.init(t,e),yk.init(t,e),ee.defineLazy(t,"shape",()=>e.shape)});function yl(t,e){let r={type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},...ee.normalizeParams(e)};return new _k(r)}Ue();ri();function Dt(t){return!!t._zod}function ln(t){let e=Object.values(t);if(e.length===0)return yl({});let r=e.every(Dt),n=e.every(o=>!Dt(o));if(r)return yl(t);if(n)return mc(t);throw new Error("Mixed Zod versions detected in object shape.")}function vr(t,e){return Dt(t)?sn(t,e):t.safeParse(e)}async function li(t,e){return Dt(t)?await an(t,e):await t.safeParseAsync(e)}function xr(t){if(!t)return;let e;if(Dt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Dn(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 ln(t)}}if(Dt(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 xk(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function di(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 ${xk(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 Ah(t){return t.description}function Oh(t){if(Dt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Ln(t){if(Dt(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}wr();function $r(t){return t==="completed"||t==="failed"||t==="cancelled"}var Sg=Symbol("Let zodToJsonSchema decide on which parser to use");var kg={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"},Tg=t=>typeof t=="string"?{...kg,name:t}:{...kg,...t};var Eg=t=>{let e=Tg(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 Jl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function re(t,e,r,n,o){t[e]=r,Jl(t,e,n,o)}var Mi=(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 $e(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Mi(e,t.currentPath):e.join("/")}}function zg(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=F(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&re(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&re(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(re(r,"minItems",t.exactLength.value,t.exactLength.message,e),re(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Rg(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?re(r,"minimum",n.value,n.message,e):re(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?re(r,"maximum",n.value,n.message,e):re(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",n.value,n.message,e));break;case"multipleOf":re(r,"multipleOf",n.value,n.message,e);break}return r}function Pg(){return{type:"boolean"}}function ji(t,e){return F(t.type._def,e)}var Ig=(t,e)=>F(t.innerType._def,e);function Wl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Wl(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 VT(t,e)}}var VT=(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":re(r,"minimum",n.value,n.message,e);break;case"max":re(r,"maximum",n.value,n.message,e);break}return r};function Cg(t,e){return{...F(t.innerType._def,e),default:t.defaultValue()}}function Ag(t,e){return e.effectStrategy==="input"?F(t.schema._def,e):$e(e)}function Og(t){return{type:"string",enum:Array.from(t.values)}}var JT=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Ng(t,e){let r=[F(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),F(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(JT(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 Mg(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 Kl,kt={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:()=>(Kl===void 0&&(Kl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Kl),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 Zi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":re(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":St(r,"email",n.message,e);break;case"format:idn-email":St(r,"idn-email",n.message,e);break;case"pattern:zod":Be(r,kt.email,n.message,e);break}break;case"url":St(r,"uri",n.message,e);break;case"uuid":St(r,"uuid",n.message,e);break;case"regex":Be(r,n.regex,n.message,e);break;case"cuid":Be(r,kt.cuid,n.message,e);break;case"cuid2":Be(r,kt.cuid2,n.message,e);break;case"startsWith":Be(r,RegExp(`^${Gl(n.value,e)}`),n.message,e);break;case"endsWith":Be(r,RegExp(`${Gl(n.value,e)}$`),n.message,e);break;case"datetime":St(r,"date-time",n.message,e);break;case"date":St(r,"date",n.message,e);break;case"time":St(r,"time",n.message,e);break;case"duration":St(r,"duration",n.message,e);break;case"length":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),re(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Be(r,RegExp(Gl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&St(r,"ipv4",n.message,e),n.version!=="v4"&&St(r,"ipv6",n.message,e);break}case"base64url":Be(r,kt.base64url,n.message,e);break;case"jwt":Be(r,kt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Be(r,kt.ipv4Cidr,n.message,e),n.version!=="v4"&&Be(r,kt.ipv6Cidr,n.message,e);break}case"emoji":Be(r,kt.emoji(),n.message,e);break;case"ulid":{Be(r,kt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{St(r,"binary",n.message,e);break}case"contentEncoding:base64":{re(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Be(r,kt.base64,n.message,e);break}}break}case"nanoid":Be(r,kt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Gl(t,e){return e.patternStrategy==="escape"?KT(t):t}var WT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function KT(t){let e="";for(let r=0;r<t.length;r++)WT.has(t[r])||(e+="\\"),e+=t[r];return e}function St(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}}})):re(t,"format",e,r,n)}function Be(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:jg(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):re(t,"pattern",jg(e,n),r,n)}function jg(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(!Vb(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 Kb(e,this._maxRequestBodySize);if(v.tooLarge){let y=Wb(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=>Bo.parse(v)):a=[Bo.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(Ll);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(or)){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=>Ll(v)),m=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??yg;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let y of a)or(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,h,g=new ReadableStream({start:v=>{f=v},cancel:()=>{h!==void 0&&clearInterval(h),this._streamMapping.get(l)?.controller===f&&this._streamMapping.delete(l)}}),_={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(_["mcp-session-id"]=this.sessionId);for(let v of a)or(v)&&(this._streamMapping.set(l,{controller:f,encoder:p,cleanup:()=>{h!==void 0&&clearInterval(h),this._streamMapping.delete(l);try{f.close()}catch{}}}),this._requestToStreamMapping.set(v.id,l));try{await this.writePrimingEvent(f,p,l,m);for(let v of a){let y,x;or(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)or(y)&&this._requestToStreamMapping.delete(y.id);throw v}return this._streamMapping.get(l)?.controller===f&&(h=this.startKeepAlive(f,p)),new Response(g,{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&&!Vn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Vn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Vn.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((sr(e)||Jn(e))&&(n=e.id),n===void 0){if(sr(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(sr(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 tw={};To(tw,{StreamableHTTPServerTransport:()=>am});var am,rw=Q(()=>{Lb();ew();am=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new dc(e),this._requestListener=om(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 om(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={};To(Z,{BRAND:()=>Zw,DIRTY:()=>Hr,EMPTY_PATH:()=>gw,INVALID:()=>L,NEVER:()=>b$,OK:()=>Ze,ParseStatus:()=>Oe,Schema:()=>W,ZodAny:()=>_r,ZodArray:()=>rr,ZodBigInt:()=>Vr,ZodBoolean:()=>Jr,ZodBranded:()=>zo,ZodCatch:()=>on,ZodDate:()=>Wr,ZodDefault:()=>nn,ZodDiscriminatedUnion:()=>Fs,ZodEffects:()=>ft,ZodEnum:()=>tn,ZodError:()=>Xe,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Bs,ZodIntersection:()=>Yr,ZodIssueCode:()=>k,ZodLazy:()=>Qr,ZodLiteral:()=>en,ZodMap:()=>Mn,ZodNaN:()=>Zn,ZodNativeEnum:()=>rn,ZodNever:()=>kt,ZodNull:()=>Kr,ZodNullable:()=>Lt,ZodNumber:()=>Br,ZodObject:()=>Qe,ZodOptional:()=>Ye,ZodParsedType:()=>P,ZodPipeline:()=>Ro,ZodPromise:()=>vr,ZodReadonly:()=>sn,ZodRecord:()=>Hs,ZodSchema:()=>W,ZodSet:()=>jn,ZodString:()=>yr,ZodSymbol:()=>In,ZodTransformer:()=>ft,ZodTuple:()=>Dt,ZodType:()=>W,ZodUndefined:()=>Gr,ZodUnion:()=>Xr,ZodUnknown:()=>tr,ZodVoid:()=>Nn,addIssueToContext:()=>E,any:()=>Jw,array:()=>Xw,bigint:()=>Uw,boolean:()=>xm,coerce:()=>x$,custom:()=>ym,date:()=>Fw,datetimeRegex:()=>hm,defaultErrorMap:()=>Qt,discriminatedUnion:()=>e$,effect:()=>f$,enum:()=>u$,function:()=>i$,getErrorMap:()=>Cn,getParsedType:()=>Zt,instanceof:()=>Lw,intersection:()=>t$,isAborted:()=>qs,isAsync:()=>On,isDirty:()=>Us,isValid:()=>gr,late:()=>Dw,lazy:()=>a$,literal:()=>c$,makeIssue:()=>Eo,map:()=>o$,nan:()=>qw,nativeEnum:()=>l$,never:()=>Gw,null:()=>Vw,nullable:()=>m$,number:()=>vm,object:()=>_c,objectUtil:()=>hc,oboolean:()=>v$,onumber:()=>_$,optional:()=>p$,ostring:()=>y$,pipeline:()=>g$,preprocess:()=>h$,promise:()=>d$,quotelessJson:()=>pw,record:()=>n$,set:()=>s$,setErrorMap:()=>hw,strictObject:()=>Yw,string:()=>_m,symbol:()=>Hw,transformer:()=>f$,tuple:()=>r$,undefined:()=>Bw,union:()=>Qw,unknown:()=>Ww,util:()=>ee,void:()=>Kw});var ee;(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})(ee||(ee={}));var hc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(hc||(hc={}));var P=ee.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Zt=t=>{switch(typeof t){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(t)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(t)?P.array:t===null?P.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?P.promise:typeof Map<"u"&&t instanceof Map?P.map:typeof Set<"u"&&t instanceof Set?P.set:typeof Date<"u"&&t instanceof Date?P.date:P.object;default:return P.unknown}};var k=ee.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"]),pw=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Xe=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,ee.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()}};Xe.create=t=>new Xe(t);var mw=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===P.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ee.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${ee.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ee.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${ee.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}"`:ee.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,ee.assertNever(t)}return{message:r}},Qt=mw;var lm=Qt;function hw(t){lm=t}function Cn(){return lm}var Eo=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}},gw=[];function E(t,e){let r=Cn(),n=Eo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Qt?void 0:Qt].filter(o=>!!o)});t.common.issues.push(n)}var Oe=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 L;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 L;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}}},L=Object.freeze({status:"aborted"}),Hr=t=>({status:"dirty",value:t}),Ze=t=>({status:"valid",value:t}),qs=t=>t.status==="aborted",Us=t=>t.status==="dirty",gr=t=>t.status==="valid",On=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 dt=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}},dm=(t,e)=>{if(gr(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 Xe(t.common.issues);return this._error=r,this._error}}};function V(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 W=class{get description(){return this._def.description}_getType(e){return Zt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Zt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Oe,ctx:{common:e.parent.common,data:e.data,parsedType:Zt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(On(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:Zt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return dm(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Zt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return gr(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=>gr(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:Zt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(On(o)?o:Promise.resolve(o));return dm(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 ft({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 Ye.create(this,this._def)}nullable(){return Lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return rr.create(this)}promise(){return vr.create(this,this._def)}or(e){return Xr.create([this,e],this._def)}and(e){return Yr.create(this,e,this._def)}transform(e){return new ft({...V(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new nn({...V(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new zo({typeName:S.ZodBranded,type:this,...V(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new on({...V(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 Ro.create(this,e)}readonly(){return sn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},yw=/^c[^\s-]{8,}$/i,_w=/^[0-9a-z]+$/,vw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xw=/^[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,bw=/^[a-z0-9_-]{21}$/i,ww=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$w=/^[-+]?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)?)??$/,kw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Sw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gc,Tw=/^(?:(?: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])$/,Ew=/^(?:(?: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])$/,zw=/^(([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]))$/,Rw=/^(([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])$/,Pw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Cw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,pm="((\\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])))",Ow=new RegExp(`^${pm}$`);function mm(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 Aw(t){return new RegExp(`^${mm(t)}$`)}function hm(t){let e=`${pm}T${mm(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 Iw(t,e){return!!((e==="v4"||!e)&&Tw.test(t)||(e==="v6"||!e)&&zw.test(t))}function Nw(t,e){if(!ww.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 Mw(t,e){return!!((e==="v4"||!e)&&Ew.test(t)||(e==="v6"||!e)&&Rw.test(t))}var yr=class t extends W{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.string){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.string,received:s.parsedType}),L}let n=new Oe,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")kw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")gc||(gc=new RegExp(Sw,"u")),gc.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")xw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")bw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")yw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")_w.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")vw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),E(o,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?hm(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Ow.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Aw(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?$w.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Iw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Nw(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Mw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Pw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Cw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):ee.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}};yr.create=t=>new yr({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...V(t)});function jw(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 Br=class t extends W{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)!==P.number){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.number,received:s.parsedType}),L}let n,o=new Oe;for(let s of this._def.checks)s.kind==="int"?ee.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?jw(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_finite,message:s.message}),o.dirty()):ee.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"&&ee.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)}};Br.create=t=>new Br({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...V(t)});var Vr=class t extends W{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)!==P.bigint)return this._getInvalidInput(e);let n,o=new Oe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ee.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:P.bigint,received:r.parsedType}),L}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}};Vr.create=t=>new Vr({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...V(t)});var Jr=class extends W{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.boolean){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.boolean,received:n.parsedType}),L}return Ze(e.data)}};Jr.create=t=>new Jr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...V(t)});var Wr=class t extends W{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.date){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.date,received:s.parsedType}),L}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_date}),L}let n=new Oe,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ee.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}};Wr.create=t=>new Wr({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...V(t)});var In=class extends W{_parse(e){if(this._getType(e)!==P.symbol){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.symbol,received:n.parsedType}),L}return Ze(e.data)}};In.create=t=>new In({typeName:S.ZodSymbol,...V(t)});var Gr=class extends W{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.undefined,received:n.parsedType}),L}return Ze(e.data)}};Gr.create=t=>new Gr({typeName:S.ZodUndefined,...V(t)});var Kr=class extends W{_parse(e){if(this._getType(e)!==P.null){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.null,received:n.parsedType}),L}return Ze(e.data)}};Kr.create=t=>new Kr({typeName:S.ZodNull,...V(t)});var _r=class extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return Ze(e.data)}};_r.create=t=>new _r({typeName:S.ZodAny,...V(t)});var tr=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ze(e.data)}};tr.create=t=>new tr({typeName:S.ZodUnknown,...V(t)});var kt=class extends W{_parse(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:P.never,received:r.parsedType}),L}};kt.create=t=>new kt({typeName:S.ZodNever,...V(t)});var Nn=class extends W{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.void,received:n.parsedType}),L}return Ze(e.data)}};Nn.create=t=>new Nn({typeName:S.ZodVoid,...V(t)});var rr=class t extends W{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==P.array)return E(r,{code:k.invalid_type,expected:P.array,received:r.parsedType}),L;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(E(r,{code:i?k.too_big:k.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(E(r,{code:k.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(E(r,{code:k.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new dt(r,i,r.path,a)))).then(i=>Oe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new dt(r,i,r.path,a)));return Oe.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)}};rr.create=(t,e)=>new rr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...V(e)});function An(t){if(t instanceof Qe){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ye.create(An(n))}return new Qe({...t._def,shape:()=>e})}else return t instanceof rr?new rr({...t._def,type:An(t.element)}):t instanceof Ye?Ye.create(An(t.unwrap())):t instanceof Lt?Lt.create(An(t.unwrap())):t instanceof Dt?Dt.create(t.items.map(e=>An(e))):t}var Qe=class t extends W{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=ee.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==P.object){let u=this._getOrReturnCtx(e);return E(u,{code:k.invalid_type,expected:P.object,received:u.parsedType}),L}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof kt&&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 dt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof kt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(E(o,{code:k.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new dt(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=>Oe.mergeObjectSync(n,u)):Oe.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 ee.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 ee.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return An(this)}partial(e){let r={};for(let n of ee.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 ee.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ye;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return gm(ee.objectKeys(this.shape))}};Qe.create=(t,e)=>new Qe({shape:()=>t,unknownKeys:"strip",catchall:kt.create(),typeName:S.ZodObject,...V(e)});Qe.strictCreate=(t,e)=>new Qe({shape:()=>t,unknownKeys:"strict",catchall:kt.create(),typeName:S.ZodObject,...V(e)});Qe.lazycreate=(t,e)=>new Qe({shape:t,unknownKeys:"strip",catchall:kt.create(),typeName:S.ZodObject,...V(e)});var Xr=class extends W{_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 Xe(a.ctx.common.issues));return E(r,{code:k.invalid_union,unionErrors:i}),L}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 Xe(c));return E(r,{code:k.invalid_union,unionErrors:a}),L}}get options(){return this._def.options}};Xr.create=(t,e)=>new Xr({options:t,typeName:S.ZodUnion,...V(e)});var er=t=>t instanceof Qr?er(t.schema):t instanceof ft?er(t.innerType()):t instanceof en?[t.value]:t instanceof tn?t.options:t instanceof rn?ee.objectValues(t.enum):t instanceof nn?er(t._def.innerType):t instanceof Gr?[void 0]:t instanceof Kr?[null]:t instanceof Ye?[void 0,...er(t.unwrap())]:t instanceof Lt?[null,...er(t.unwrap())]:t instanceof zo||t instanceof sn?er(t.unwrap()):t instanceof on?er(t._def.innerType):[],Fs=class t extends W{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.object)return E(r,{code:k.invalid_type,expected:P.object,received:r.parsedType}),L;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(E(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),L)}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=er(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,...V(n)})}};function yc(t,e){let r=Zt(t),n=Zt(e);if(t===e)return{valid:!0,data:t};if(r===P.object&&n===P.object){let o=ee.objectKeys(e),s=ee.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=yc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===P.array&&n===P.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=yc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===P.date&&n===P.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Yr=class extends W{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(qs(s)||qs(i))return L;let a=yc(s.value,i.value);return a.valid?((Us(s)||Us(i))&&r.dirty(),{status:r.value,value:a.data}):(E(n,{code:k.invalid_intersection_types}),L)};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}))}};Yr.create=(t,e,r)=>new Yr({left:t,right:e,typeName:S.ZodIntersection,...V(r)});var Dt=class t extends W{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.array)return E(n,{code:k.invalid_type,expected:P.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return E(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&(E(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new dt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Oe.mergeArray(r,i)):Oe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dt({items:t,typeName:S.ZodTuple,rest:null,...V(e)})};var Hs=class t extends W{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!==P.object)return E(n,{code:k.invalid_type,expected:P.object,received:n.parsedType}),L;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new dt(n,a,n.path,a)),value:i._parse(new dt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Oe.mergeObjectAsync(r,o):Oe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof W?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...V(n)}):new t({keyType:yr.create(),valueType:e,typeName:S.ZodRecord,...V(r)})}},Mn=class extends W{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!==P.map)return E(n,{code:k.invalid_type,expected:P.map,received:n.parsedType}),L;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new dt(n,a,n.path,[u,"key"])),value:s._parse(new dt(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 L;(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 L;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Mn.create=(t,e,r)=>new Mn({valueType:e,keyType:t,typeName:S.ZodMap,...V(r)});var jn=class t extends W{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.set)return E(n,{code:k.invalid_type,expected:P.set,received:n.parsedType}),L;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(E(n,{code:k.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(E(n,{code:k.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return L;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 dt(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)}};jn.create=(t,e)=>new jn({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...V(e)});var Bs=class t extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.function)return E(r,{code:k.invalid_type,expected:P.function,received:r.parsedType}),L;function n(a,c){return Eo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Cn(),Qt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return Eo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Cn(),Qt].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 vr){let a=this;return Ze(async function(...c){let u=new Xe([]),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 Ze(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Xe([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Xe([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:Dt.create(e).rest(tr.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||Dt.create([]).rest(tr.create()),returns:r||tr.create(),typeName:S.ZodFunction,...V(n)})}},Qr=class extends W{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})}};Qr.create=(t,e)=>new Qr({getter:t,typeName:S.ZodLazy,...V(e)});var en=class extends W{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return E(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};en.create=(t,e)=>new en({value:t,typeName:S.ZodLiteral,...V(e)});function gm(t,e){return new tn({values:t,typeName:S.ZodEnum,...V(e)})}var tn=class t extends W{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{expected:ee.joinValues(n),received:r.parsedType,code:k.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{received:r.data,code:k.invalid_enum_value,options:n}),L}return Ze(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})}};tn.create=gm;var rn=class extends W{_parse(e){let r=ee.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==P.string&&n.parsedType!==P.number){let o=ee.objectValues(r);return E(n,{expected:ee.joinValues(o),received:n.parsedType,code:k.invalid_type}),L}if(this._cache||(this._cache=new Set(ee.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ee.objectValues(r);return E(n,{received:n.data,code:k.invalid_enum_value,options:o}),L}return Ze(e.data)}get enum(){return this._def.values}};rn.create=(t,e)=>new rn({values:t,typeName:S.ZodNativeEnum,...V(e)});var vr=class extends W{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.promise&&r.common.async===!1)return E(r,{code:k.invalid_type,expected:P.promise,received:r.parsedType}),L;let n=r.parsedType===P.promise?r.data:Promise.resolve(r.data);return Ze(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};vr.create=(t,e)=>new vr({type:t,typeName:S.ZodPromise,...V(e)});var ft=class extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{E(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return L;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?L:c.status==="dirty"?Hr(c.value):r.value==="dirty"?Hr(c.value):c});{if(r.value==="aborted")return L;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?L:a.status==="dirty"?Hr(a.value):r.value==="dirty"?Hr(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?L:(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"?L:(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(!gr(i))return L;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=>gr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):L);ee.assertNever(o)}};ft.create=(t,e,r)=>new ft({schema:t,typeName:S.ZodEffects,effect:e,...V(r)});ft.createWithPreprocess=(t,e,r)=>new ft({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...V(r)});var Ye=class extends W{_parse(e){return this._getType(e)===P.undefined?Ze(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ye.create=(t,e)=>new Ye({innerType:t,typeName:S.ZodOptional,...V(e)});var Lt=class extends W{_parse(e){return this._getType(e)===P.null?Ze(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Lt.create=(t,e)=>new Lt({innerType:t,typeName:S.ZodNullable,...V(e)});var nn=class extends W{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===P.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};nn.create=(t,e)=>new nn({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...V(e)});var on=class extends W{_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 On(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Xe(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Xe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};on.create=(t,e)=>new on({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...V(e)});var Zn=class extends W{_parse(e){if(this._getType(e)!==P.nan){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};Zn.create=t=>new Zn({typeName:S.ZodNaN,...V(t)});var Zw=Symbol("zod_brand"),zo=class extends W{_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}},Ro=class t extends W{_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"?L:s.status==="dirty"?(r.dirty(),Hr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?L: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})}},sn=class extends W{_parse(e){let r=this._def.innerType._parse(e),n=o=>(gr(o)&&(o.value=Object.freeze(o.value)),o);return On(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};sn.create=(t,e)=>new sn({innerType:t,typeName:S.ZodReadonly,...V(e)});function fm(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function ym(t,e={},r){return t?_r.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=fm(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=fm(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):_r.create()}var Dw={object:Qe.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 Lw=(t,e={message:`Input not instance of ${t.name}`})=>ym(r=>r instanceof t,e),_m=yr.create,vm=Br.create,qw=Zn.create,Uw=Vr.create,xm=Jr.create,Fw=Wr.create,Hw=In.create,Bw=Gr.create,Vw=Kr.create,Jw=_r.create,Ww=tr.create,Gw=kt.create,Kw=Nn.create,Xw=rr.create,_c=Qe.create,Yw=Qe.strictCreate,Qw=Xr.create,e$=Fs.create,t$=Yr.create,r$=Dt.create,n$=Hs.create,o$=Mn.create,s$=jn.create,i$=Bs.create,a$=Qr.create,c$=en.create,u$=tn.create,l$=rn.create,d$=vr.create,f$=ft.create,p$=Ye.create,m$=Lt.create,h$=ft.createWithPreprocess,g$=Ro.create,y$=()=>_m().optional(),_$=()=>vm().optional(),v$=()=>xm().optional(),x$={string:(t=>yr.create({...t,coerce:!0})),number:(t=>Br.create({...t,coerce:!0})),boolean:(t=>Jr.create({...t,coerce:!0})),bigint:(t=>Vr.create({...t,coerce:!0})),date:(t=>Wr.create({...t,coerce:!0}))};var b$=L;He();He();He();He();var Pk=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");de.init(t,e),t.def=e,t.parse=(r,n)=>Ac(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>un(t,r,n),t.parseAsync=async(r,n)=>Nc(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>ln(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)=>ct(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var Ck=w("ZodMiniObject",(t,e)=>{ni.init(t,e),Pk.init(t,e),re.defineLazy(t,"shape",()=>e.shape)});function bl(t,e){let r={type:"object",get shape(){return re.assignProp(this,"shape",{...t}),this.shape},...re.normalizeParams(e)};return new Ck(r)}He();si();function Ft(t){return!!t._zod}function pn(t){let e=Object.values(t);if(e.length===0)return bl({});let r=e.every(Ft),n=e.every(o=>!Ft(o));if(r)return bl(t);if(n)return _c(t);throw new Error("Mixed Zod versions detected in object shape.")}function wr(t,e){return Ft(t)?un(t,e):t.safeParse(e)}async function pi(t,e){return Ft(t)?await ln(t,e):await t.safeParseAsync(e)}function $r(t){if(!t)return;let e;if(Ft(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Fn(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 pn(t)}}if(Ft(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 Ak(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function mi(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 ${Ak(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 Uh(t){return t.description}function Fh(t){if(Ft(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Hn(t){if(Ft(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}Sr();function Tr(t){return t==="completed"||t==="failed"||t==="cancelled"}var Ig=Symbol("Let zodToJsonSchema decide on which parser to use");var Ag={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"},Ng=t=>typeof t=="string"?{...Ag,name:t}:{...Ag,...t};var Mg=t=>{let e=Ng(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 Xl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function oe(t,e,r,n,o){t[e]=r,Xl(t,e,n,o)}var Di=(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 ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Di(e,t.currentPath):e.join("/")}}function jg(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=F(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&oe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&oe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(oe(r,"minItems",t.exactLength.value,t.exactLength.message,e),oe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Zg(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?oe(r,"minimum",n.value,n.message,e):oe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),oe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?oe(r,"maximum",n.value,n.message,e):oe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),oe(r,"maximum",n.value,n.message,e));break;case"multipleOf":oe(r,"multipleOf",n.value,n.message,e);break}return r}function Dg(){return{type:"boolean"}}function Li(t,e){return F(t.type._def,e)}var Lg=(t,e)=>F(t.innerType._def,e);function Yl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Yl(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 sE(t,e)}}var sE=(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":oe(r,"minimum",n.value,n.message,e);break;case"max":oe(r,"maximum",n.value,n.message,e);break}return r};function qg(t,e){return{...F(t.innerType._def,e),default:t.defaultValue()}}function Ug(t,e){return e.effectStrategy==="input"?F(t.schema._def,e):ke(e)}function Fg(t){return{type:"string",enum:Array.from(t.values)}}var iE=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Hg(t,e){let r=[F(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),F(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(iE(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 Bg(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 Ql,Tt={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:()=>(Ql===void 0&&(Ql=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ql),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 qi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":oe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":oe(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":Et(r,"email",n.message,e);break;case"format:idn-email":Et(r,"idn-email",n.message,e);break;case"pattern:zod":Ve(r,Tt.email,n.message,e);break}break;case"url":Et(r,"uri",n.message,e);break;case"uuid":Et(r,"uuid",n.message,e);break;case"regex":Ve(r,n.regex,n.message,e);break;case"cuid":Ve(r,Tt.cuid,n.message,e);break;case"cuid2":Ve(r,Tt.cuid2,n.message,e);break;case"startsWith":Ve(r,RegExp(`^${ed(n.value,e)}`),n.message,e);break;case"endsWith":Ve(r,RegExp(`${ed(n.value,e)}$`),n.message,e);break;case"datetime":Et(r,"date-time",n.message,e);break;case"date":Et(r,"date",n.message,e);break;case"time":Et(r,"time",n.message,e);break;case"duration":Et(r,"duration",n.message,e);break;case"length":oe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),oe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ve(r,RegExp(ed(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Et(r,"ipv4",n.message,e),n.version!=="v4"&&Et(r,"ipv6",n.message,e);break}case"base64url":Ve(r,Tt.base64url,n.message,e);break;case"jwt":Ve(r,Tt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ve(r,Tt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ve(r,Tt.ipv6Cidr,n.message,e);break}case"emoji":Ve(r,Tt.emoji(),n.message,e);break;case"ulid":{Ve(r,Tt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Et(r,"binary",n.message,e);break}case"contentEncoding:base64":{oe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ve(r,Tt.base64,n.message,e);break}}break}case"nanoid":Ve(r,Tt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ed(t,e){return e.patternStrategy==="escape"?cE(t):t}var aE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function cE(t){let e="";for(let r=0;r<t.length;r++)aE.has(t[r])||(e+="\\"),e+=t[r];return e}function Et(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}}})):oe(t,"format",e,r,n)}function Ve(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:Vg(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):oe(t,"pattern",Vg(e,n),r,n)}function Vg(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 Di(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]:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??$e(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:F(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}=Zi(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}=ji(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Zg(t,e){if(e.mapStrategy==="record")return Di(t,e);let r=F(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||$e(e),n=F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||$e(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Dg(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 Lg(t){return t.target==="openAi"?void 0:{not:$e({...t,currentPath:[...t.currentPath,"not"]})}}function qg(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Xo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ug(t,e){if(e.target==="openApi3")return Fg(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Xo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Xo[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 Fg(t,e)}var Fg=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>F(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 Hg(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:Xo[t.innerType._def.typeName],nullable:!0}:{type:[Xo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Bg(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",Jl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?re(r,"minimum",n.value,n.message,e):re(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?re(r,"maximum",n.value,n.message,e):re(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",n.value,n.message,e));break;case"multipleOf":re(r,"multipleOf",n.value,n.message,e);break}return r}function Vg(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=XT(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=F(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=GT(t,e);return i!==void 0&&(n.additionalProperties=i),n}function GT(t,e){if(t.catchall._def.typeName!=="ZodNever")return F(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 XT(t){try{return t.isOptional()}catch{return!0}}var Jg=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return F(t.innerType._def,e);let r=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:$e(e)},r]}:$e(e)};var Wg=(t,e)=>{if(e.pipeStrategy==="input")return F(t.in._def,e);if(e.pipeStrategy==="output")return F(t.out._def,e);let r=F(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=F(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Kg(t,e){return F(t.type._def,e)}function Gg(t,e){let n={type:"array",uniqueItems:!0,items:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&re(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&re(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Xg(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>F(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:F(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>F(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Yg(t){return{not:$e(t)}}function Qg(t){return $e(t)}var ey=(t,e)=>F(t.innerType._def,e);var ty=(t,e,r)=>{switch(e){case S.ZodString:return Zi(t,r);case S.ZodNumber:return Bg(t,r);case S.ZodObject:return Vg(t,r);case S.ZodBigInt:return Rg(t,r);case S.ZodBoolean:return Pg();case S.ZodDate:return Wl(t,r);case S.ZodUndefined:return Yg(r);case S.ZodNull:return qg(r);case S.ZodArray:return zg(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Ug(t,r);case S.ZodIntersection:return Ng(t,r);case S.ZodTuple:return Xg(t,r);case S.ZodRecord:return Di(t,r);case S.ZodLiteral:return Mg(t,r);case S.ZodEnum:return Og(t);case S.ZodNativeEnum:return Dg(t);case S.ZodNullable:return Hg(t,r);case S.ZodOptional:return Jg(t,r);case S.ZodMap:return Zg(t,r);case S.ZodSet:return Gg(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Kg(t,r);case S.ZodNaN:case S.ZodNever:return Lg(r);case S.ZodEffects:return Ag(t,r);case S.ZodAny:return $e(r);case S.ZodUnknown:return Qg(r);case S.ZodDefault:return Cg(t,r);case S.ZodBranded:return ji(t,r);case S.ZodReadonly:return ey(t,r);case S.ZodCatch:return Ig(t,r);case S.ZodPipeline:return Wg(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function F(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Sg)return a}if(n&&!r){let a=YT(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=ty(t,t.typeName,e),i=typeof s=="function"?F(s(),e):s;if(i&&QT(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var YT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Mi(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`),$e(e)):e.$refStrategy==="seen"?$e(e):void 0}},QT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Xl=(t,e)=>{let r=Eg(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:F(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??$e(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=F(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??$e(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 eE(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Yl(t,e){return Dt(t)?gl(t,{target:eE(e?.target),io:e?.pipeStrategy??"input"}):Xl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Ql(t){let r=xr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ln(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ed(t,e){let r=vr(t,e);if(!r.success)throw r.error;return r.data}var tE=6e4,Li=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(_i,r=>{this._oncancel(r)}),this.setNotificationHandler(bi,r=>{this._onprogress(r)}),this.setRequestHandler(xi,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wi,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(O.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ki,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new C(O.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 C(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 C(O.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,[br]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Si,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 C(O.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ei,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(O.InvalidParams,`Task not found: ${r.params.taskId}`);if($r(o.status))throw new C(O.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 C(O.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof C?o:new C(O.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),C.fromError(O.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),rr(s)||Un(s)?this._onresponse(s):tr(s)?this._onrequest(s,i):mg(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=C.fromError(O.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?.[br]?.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 C(O.InvalidParams,`Task not found: ${s}`);c=!0})()),n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:O.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=dg(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 C(O.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 C(O.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:O.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),rr(e))n(e);else{let i=new C(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(rr(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),rr(e))o(e);else{let i=C.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 C?i:new C(O.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Hn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new C(O.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 C(O.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new C(O.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 C?i:new C(O.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||{},[br]: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 C?v:new C(O.RequestTimeout,String(v));l(y)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let y=vr(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??tE,h=()=>f(C.fromError(O.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},$i,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},Ti,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},gg,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||{},[br]: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||{},[br]: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||{},[br]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ql(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ed(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=Ql(e);this._notificationHandlers.set(n,o=>{let s=ed(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"&&tr(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new C(O.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 C(O.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new C(O.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 C(O.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=Jo.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 C(O.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if($r(a.status))throw new C(O.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=Jo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),$r(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function ry(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ny(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];ry(i)&&ry(s)?r[o]={...i,...s}:r[o]=s}return r}wr();var sv=lc(Vf(),1),iv=lc(ov(),1);function mC(){let t=new sv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,iv.default)(t),t}var Sa=class{constructor(e){this._ajv=e??mC()}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)}}};wr();var Ta=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},Go,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},Jn,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 av(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 cv(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 Ea=class extends Li{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ko.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 Sa,this.setRequestHandler(vi,n=>this._oninitialize(n)),this.setNotificationHandler(jl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Hl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ko.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ta(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ny(this._capabilities,e)}setRequestHandler(e,r){let o=xr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Ln(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=vr(Vn,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new C(O.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let f=vr(Hn,m);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new C(O.InvalidParams,`Invalid task creation result: ${g}`)}return f.data}let p=vr(Oi,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new C(O.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){cv(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&av(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:Fn.includes(r)?r:Cl,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"},yi)}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},Bl,r):this.request({method:"sampling/createMessage",params:e},Go,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},Jn,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},Jn,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new C(O.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof C?i:new C(O.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},Vl,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"})}};wr();var lv=Symbol.for("mcp.completable");function ep(t){return!!t&&typeof t=="object"&&lv in t}function dv(t){return t[lv]?.complete}var uv;(function(t){t.Completable="McpCompletable"})(uv||(uv={}));var za=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 hC=/^[A-Za-z0-9._-]{1,128}$/;function gC(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"),!hC.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 yC(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 tp(t){let e=gC(t);return yC(t,e.warnings),e.isValid}var Ra=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};function _C(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 vC(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 Pa=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 Ea(e,r),this._maxToolInputElements=vC(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 Ra(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Cr(Ai)),this.server.assertCanSetRequestHandler(Cr(Vn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ai,()=>({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=Dn(r.inputSchema);return o?Yl(o,{strictUnions:!0,pipeStrategy:"input"}):xC})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Dn(r.outputSchema);o&&(n.outputSchema=Yl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Vn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new C(O.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new C(O.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 C(O.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new C(O.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 C&&n.code===O.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&&_C(r,this._maxToolInputElements)>this._maxToolInputElements)throw new C(O.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=Dn(e.inputSchema)??e.inputSchema,i=await li(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",c=di(a);throw new C(O.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 C(O.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Dn(e.outputSchema),s=await li(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=di(i);throw new C(O.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 C(O.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Cr(Ni)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ni,async e=>{switch(e.params.ref.type){case"ref/prompt":return wg(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return $g(e),this.handleResourceCompletion(e,e.params.ref);default:throw new C(O.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new C(O.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return zs;let s=xr(n.argsSchema)?.[e.params.argument.name];if(!ep(s))return zs;let i=dv(s);if(!i)return zs;let a=await i(e.params.argument.value,e.params.context);return pv(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 zs;throw new C(O.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return zs;let s=await o(e.params.argument.value,e.params.context);return pv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Cr(zi)),this.server.assertCanSetRequestHandler(Cr(Ri)),this.server.assertCanSetRequestHandler(Cr(Pi)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zi,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(Ri,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Pi,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new C(O.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 C(O.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Cr(Ii)),this.server.assertCanSetRequestHandler(Cr(Ci)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ii,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?bC(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ci,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new C(O.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Dn(n.argsSchema),s=await li(o,e.params.arguments??{});if(!s.success){let c="error"in s?s.error:"Unknown error",u=di(c);throw new C(O.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:ln(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=ln(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 Xe?c._def?.innerType:c;return ep(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){tp(e);let l={title:r,description:n,inputSchema:fv(o),outputSchema:fv(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"&&tp(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=ln(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=ln(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(rp(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!rp(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()}},Ia=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new za(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},xC={type:"object",properties:{}};function mv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function hv(t){return"_def"in t||"_zod"in t||mv(t)}function rp(t){return typeof t!="object"||t===null||hv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(mv)}function fv(t){if(t){if(rp(t))return ln(t);if(!hv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function bC(t){let e=xr(t);return e?Object.entries(e).map(([r,n])=>{let o=Ah(n),s=Oh(n);return{name:r,description:o,required:!s}}):[]}function Cr(t){let r=xr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ln(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function pv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var zs={completion:{values:[],hasMore:!1}};import yv from"node:process";wr();var wC=10*1024*1024,Ca=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??wC}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 sp(r,e)}function _v(t){if(typeof t!="string")if(t!==null&&typeof t=="object")try{t=JSON.stringify(t)}catch{return np("")}else t=t==null?"":String(t);let e;try{e=JSON.parse(t)}catch(l){return np(t,l)}if(e===null||typeof e!="object")return np(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)=>op(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)=>sp(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}:op(d,-1);l.push({index:-1,role:"system",kind:"system",text:m.text,hasBinary:m.hasBinary})}return l.push(...r.contents.map((m,p)=>op(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=Oa(r.system);a.push({index:-1,role:"system",kind:"system",text:l.text,hasBinary:l.hasBinary})}a.push(...s.map((l,d)=>sp(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 oA}from"node:crypto";var vv=[[/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]],Tq=Math.max(...vv.map(([,t])=>t));function Na(t){if(t){for(let[e,r]of vv)if(e.test(t))return r}}function Ar(t){return t?/claude/i.test(t)?"anthropic":/gpt|^o\d/i.test(t)?"openai":/gemini/i.test(t)?"google":"generic":"generic"}function TC(t){return t.length===0?0:(t.match(/[{}[\]()<>;:=_\/\\|"'`#$%&*+^~-]/g)?.length??0)/t.length}var Rs={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 xv(t){return TC(t)>.08}function ip(t,e){let r=Rs[Ar(e)];return xv(t)?r.code:r.prose}function It(t,e){return typeof t!="string"&&(t=String(t??"")),t?EC(t.length,xv(t),e):0}function EC(t,e,r){if(!(t>0))return 0;let n=Rs[Ar(r)];return Math.ceil(t/(e?n.code:n.prose))}var ap=4;function R(t){if(!Number.isFinite(t))return"0";if(t<0)return`-${R(-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 T=(t,e,r)=>({inputPerM:t,outputPerM:e,cacheReadPerM:r});function Me(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 Ma=[/claude.*fable|claude.*mythos/i,/claude.*opus/i,/claude.*sonnet/i,/claude.*haiku/i],bv=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Q(t){return new RegExp(`(?<![\\w.-])${bv(t)}(?:-\\d{4}-\\d{2}-\\d{2})?(?![\\w.-])`,"i")}function Bt(t){return new RegExp(`(?<![\\w.-])${bv(t)}(?![\\w.])(?!-(?:[\\w.]+-)*(?:lite|image|tts|live|audio|transcribe|translate)\\b)`,"i")}var We=!0,zC=[[Me("fable|mythos",5,1),T(10,50,.25)],[Me("fable|mythos",5),T(10,50,1)],[Me("opus",5,5),T(4,20,.2)],[Me("opus",5),T(5,25,.5)],[Me("opus",4,8),T(5,25,.5)],[Me("opus",4,7),T(5,25,.5)],[Me("opus",4,6),T(5,25,.5)],[Me("opus",4,5),T(5,25,.5)],[Me("opus",4,1),T(15,75,1.5)],[Me("opus",4),T(15,75,1.5)],[Me("sonnet",5,5),T(2,10,.1)],[Me("sonnet",5),T(2,10,.2)],[Me("haiku",5,5),T(.1,.5,.01)],[Me("haiku",4,5),T(1,5,.1)],[Me("sonnet",4,6),T(3,15,.3)],[Me("sonnet",4,5),T(3,15,.3)],[Me("sonnet",4),T(3,15,.3)],[/claude-3-opus/i,T(15,75,1.5)],[/claude-3-5-haiku/i,T(.8,4,.08)],[/claude-3-haiku/i,T(.25,1.25,.03)],[/claude-3-[57]-sonnet/i,T(3,15,.3)],[Ma[0],T(10,50,1),We],[Ma[1],T(5,25,.5),We],[Ma[2],T(3,15,.3),We],[Ma[3],T(1,5,.1),We],[Q("gpt-6-astra"),T(10,50,1)],[Q("gpt-6-astra-law"),T(10,50,1)],[Q("gpt-6.1-sol"),T(2,10,.1)],[Q("gpt-6.1-terra"),T(1,5,.05)],[Q("gpt-6-sol"),T(2,10,.2)],[Q("gpt-6-luna"),T(.1,.5,.01)],[Q("gpt-6-cyber"),T(20,100,2)],[Q("gpt-6-rosalind"),T(15,75,1.5)],[Q("gpt-rosalind-research"),T(5,25,.5)],[Q("gpt-rosalind-discovery"),T(5,25,.5)],[Q("gpt-5.6-sol"),T(4,20,.4)],[Q("gpt-5.6"),T(4,20,.4)],[Q("gpt-5.6-terra"),T(2,12,.2)],[Q("gpt-5.6-luna"),T(.2,1.2,.02)],[Q("gpt-5.6-cyber"),T(12.5,75,1.25)],[Q("gpt-5.5"),T(5,30,.5)],[Q("gpt-5.5-pro"),T(30,180,30)],[Q("gpt-5.5-cyber"),T(12.5,75,1.25)],[Q("gpt-5.4"),T(2.5,15,.25)],[Q("gpt-5.4-mini"),T(.75,4.5,.075)],[Q("gpt-5.4-nano"),T(.2,1.25,.02)],[Q("gpt-5.4-pro"),T(30,180,30)],[Q("gpt-5.3-codex"),T(1.75,14,.175)],[Q("gpt-5.2"),T(1.75,14,.175)],[Q("gpt-5.2-pro"),T(21,168,21)],[Q("gpt-5.1"),T(1.25,10,.125)],[Q("gpt-5"),T(1.25,10,.125)],[Q("gpt-5-mini"),T(.25,2,.025)],[Q("gpt-5-nano"),T(.05,.4,.005)],[Q("gpt-5-pro"),T(15,120,15)],[Q("gpt-4.1"),T(2,8,.5)],[Q("gpt-4.1-mini"),T(.4,1.6,.1)],[Q("gpt-4o"),T(2.5,10,1.25)],[Q("gpt-4o-mini"),T(.15,.6,.075)],[Q("o3"),T(2,8,.5)],[Q("o3-pro"),T(20,80,20)],[Q("chat-latest"),T(5,30,.5)],[/gpt-5.*(mini|nano)/i,T(.25,2,.025),We],[/gpt-5/i,T(1.25,10,.125),We],[/gpt-4o-mini/i,T(.15,.6,.075),We],[/gpt-4o|gpt-4\.1/i,T(2.5,10,1.25),We],[/gpt-4-turbo/i,T(10,30,10),We],[/o[13](-|$)/i,T(2,8,1),We],[Bt("gemini-4-argon"),T(2,10,.1)],[Bt("gemini-3.8-flash"),T(.75,3.75,.075)],[Bt("gemini-3.6-flash"),T(.75,3.75,.075)],[Bt("gemini-3.5-flash-lite"),T(.3,2.5,.03)],[Bt("gemini-3.1-flash-lite"),T(.25,1.5,.025)],[Bt("gemini-3.1-pro"),T(2,12,.2)],[Bt("gemini-3-flash"),T(.5,3,.05)],[Bt("gemini-2.5-pro"),T(1.25,10,.125)],[Bt("gemini-2.5-flash"),T(.3,2.5,.03)],[Bt("gemini-2.5-flash-lite"),T(.1,.4,.01)],[/gemini-3[.\d]*-flash-lite/i,T(.3,2.5,.03),We],[/gemini-3[.\d]*-flash/i,T(.75,3.75,.075),We],[/gemini-3[.\d]*-pro/i,T(2,12,.2),We],[/gemini.*flash/i,T(.1,.4,.025),We],[/gemini.*pro/i,T(1.25,5,.31),We]];function RC(t){if(t)return zC.find(([e])=>e.test(t))}function fo(t){return RC(t)?.[1]}function Or(t,e){return t/1e6*e.inputPerM}function cp(t){return t/25e3}function Vt(t){return Number.isFinite(t)?t>=1?`$${t.toFixed(2)}`:t>=.01?`$${t.toFixed(3)}`:`$${t.toFixed(4)}`:"$0.00"}var wv=/(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g,PC="[context-doctor: base64 blob removed \u2014 use file/image APIs instead]";function $v(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 po(t){for(let e of t.matchAll(wv))if($v(e[0]))return!0;return!1}function up(t){return t.replace(wv,e=>$v(e)?PC:e)}import{mkdirSync as Dq,readFileSync as KC,writeFileSync as Lq}from"node:fs";import{dirname as GC,join as XC}from"node:path";import{appendFileSync as OC,existsSync as lp,mkdirSync as NC,readFileSync as MC,statSync as jC,writeFileSync as ZC}from"node:fs";import{homedir as Sv}from"node:os";import{dirname as Ev,join as mo}from"node:path";import{homedir as kv}from"node:os";import{join as IC,resolve as CC}from"node:path";function AC(t,e){if(t!==void 0&&t!==kv())return;let r=e.CLAUDE_CONFIG_DIR?.trim();return r?CC(r):void 0}function Nr(t,e=process.env){return AC(t,e)??IC(t??kv(),".claude")}var DC={optimizeSaved:0,optimizeUsd:0,proxySaved:0,proxyUsd:0,proxyRequests:0,checks:0,warnings:0,shrinkage:0};function LC(t){let e={...DC},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 qC(){let t=process.env.XDG_STATE_HOME?.trim();return t?mo(t,"context-doctor"):process.platform==="win32"?mo(process.env.LOCALAPPDATA?.trim()||mo(Sv(),"AppData","Local"),"context-doctor"):mo(Sv(),".local","state","context-doctor")}function FC(){let t=qC();if(lp(t))return t;let e=Nr();return lp(e)?e:t}function dp(){return process.env.CONTEXT_DOCTOR_HOOK_STATE??mo(FC(),".context-doctor-hook-state.json")}function UC(){return mo(Ev(dp()),".context-doctor-ledger.jsonl")}var Tv=100,HC=256*1024,BC=128*1024,VC=500,JC=4*1024;function WC(t){if(typeof t!="string")return;let e=t.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return e.length>Tv?e.slice(0,Tv):e}function ja(t){let e=UC();try{if(NC(Ev(e),{recursive:!0}),lp(e)&&jC(e).size>HC){let n=MC(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<
|
|
56
|
+
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function Ui(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:F(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}=qi(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}=Li(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Jg(t,e){if(e.mapStrategy==="record")return Ui(t,e);let r=F(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ke(e),n=F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Wg(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 Gg(t){return t.target==="openAi"?void 0:{not:ke({...t,currentPath:[...t.currentPath,"not"]})}}function Kg(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var es={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Yg(t,e){if(e.target==="openApi3")return Xg(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in es&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=es[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 Xg(t,e)}var Xg=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>F(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 Qg(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:es[t.innerType._def.typeName],nullable:!0}:{type:[es[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ey(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",Xl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?oe(r,"minimum",n.value,n.message,e):oe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),oe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?oe(r,"maximum",n.value,n.message,e):oe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),oe(r,"maximum",n.value,n.message,e));break;case"multipleOf":oe(r,"multipleOf",n.value,n.message,e);break}return r}function ty(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=lE(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=F(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=uE(t,e);return i!==void 0&&(n.additionalProperties=i),n}function uE(t,e){if(t.catchall._def.typeName!=="ZodNever")return F(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 lE(t){try{return t.isOptional()}catch{return!0}}var ry=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return F(t.innerType._def,e);let r=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ke(e)},r]}:ke(e)};var ny=(t,e)=>{if(e.pipeStrategy==="input")return F(t.in._def,e);if(e.pipeStrategy==="output")return F(t.out._def,e);let r=F(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=F(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function oy(t,e){return F(t.type._def,e)}function sy(t,e){let n={type:"array",uniqueItems:!0,items:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&oe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&oe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function iy(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>F(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:F(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>F(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function ay(t){return{not:ke(t)}}function cy(t){return ke(t)}var uy=(t,e)=>F(t.innerType._def,e);var ly=(t,e,r)=>{switch(e){case S.ZodString:return qi(t,r);case S.ZodNumber:return ey(t,r);case S.ZodObject:return ty(t,r);case S.ZodBigInt:return Zg(t,r);case S.ZodBoolean:return Dg();case S.ZodDate:return Yl(t,r);case S.ZodUndefined:return ay(r);case S.ZodNull:return Kg(r);case S.ZodArray:return jg(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Yg(t,r);case S.ZodIntersection:return Hg(t,r);case S.ZodTuple:return iy(t,r);case S.ZodRecord:return Ui(t,r);case S.ZodLiteral:return Bg(t,r);case S.ZodEnum:return Fg(t);case S.ZodNativeEnum:return Wg(t);case S.ZodNullable:return Qg(t,r);case S.ZodOptional:return ry(t,r);case S.ZodMap:return Jg(t,r);case S.ZodSet:return sy(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return oy(t,r);case S.ZodNaN:case S.ZodNever:return Gg(r);case S.ZodEffects:return Ug(t,r);case S.ZodAny:return ke(r);case S.ZodUnknown:return cy(r);case S.ZodDefault:return qg(t,r);case S.ZodBranded:return Li(t,r);case S.ZodReadonly:return uy(t,r);case S.ZodCatch:return Lg(t,r);case S.ZodPipeline:return ny(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function F(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Ig)return a}if(n&&!r){let a=dE(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=ly(t,t.typeName,e),i=typeof s=="function"?F(s(),e):s;if(i&&fE(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var dE=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Di(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`),ke(e)):e.$refStrategy==="seen"?ke(e):void 0}},fE=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var td=(t,e)=>{let r=Mg(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:F(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ke(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=F(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ke(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 pE(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function rd(t,e){return Ft(t)?xl(t,{target:pE(e?.target),io:e?.pipeStrategy??"input"}):td(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function nd(t){let r=$r(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Hn(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function od(t,e){let r=wr(t,e);if(!r.success)throw r.error;return r.data}var mE=6e4,Fi=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(bi,r=>{this._oncancel(r)}),this.setNotificationHandler(ki,r=>{this._onprogress(r)}),this.setRequestHandler($i,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Si,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new O(A.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ei,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new O(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 O(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 O(A.InvalidParams,`Task not found: ${s}`);if(!Tr(i.status))return await this._waitForTaskUpdate(s,n.signal,n.sessionId),await o();if(Tr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s,n.sessionId),{...a,_meta:{...a._meta,[kr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(zi,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new O(A.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Pi,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new O(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(Tr(o.status))throw new O(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 O(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof O?o:new O(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),O.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),sr(s)||Jn(s)?this._onresponse(s):or(s)?this._onrequest(s,i):$g(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=O.fromError(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?.[kr]?.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 O(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 h={type:"error",message:f,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(s,h,i),()=>o?.send(f)).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):o?.send(f).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let d=xg(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 h={relatedRequestId:e.id};s&&(h.relatedTask={taskId:s}),await this.notification(f,h)},sendRequest:async(f,h,g)=>{if(l.signal.aborted)throw new O(A.ConnectionClosed,"Request was cancelled");let _={...g,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,h,_)},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 O(A.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,p)).then(async f=>{if(l.signal.aborted)return;let h={result:f,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)},async f=>{if(l.signal.aborted)return;let h={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:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)}).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),sr(e))n(e);else{let i=new O(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(sr(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),sr(e))o(e);else{let i=O.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof O?i:new O(A.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Wn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new O(A.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Tr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new O(A.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new O(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 O?i:new O(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||{},[kr]: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 O?v:new O(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=wr(r,v.result);y.success?u(y.data):l(y.error)}catch(y){l(y)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??mE,g=()=>f(O.fromError(A.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,g,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},Ti,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ri,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Sg,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||{},[kr]: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||{},[kr]: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||{},[kr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=nd(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=od(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=nd(e);this._notificationHandlers.set(n,o=>{let s=od(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"&&or(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new O(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 O(A.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new O(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 O(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=Ko.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Tr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new O(A.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Tr(a.status))throw new O(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=Ko.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Tr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function dy(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function fy(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];dy(i)&&dy(s)?r[o]={...i,...s}:r[o]=s}return r}Sr();var mv=mc(Kf(),1),hv=mc(pv(),1);function EO(){let t=new mv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,hv.default)(t),t}var za=class{constructor(e){this._ajv=e??EO()}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)}}};Sr();var Ra=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},Qo,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},Xn,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 gv(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 yv(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 Pa=class extends Fi{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Yo.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 za,this.setRequestHandler(wi,n=>this._oninitialize(n)),this.setNotificationHandler(ql,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Wl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Yo.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ra(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=fy(this._capabilities,e)}setRequestHandler(e,r){let o=$r(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Hn(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=wr(Kn,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new O(A.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let f=wr(Wn,m);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new O(A.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let p=wr(ji,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new O(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){yv(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&gv(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:Vn.includes(r)?r:Ml,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"},xi)}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},Gl,r):this.request({method:"sampling/createMessage",params:e},Qo,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},Xn,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},Xn,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new O(A.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof O?i:new O(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},Kl,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"})}};Sr();var vv=Symbol.for("mcp.completable");function op(t){return!!t&&typeof t=="object"&&vv in t}function xv(t){return t[vv]?.complete}var _v;(function(t){t.Completable="McpCompletable"})(_v||(_v={}));var Ca=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 zO=/^[A-Za-z0-9._-]{1,128}$/;function RO(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"),!zO.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 PO(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 sp(t){let e=RO(t);return PO(t,e.warnings),e.isValid}var Oa=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 CO(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 OO(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 Aa=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 Pa(e,r),this._maxToolInputElements=OO(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 Oa(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Nr(Mi)),this.server.assertCanSetRequestHandler(Nr(Kn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Mi,()=>({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=Fn(r.inputSchema);return o?rd(o,{strictUnions:!0,pipeStrategy:"input"}):AO})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Fn(r.outputSchema);o&&(n.outputSchema=rd(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Kn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new O(A.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new O(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 O(A.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new O(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 O&&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&&CO(r,this._maxToolInputElements)>this._maxToolInputElements)throw new O(A.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=Fn(e.inputSchema)??e.inputSchema,i=await pi(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",c=mi(a);throw new O(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 O(A.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Fn(e.outputSchema),s=await pi(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=mi(i);throw new O(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 O(A.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Nr(Zi)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Zi,async e=>{switch(e.params.ref.type){case"ref/prompt":return Cg(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Og(e),this.handleResourceCompletion(e,e.params.ref);default:throw new O(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 O(A.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new O(A.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Cs;let s=$r(n.argsSchema)?.[e.params.argument.name];if(!op(s))return Cs;let i=xv(s);if(!i)return Cs;let a=await i(e.params.argument.value,e.params.context);return wv(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 Cs;throw new O(A.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Cs;let s=await o(e.params.argument.value,e.params.context);return wv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Nr(Ci)),this.server.assertCanSetRequestHandler(Nr(Oi)),this.server.assertCanSetRequestHandler(Nr(Ai)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ci,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(Oi,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ai,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new O(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 O(A.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Nr(Ii)),this.server.assertCanSetRequestHandler(Nr(Ni)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ii,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?IO(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ni,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new O(A.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new O(A.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Fn(n.argsSchema),s=await pi(o,e.params.arguments??{});if(!s.success){let c="error"in s?s.error:"Unknown error",u=mi(c);throw new O(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:pn(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=pn(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 Ye?c._def?.innerType:c;return op(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){sp(e);let l={title:r,description:n,inputSchema:bv(o),outputSchema:bv(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"&&sp(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=pn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=pn(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(ip(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!ip(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()}},Ia=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new Ca(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},AO={type:"object",properties:{}};function $v(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function kv(t){return"_def"in t||"_zod"in t||$v(t)}function ip(t){return typeof t!="object"||t===null||kv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some($v)}function bv(t){if(t){if(ip(t))return pn(t);if(!kv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function IO(t){let e=$r(t);return e?Object.entries(e).map(([r,n])=>{let o=Uh(n),s=Fh(n);return{name:r,description:o,required:!s}}):[]}function Nr(t){let r=$r(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Hn(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function wv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Cs={completion:{values:[],hasMore:!1}};import Tv from"node:process";Sr();var NO=10*1024*1024,Na=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??NO}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),MO(r)}clear(){this._buffer=void 0}};function MO(t){return Bo.parse(JSON.parse(t))}function Sv(t){return JSON.stringify(t)+`
|
|
58
|
+
`}var Ma=class{constructor(e=Tv.stdin,r=Tv.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 Na({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=Sv(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};Sr();function ja(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=ja(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 up(t,e){let r=t&&typeof t=="object"?t:{},n=String(r.role??"user"),o=ja(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 ap(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 jO(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 cp(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=jO(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 ZO(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}:ja(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 up(r,e)}function Ev(t){if(typeof t!="string")if(t!==null&&typeof t=="object")try{t=JSON.stringify(t)}catch{return ap("")}else t=t==null?"":String(t);let e;try{e=JSON.parse(t)}catch(l){return ap(t,l)}if(e===null||typeof e!="object")return ap(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)=>cp(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)=>up(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}:cp(d,-1);l.push({index:-1,role:"system",kind:"system",text:m.text,hasBinary:m.hasBinary})}return l.push(...r.contents.map((m,p)=>cp(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)=>ZO(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=ja(r.system);a.push({index:-1,role:"system",kind:"system",text:l.text,hasBinary:l.hasBinary})}a.push(...s.map((l,d)=>up(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 gA}from"node:crypto";var zv=[[/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]],Lq=Math.max(...zv.map(([,t])=>t));function Za(t){if(t){for(let[e,r]of zv)if(e.test(t))return r}}function Mr(t){return t?/claude/i.test(t)?"anthropic":/gpt|^o\d/i.test(t)?"openai":/gemini/i.test(t)?"google":"generic":"generic"}function DO(t){return t.length===0?0:(t.match(/[{}[\]()<>;:=_\/\\|"'`#$%&*+^~-]/g)?.length??0)/t.length}var Os={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 Rv(t){return DO(t)>.08}function lp(t,e){let r=Os[Mr(e)];return Rv(t)?r.code:r.prose}function At(t,e){return typeof t!="string"&&(t=String(t??"")),t?LO(t.length,Rv(t),e):0}function LO(t,e,r){if(!(t>0))return 0;let n=Os[Mr(r)];return Math.ceil(t/(e?n.code:n.prose))}var dp=4;function R(t){if(!Number.isFinite(t))return"0";if(t<0)return`-${R(-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`}import{homedir as fp}from"node:os";import{join as Pv,resolve as qO}from"node:path";function Cv(t,e){if(t!==void 0&&t!==fp())return;let r=e.CLAUDE_CONFIG_DIR?.trim();return r?qO(r):void 0}function It(t,e=process.env){return Cv(t,e)??Pv(t??fp(),".claude")}function pp(t,e=process.env){return Pv(Cv(t,e)??t??fp(),".claude.json")}var Vq=Symbol("absent");var Jq=new Int32Array(new SharedArrayBuffer(4));var T=(t,e,r)=>({inputPerM:t,outputPerM:e,cacheReadPerM:r});function Ce(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 Da=[/claude.*fable|claude.*mythos/i,/claude.*opus/i,/claude.*sonnet/i,/claude.*haiku/i],Ov=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function te(t){return new RegExp(`(?<![\\w.-])${Ov(t)}(?:-\\d{4}-\\d{2}-\\d{2})?(?![\\w.-])`,"i")}function Gt(t){return new RegExp(`(?<![\\w.-])${Ov(t)}(?![\\w.])(?!-(?:[\\w.]+-)*(?:lite|image|tts|live|audio|transcribe|translate)\\b)`,"i")}var Ge={fallback:!0},Nt={geo:!0},mp=t=>({over:272e3,rates:T(t.inputPerM*2,t.outputPerM*1.5,t.cacheReadPerM*2)}),vt=(t,e,r)=>{let n=T(t,e,r);return[n,{long:mp(n)}]},FO=[[Ce("fable|mythos",5,2),T(8,40,.2),{geo:!0,fast:T(16,80,.4)}],[Ce("fable|mythos",5,1),T(10,50,.25),Nt],[Ce("fable|mythos",5),T(10,50,1),Nt],[Ce("opus",5,5),T(4,20,.2),{geo:!0,fast:T(8,40,.4)}],[Ce("opus",5),T(5,25,.5),{geo:!0,fast:T(10,50,1)}],[Ce("opus",4,8),T(5,25,.5),{geo:!0,fast:T(10,50,1)}],[Ce("opus",4,7),T(5,25,.5),Nt],[Ce("opus",4,6),T(5,25,.5),Nt],[Ce("opus",4,5),T(5,25,.5)],[Ce("opus",4,1),T(15,75,1.5)],[Ce("opus",4),T(15,75,1.5)],[Ce("sonnet",5,5),T(2,10,.1),Nt],[Ce("sonnet",5),T(2,10,.2),Nt],[Ce("haiku",5,5),T(.1,.5,.01),{geo:!0,long:{over:1e5,rates:T(.5,2.5,.05)}}],[Ce("haiku",4,5),T(1,5,.1)],[Ce("sonnet",4,6),T(3,15,.3),Nt],[Ce("sonnet",4,5),T(3,15,.3)],[Ce("sonnet",4),T(3,15,.3)],[/claude-3-opus/i,T(15,75,1.5)],[/claude-3-5-haiku/i,T(.8,4,.08)],[/claude-3-haiku/i,T(.25,1.25,.03)],[/claude-3-[57]-sonnet/i,T(3,15,.3)],[Da[0],T(10,50,1),{...Ge,...Nt}],[Da[1],T(5,25,.5),{...Ge,...Nt}],[Da[2],T(3,15,.3),{...Ge,...Nt}],[Da[3],T(1,5,.1),{...Ge,...Nt}],[te("gpt-6-astra"),...vt(10,50,1)],[te("gpt-6-astra-law"),T(10,50,1)],[te("gpt-6.1-sol"),...vt(2,10,.1)],[te("gpt-6.1-terra"),...vt(1,5,.05)],[te("gpt-6-sol"),...vt(2,10,.2)],[te("gpt-6-luna"),...vt(.1,.5,.01)],[te("gpt-6-cyber"),T(20,100,2)],[te("gpt-6-rosalind"),...vt(15,75,1.5)],[te("gpt-rosalind-research"),T(5,25,.5)],[te("gpt-rosalind-discovery"),T(5,25,.5)],[te("gpt-5.6-sol"),T(4,20,.4),{long:mp(T(4,20,.4)),changes:"2026-12-01"}],[te("gpt-5.6"),T(4,20,.4),{long:mp(T(4,20,.4)),changes:"2026-12-01"}],[te("gpt-5.6-terra"),...vt(2,12,.2)],[te("gpt-5.6-luna"),...vt(.2,1.2,.02)],[te("gpt-5.6-cyber"),T(12.5,75,1.25)],[te("gpt-5.5"),...vt(5,30,.5)],[te("gpt-5.5-pro"),...vt(30,180,30)],[te("gpt-5.5-cyber"),T(12.5,75,1.25)],[te("gpt-5.4"),...vt(2.5,15,.25)],[te("gpt-5.4-mini"),T(.75,4.5,.075)],[te("gpt-5.4-nano"),T(.2,1.25,.02)],[te("gpt-5.4-pro"),...vt(30,180,30)],[te("gpt-5.3-codex"),T(1.75,14,.175)],[te("gpt-5.2"),T(1.75,14,.175)],[te("gpt-5.2-pro"),T(21,168,21)],[te("gpt-5.1"),T(1.25,10,.125)],[te("gpt-5"),T(1.25,10,.125)],[te("gpt-5-mini"),T(.25,2,.025)],[te("gpt-5-nano"),T(.05,.4,.005)],[te("gpt-5-pro"),T(15,120,15)],[te("gpt-4.1"),T(2,8,.5)],[te("gpt-4.1-mini"),T(.4,1.6,.1)],[te("gpt-4o"),T(2.5,10,1.25)],[te("gpt-4o-mini"),T(.15,.6,.075)],[te("o3"),T(2,8,.5)],[te("o3-pro"),T(20,80,20)],[te("chat-latest"),T(5,30,.5)],[/gpt-5.*(mini|nano)/i,T(.25,2,.025),Ge],[/gpt-5/i,T(1.25,10,.125),Ge],[/gpt-4o-mini/i,T(.15,.6,.075),Ge],[/gpt-4o|gpt-4\.1/i,T(2.5,10,1.25),Ge],[/gpt-4-turbo/i,T(10,30,10),Ge],[/o[13](-|$)/i,T(2,8,1),Ge],[Gt("gemini-4-argon"),T(2,10,.1),{changes:"2026-12-01",then:T(4,20,.2)}],[Gt("gemini-3.8-flash"),T(.75,3.75,.075),{changes:"2027-01-01",then:T(1.5,7.5,.15)}],[Gt("gemini-3.6-flash"),T(.75,3.75,.075),{changes:"2027-01-01",then:T(1.5,7.5,.15)}],[Gt("gemini-3.5-flash-lite"),T(.3,2.5,.03)],[Gt("gemini-3.1-flash-lite"),T(.25,1.5,.025)],[Gt("gemini-3.1-pro"),T(2,12,.2),{long:{over:2e5,rates:T(4,18,.4)}}],[Gt("gemini-3-flash"),T(.5,3,.05)],[Gt("gemini-2.5-pro"),T(1.25,10,.125),{long:{over:2e5,rates:T(2.5,15,.25)},changes:"2026-12-01",then:T(.75,3.75,.075),routes:"gemini-3.8-flash"}],[Gt("gemini-2.5-flash"),T(.3,2.5,.03)],[Gt("gemini-2.5-flash-lite"),T(.1,.4,.01)],[/gemini-3[.\d]*-flash-lite/i,T(.3,2.5,.03),Ge],[/gemini-3[.\d]*-flash/i,T(.75,3.75,.075),Ge],[/gemini-3[.\d]*-pro/i,T(2,12,.2),Ge],[/gemini.*flash/i,T(.1,.4,.025),Ge],[/gemini.*pro/i,T(1.25,5,.31),Ge]];function HO(t){if(t)return FO.find(([e])=>e.test(t))}function go(t){return HO(t)?.[1]}function jr(t,e){return t/1e6*e.inputPerM}var i9=10/1e3;var a9=Object.freeze({fastUsd:0,geoUsd:0,longUsd:0,webSearchUsd:0,webSearches:0});function hp(t){return t/25e3}function Kt(t){return Number.isFinite(t)?t>=1?`$${t.toFixed(2)}`:t>=.01?`$${t.toFixed(3)}`:`$${t.toFixed(4)}`:"$0.00"}var Av=/(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g,BO="[context-doctor: base64 blob removed \u2014 use file/image APIs instead]";function Iv(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 yo(t){for(let e of t.matchAll(Av))if(Iv(e[0]))return!0;return!1}function gp(t){return t.replace(Av,e=>Iv(e)?BO:e)}import{mkdirSync as g9,readFileSync as aA,writeFileSync as y9}from"node:fs";import{dirname as cA,join as uA}from"node:path";import{appendFileSync as VO,existsSync as yp,mkdirSync as JO,readFileSync as WO,statSync as GO,writeFileSync as KO}from"node:fs";import{homedir as Nv}from"node:os";import{dirname as jv,join as _o}from"node:path";var XO={optimizeSaved:0,optimizeUsd:0,proxySaved:0,proxyUsd:0,proxyRequests:0,checks:0,warnings:0,shrinkage:0};function YO(t){let e={...XO},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 QO(){let t=process.env.XDG_STATE_HOME?.trim();return t?_o(t,"context-doctor"):process.platform==="win32"?_o(process.env.LOCALAPPDATA?.trim()||_o(Nv(),"AppData","Local"),"context-doctor"):_o(Nv(),".local","state","context-doctor")}function eA(){let t=QO();if(yp(t))return t;let e=It();return yp(e)?e:t}function _p(){return process.env.CONTEXT_DOCTOR_HOOK_STATE??_o(eA(),".context-doctor-hook-state.json")}function tA(){return _o(jv(_p()),".context-doctor-ledger.jsonl")}var Mv=100,rA=256*1024,nA=128*1024,oA=500,sA=4*1024;function iA(t){if(typeof t!="string")return;let e=t.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return e.length>Mv?e.slice(0,Mv):e}function La(t){let e=tA();try{if(JO(jv(e),{recursive:!0}),yp(e)&&GO(e).size>rA){let n=WO(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<oA;d--){let m=Buffer.byteLength(n[d])+1;if(!(m>sA)){if(i+m>nA)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=YO(c),l={ts:Date.now(),ev:"rollup",carried:u};KO(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 YC=2,QC=.5,eA=2;function tA(){return XC(GC(dp()),".context-doctor-calibration.json")}function rA(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 nA(){try{return JSON.parse(KC(tA(),"utf8"))}catch{return{}}}function zv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=nA()[rA(t)];if(!e||e.v!==YC||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<QC||r>eA?{factor:1,samples:0}:{factor:r,samples:e.samples}}function sA(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 iA(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 aA(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function Rv(t){return oA("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function cA(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 uA(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=cA(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var Pv=.6;function lA(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 Iv=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function dA(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function fA(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;Iv.lastIndex=0;for(let n of e.matchAll(Iv)){let o=n[2].replace(/\\+$/,"");dA(o)&&r.add(o)}return[...r]}function Cv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=zv(r),o=t.messages.map(y=>({msg:y,tokens:Math.round(It(y.text,r)*n.factor)+ap})),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[sA(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 ~${R(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 ~${R(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=Rv(y.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:y.tokens-ap,message:`Message #${y.msg.index} duplicates the content of message #${$} (~${R(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(H=>H.msg.text.length>=300).sort((H,ve)=>ve.tokens-H.tokens).slice(0,150),x=y.map(H=>uA(H.msg.text)),$=x.map(H=>H.size),N=new Set(a.filter(H=>H.id==="duplicate_content").flatMap(H=>H.messages)),A=y.map((H,ve)=>ve),ce=H=>{for(;A[H]!==H;)H=A[H]=A[A[H]];return H},ue=y.map(()=>({sim:0,partnerTokens:0}));for(let H=0;H<y.length;H++)for(let ve=H+1;ve<y.length;ve++){let At=y[H],Dr=y[ve];if(N.has(At.msg.index)&&N.has(Dr.msg.index))continue;let js=Math.min($[H],$[ve]),Tn=Math.max($[H],$[ve]);if(Tn===0||js/Tn<Pv)continue;let xt=lA(x[H],x[ve]);xt<Pv||(A[ce(H)]=ce(ve),xt>ue[H].sim&&(ue[H]={sim:xt,partnerTokens:Dr.tokens}),xt>ue[ve].sim&&(ue[ve]={sim:xt,partnerTokens:At.tokens}))}let ze=new Map;y.forEach((H,ve)=>{if(ue[ve].sim===0)return;let At=ce(ve);ze.set(At,[...ze.get(At)??[],ve])});for(let H of ze.values()){if(H.length<2)continue;H.sort((bt,Lr)=>y[bt].msg.index-y[Lr].msg.index);let ve=H.slice(1),At=ve.reduce((bt,Lr)=>bt+Math.round(Math.min(y[Lr].tokens,ue[Lr].partnerTokens)*ue[Lr].sim*.9),0),Dr=H.map(bt=>ue[bt].sim),js=Math.round(Math.min(...Dr)*100),Tn=Math.round(Math.max(...Dr)*100),xt=H.map(bt=>y[bt].msg.index),em=js===Tn?`~${Tn}%`:`${js}-${Tn}%`,Jb=ve.reduce((bt,Lr)=>bt+y[Lr].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:At,message:H.length===2?`Messages #${xt[0]} and #${xt[1]} are ${em} similar (~${R(Math.min(y[H[0]].tokens,y[H[1]].tokens))} tokens repeated with different framing).`:`${H.length} messages are ${em} similar to each other (${xt.slice(0,6).map(bt=>`#${bt}`).join(", ")}${xt.length>6?", \u2026":""}): ~${R(Jb)} tokens in the ${ve.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:xt})}}let u=new Map;for(let y of o){if(y.msg.kind!=="tool_call"||!y.msg.toolCallText)continue;let x=Rv(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((N,A)=>l(y[A])?.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 fA(x.msg.toolName,x.msg.toolCallText))y.set($,[...y.get($)??[],x.msg.index]);for(let[x,$]of y){if($.length<3)continue;let N=o.filter(ce=>ce.msg.kind==="tool_result"&&$.some(ue=>ce.msg.index===ue+1)).reduce((ce,ue)=>ce+ue.tokens,0),A=Math.round(N*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:A>4e3?"high":"warn",estSavings:A,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 ~${R(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)po(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 (~${R(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(($,N)=>$+N.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${R(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 ~${R(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:[]}),(Ar(e)==="anthropic"||Ar(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=Na(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:aA(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=iA(a,s),_=fo(e),v;if(_){let y=Or(s,_),x=Or(h,_);v={perCallUsd:y,per1kCallsUsd:y*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:cp(s),ttftSavedSeconds:cp(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 pA}from"node:crypto";var Nv=10,Za={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:Nv};function mA(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 hA(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 Av(t,e,r){let n=Math.round(e*ip("",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,
|
|
71
|
-
`)}var
|
|
72
|
-
`)):(e.push(""),e.push(`Findings (recoverable ~${R(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?` [~${R(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=iA(r[n]);o===void 0?delete r[n]:r[n]=o}VO(e,JSON.stringify({ts:Date.now(),...r})+`
|
|
65
|
+
`)}catch{}}var lA=2,dA=.5,fA=2;function pA(){return uA(cA(_p()),".context-doctor-calibration.json")}function mA(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 hA(){try{return JSON.parse(aA(pA(),"utf8"))}catch{return{}}}function Zv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=hA()[mA(t)];if(!e||e.v!==lA||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<dA||r>fA?{factor:1,samples:0}:{factor:r,samples:e.samples}}function yA(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 _A(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 vA(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function Dv(t){return gA("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function xA(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 bA(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=xA(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var Lv=.6;function wA(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 qv=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function $A(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function kA(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;qv.lastIndex=0;for(let n of e.matchAll(qv)){let o=n[2].replace(/\\+$/,"");$A(o)&&r.add(o)}return[...r]}function Uv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=Zv(r),o=t.messages.map(y=>({msg:y,tokens:Math.round(At(y.text,r)*n.factor)+dp})),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[yA(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 ~${R(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 ~${R(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=Dv(y.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:y.tokens-dp,message:`Message #${y.msg.index} duplicates the content of message #${$} (~${R(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(D=>D.msg.text.length>=300).sort((D,xe)=>xe.tokens-D.tokens).slice(0,150),x=y.map(D=>bA(D.msg.text)),$=x.map(D=>D.size),I=new Set(a.filter(D=>D.id==="duplicate_content").flatMap(D=>D.messages)),U=y.map((D,xe)=>xe),H=D=>{for(;U[D]!==D;)D=U[D]=U[U[D]];return D},ie=y.map(()=>({sim:0,partnerTokens:0}));for(let D=0;D<y.length;D++)for(let xe=D+1;xe<y.length;xe++){let jt=y[D],Ur=y[xe];if(I.has(jt.msg.index)&&I.has(Ur.msg.index))continue;let Ls=Math.min($[D],$[xe]),Pn=Math.max($[D],$[xe]);if(Pn===0||Ls/Pn<Lv)continue;let wt=wA(x[D],x[xe]);wt<Lv||(U[H(D)]=H(xe),wt>ie[D].sim&&(ie[D]={sim:wt,partnerTokens:Ur.tokens}),wt>ie[xe].sim&&(ie[xe]={sim:wt,partnerTokens:jt.tokens}))}let Re=new Map;y.forEach((D,xe)=>{if(ie[xe].sim===0)return;let jt=H(xe);Re.set(jt,[...Re.get(jt)??[],xe])});for(let D of Re.values()){if(D.length<2)continue;D.sort(($t,Fr)=>y[$t].msg.index-y[Fr].msg.index);let xe=D.slice(1),jt=xe.reduce(($t,Fr)=>$t+Math.round(Math.min(y[Fr].tokens,ie[Fr].partnerTokens)*ie[Fr].sim*.9),0),Ur=D.map($t=>ie[$t].sim),Ls=Math.round(Math.min(...Ur)*100),Pn=Math.round(Math.max(...Ur)*100),wt=D.map($t=>y[$t].msg.index),um=Ls===Pn?`~${Pn}%`:`${Ls}-${Pn}%`,iw=xe.reduce(($t,Fr)=>$t+y[Fr].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:jt,message:D.length===2?`Messages #${wt[0]} and #${wt[1]} are ${um} similar (~${R(Math.min(y[D[0]].tokens,y[D[1]].tokens))} tokens repeated with different framing).`:`${D.length} messages are ${um} similar to each other (${wt.slice(0,6).map($t=>`#${$t}`).join(", ")}${wt.length>6?", \u2026":""}): ~${R(iw)} tokens in the ${xe.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:wt})}}let u=new Map;for(let y of o){if(y.msg.kind!=="tool_call"||!y.msg.toolCallText)continue;let x=Dv(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((I,U)=>l(y[U])?.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 kA(x.msg.toolName,x.msg.toolCallText))y.set($,[...y.get($)??[],x.msg.index]);for(let[x,$]of y){if($.length<3)continue;let I=o.filter(H=>H.msg.kind==="tool_result"&&$.some(ie=>H.msg.index===ie+1)).reduce((H,ie)=>H+ie.tokens,0),U=Math.round(I*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:U>4e3?"high":"warn",estSavings:U,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 ~${R(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)yo(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 (~${R(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(($,I)=>$+I.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${R(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 ~${R(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:[]}),(Mr(e)==="anthropic"||Mr(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=Za(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:vA(y.msg.text),toolName:y.msg.toolName})).sort((y,x)=>x.tokens-y.tokens).slice(0,5),h={high:0,warn:1,info:2};a.sort((y,x)=>h[y.severity]-h[x.severity]||x.estSavings-y.estSavings);let g=_A(a,s),_=go(e),v;if(_){let y=jr(s,_),x=jr(g,_);v={perCallUsd:y,per1kCallsUsd:y*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:hp(s),ttftSavedSeconds:hp(g)}}return{totalTokens:s,model:e,contextWindow:m,usagePct:p,messageCount:t.messages.length,categories:i,largestMessages:f,findings:a,totalEstSavings:g,cost:v,sourceFormat:t.sourceFormat,calibration:n.samples>0?n:void 0,parseWarning:t.parseWarning}}import{createHash as SA}from"node:crypto";var Bv=10,qa={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:Bv};function TA(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 EA(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 Fv(t,e,r){let n=Math.round(e*lp("",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 vp(t,e,r=Bv){let n=t-e;return n<=0?0:n<r?n:Math.floor(n/r)*r}function zA(t){return SA("sha1").update(t.trim()).digest("hex")}function vo(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"?vo(e.content):e?.type==="tool_use"?JSON.stringify(e.input??{}):"").join(`
|
|
67
|
+
`):JSON.stringify(t)}function xp(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 bp(t){return typeof t=="string"?yo(t)?gp(t):t:Array.isArray(t)?t.map(bp):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,bp(r)])):t}function RA(t,e,r){let n=Math.round(e*lp(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 PA(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 Hv(t){return t?.role==="tool"?!0:Array.isArray(t?.content)?t.content.some(e=>e?.type==="tool_result"):!1}function Vv(t,e={}){let r={strategies:e.strategies??qa.strategies,keepRecent:e.keepRecent??qa.keepRecent,maxToolResultTokens:e.maxToolResultTokens??qa.maxToolResultTokens,trimBoundaryStep:e.trimBoundaryStep&&e.trimBoundaryStep>0?Math.floor(e.trimBoundaryStep):qa.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 g=o.length-1;g>=0;g--)(!o[g]||typeof o[g]!="object")&&o.splice(g,1);let s=!Array.isArray(n)&&n?.system!=null||o.some(g=>Array.isArray(g?.content)&&g.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=g=>At(g,i),c=Array.isArray(n)?0:(n?.system!=null?a(typeof n.system=="string"?n.system:vo(n.system)):0)+(n?.tools!=null?a(JSON.stringify(n.tools)):0),u=g=>{let _=a(vo(g.content));for(let v of Array.isArray(g.tool_calls)?g.tool_calls:[]){let y=v?.function;y&&(_+=a(`${y.name??""} ${typeof y.arguments=="string"?y.arguments:JSON.stringify(y.arguments??{})}`))}return g.function_call&&(_+=a(`${g.function_call.name??""} ${g.function_call.arguments??""}`)),_},l=c+o.reduce((g,_)=>g+u(_),0),d=[];if(r.strategies.includes("strip-base64")&&o.forEach((g,_)=>{let v=vo(g.content);if(!yo(v))return;let y=a(v),x=xp(g,I=>yo(I)?gp(I):I);Array.isArray(x)&&(x=x.map(I=>I?.type==="tool_use"&&I.input!=null?{...I,input:bp(I.input)}:I));let $=y-a(vo(x));$>50&&(g.content=x,d.push({strategy:"strip-base64",messageIndex:_,tokensSaved:$,note:"Removed inline base64 data"}))}),r.strategies.includes("dedupe")){let g=vp(o.length,r.keepRecent,r.trimBoundaryStep),_=new Map;o.forEach((v,y)=>{let x=0,$,I=xp(v,U=>{if(U.length<300)return U;let H=zA(U),ie=_.get(H);if(ie===void 0)return _.set(H,y),U;if(y>=g)return U;let Re=`[context-doctor: identical to message #${ie} \u2014 content removed]`;return x+=a(U)-a(Re),$??=ie,Re});x<=0||(v.content=I,d.push({strategy:"dedupe",messageIndex:y,tokensSaved:x,note:`Duplicate of message #${$}`}))})}if(r.strategies.includes("trim-tool-results")){let g=vp(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=g||!Hv(_))return;let y=0,x=xp(_,($,I)=>{if(I!=="tool_result")return $;let U=a($);if(U<=r.maxToolResultTokens)return $;let H=RA($,r.maxToolResultTokens,i),ie=a(H);return ie>=U?$:(y+=U-ie,H)});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 g=vp(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=g)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"||EA(o,v,TA(x)))continue;let $=a(JSON.stringify(x.input));if($<=r.maxToolResultTokens)continue;let I=Fv(x.input,r.maxToolResultTokens,i),U=a(JSON.stringify(I));U>=$||(x.input=I,y+=$-U)}for(let x of _.tool_calls??[]){let $=x?.function?.arguments;if(typeof $!="string")continue;let I=a($);if(I<=r.maxToolResultTokens)continue;let U;try{U=JSON.parse($)}catch{continue}if(!U||typeof U!="object"||Array.isArray(U))continue;let H=JSON.stringify(Fv(U,r.maxToolResultTokens,i)),ie=a(H);ie>=I||(x.function.arguments=H,y+=I-ie)}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 g=o.length-f;for(;g<o.length&&Hv(o[g]);)g++;if(o.length-g>=2){PA(o.slice(g));let _=o.slice(p,g),v=_.reduce((x,$)=>x+u($),0);m=_.map((x,$)=>`[${p+$}:${x.role}] ${vo(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,g-p,y),d.push({strategy:"prune-history",messageIndex:p,tokensSaved:v-a(y.content),note:`Pruned ${_.length} old messages`})}}let h=c+o.reduce((g,_)=>g+u(_),0);return{conversation:n,tokensBefore:l,tokensAfter:h,applied:d,prunedDigest:m}}var Jv={system:"System prompt",user:"User messages",assistant:"Assistant replies",tool_calls:"Tool calls",tool_results:"Tool results",other:"Other"},CA={high:"\u2716",warn:"\u25B2",info:"\u2139"};function OA(t,e=28){let r=Math.round(t*e);return"\u2588".repeat(r)+"\u2591".repeat(e-r)}function AA(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 Wv(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: ~${R(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 ${R(n.contextWindow)} window (${n.usagePct.toFixed(1)}%)`:" (unknown window size)";r.push(`Model: ${n.model}${i}`)}n.cost&&r.push(`Cost: ~${Kt(n.cost.perCallUsd)} input per call \xB7 ~${Kt(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])=>Jv[i].length));for(let[i,a]of o){let c=n.totalTokens>0?a/n.totalTokens:0;r.push(`${Jv[i].padEnd(s)} ${OA(c)} ${String(Math.round(c*100)).padStart(3)}% ~${R(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}] ~${R(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 ~${R(u.estSavings)}]`:"";r.push(`${CA[u.severity]} ${e.redact?AA(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 ~${R(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: ~${R(n.totalEstSavings)} tokens (~${u}% of context)`;n.cost&&n.cost.savingsPerCallUsd>0&&(l+=` \u2248 ${Kt(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 IA=2060,NA={code:42,tool_result:56,paste:56,text:80,base64:76,image:0},MA=6.3,jA={paste:2400,code:2400,tool_result:2400,text:900,base64:12e3,image:0},ZA=1500,Gv=2e3,DA=30,wp=400,LA=1e4,qA=6;function UA(t,e){let r=Os[Mr(e)];return t==="code"||t==="tool_result"||t==="base64"?r.code:r.prose}function FA(t,e){if(t.kind==="image")return t.approx_tokens&&t.approx_tokens>0?Math.round(t.approx_tokens):ZA;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*NA[t.kind]:t.approx_words&&t.approx_words>0?t.approx_words*MA:jA[t.kind];return Math.round(r/UA(t.kind,e))}function $p(t){return Math.round(IA/Os[Mr(t)].prose)}var Kv=60;function HA(t){let e=String(t??"").replace(/\s+/g," ").trim()||"unnamed block";return e.length>Kv?e.slice(0,Kv-1)+"\u2026":e}function BA(t){let e=Math.max(0,Math.floor(t.turns||0)),r=(Array.isArray(t.blocks)?t.blocks:[]).map(_=>({..._,label:HA(_?.label)})),n=$p(t.model),o=e*n,s=r.map(_=>({block:_,tokens:FA(_,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 (~${R(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 (~${R(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>=Gv){let x=_.stale?Math.max(0,v-100):Math.round(v*.7);c.push({id:"large_block",severity:v>=4*Gv?"high":"warn",estSavings:x,message:`"${_.label}" (turn ${_.turn}, ${_.kind}) is ~${R(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 (~${R(_)}) 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>=DA){let _=qA*n+wp;c.push({id:"long_history",severity:a>1e5?"high":"warn",estSavings:Math.max(0,a-_),message:`${e} turns: every new message re-reads ~${R(a)}.`,action:`Offer a handoff once: with the user's agreement, write a \u2264${wp}-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 ~${R(_)} of conversation instead, plus the app's own system prompt, which every chat carries.`})}let l=Za(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 ${R(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),h=Math.min(a,Math.max(p,f)),g=go(t.model);return{totalTokens:a,baselineTokens:o,blockTokens:i,turns:e,model:t.model,contextWindow:l,usagePct:d,findings:c,totalEstSavings:h,perTurnUsd:g?jr(a,g):void 0,perTurnCachedUsd:g?a/1e6*g.cacheReadPerM:void 0}}function Xv(t){let e=[],r=t.usagePct!==void 0?` (~${t.usagePct}% of ${R(t.contextWindow)})`:"";return e.push(`Context estimate from sketch: ~${R(t.totalTokens)} tokens${r}, ${t.turns} turns.`),e.push(` ${R(t.baselineTokens)} plain conversation + ${R(t.blockTokens)} in pastes, tool output and images. Estimate, usually within \xB120%.`),t.perTurnUsd!==void 0?e.push(` Re-read on every turn: ${Kt(t.perTurnUsd)} at list price, ${Kt(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 ~${R(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?` [~${R(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>=LA&&e.push(`To recover the ~${R(t.totalEstSavings)}: offer a handoff once. With the user's agreement, call save_handoff (a \u2264${wp}-token brief plus the blocks that must stay exact); a new chat starts from that.`),e.join(`
|
|
73
|
+
`))}function Yv(t,{record:e=!0}={}){let r=BA(t);return e&&La({ev:"check",src:"mcp",tok:r.totalTokens,warn:r.findings.some(n=>n.severity!=="info"),model:t.model}),r}import{spawnSync as bx}from"node:child_process";import{existsSync as wx,lstatSync as dI,readdirSync as fI,readFileSync as pI,realpathSync as Cp,statSync as mI}from"node:fs";import{homedir as Ap}from"node:os";import{basename as Wa,extname as Ga,isAbsolute as hI,join as K,relative as $x,resolve as gI,sep as yI}from"node:path";import{execFile as VA,spawnSync as Qv}from"node:child_process";import{existsSync as ex,mkdtempSync as tx,readFileSync as Sp,rmSync as rx}from"node:fs";import{tmpdir as nx}from"node:os";import{dirname as ox,extname as sx,join as Ua,resolve as JA}from"node:path";var Fa=new Set([".pdf",".docx",".doc",".rtf",".odt",".pptx"]),ix={encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024};function As(t,e){try{let r=Qv(t,e,ix);return r.status===0&&typeof r.stdout=="string"&&r.stdout.trim()?r.stdout:void 0}catch{return}}var ax=["-convert","txt","-noload","-nostore","-stdout"],cx='ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';function WA(t){let e=As("pdftotext",["-enc","UTF-8",t,"-"])??As("pdftotext",[t,"-"]);if(e)return e;let r=Ua(tx(Ua(nx(),"cd-pdf-")),"out.txt");try{Qv("pdftotext",[t,r],ix);let n=ex(r)?Sp(r,"utf8"):"";return n.trim()?n:void 0}catch{return}finally{rx(ox(r),{recursive:!0,force:!0})}}function GA(t,e){let r=As("unzip",["-p",t,...e]);return r?ux(r):void 0}function ux(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 lx(t){return JA(t)}function dx(t){let e=lx(t),r=sx(e).toLowerCase(),n=process.platform==="darwin",o;if(r===".pdf"){if(o=WA(e)?.replace(/\f/g,`
|
|
78
78
|
|
|
79
|
-
`),!n&&
|
|
79
|
+
`),!o&&n&&(o=As("osascript",["-l","JavaScript","-e",cx,e])),!o)return{error:n?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}else{if(n&&r!==".pptx"&&(o=As("textutil",[...ax,e])),!o){let s=r===".docx"?["word/document.xml"]:r===".pptx"?["ppt/slides/*.xml"]:r===".odt"?["content.xml"]:[];s.length&&(o=GA(e,s))}if(!o)return{error:n?"unreadable document":`needs unzip${r===".doc"||r===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}return{text:o}}var Is=2e4,lt=()=>performance.now();function KA(t){return Math.min(t,3e4,Math.max(2e3,t/2))}function kp(t,e,r){let n=Math.ceil(r-lt());if(n<=0)return Promise.resolve({timedOut:!0});let o=Math.ceil(KA(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:lt()>=r-50})},o);try{c=VA(t,e,{encoding:"utf8",timeout:o,killSignal:"SIGKILL",maxBuffer:64*1024*1024,windowsHide:!0},(l,d)=>{if(l)return a({timedOut:lt()>=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 Ha(t,e=lt()+Is){let r=lx(t),n=sx(r).toLowerCase(),o=process.platform==="darwin",s,i=!1,a=async(u,l)=>{if(s||i)return;let d=await kp(u,l,e);d.timedOut?i=!0:s=d.out},c=()=>({error:"not read: the time allowed for reading documents in this call ran out"});if(n===".pdf"){if(await a("pdftotext",["-enc","UTF-8",r,"-"]),await a("pdftotext",[r,"-"]),!s&&!i){let u=Ua(tx(Ua(nx(),"cd-pdf-")),"out.txt");try{(await kp("pdftotext",[r,u],e)).timedOut?i=!0:ex(u)&&(s=Sp(u,"utf8").trim()?Sp(u,"utf8"):void 0)}finally{rx(ox(u),{recursive:!0,force:!0})}}return s=s?.replace(/\f/g,`
|
|
80
80
|
|
|
81
|
-
`),!o&&
|
|
81
|
+
`),!s&&o&&await a("osascript",["-l","JavaScript","-e",cx,r]),s?{text:s}:i?c():{error:o?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}if(o&&n!==".pptx"&&await a("textutil",[...ax,r]),!s&&!i){let u=n===".docx"?["word/document.xml"]:n===".pptx"?["ppt/slides/*.xml"]:n===".odt"?["content.xml"]:[];if(u.length){let l=await kp("unzip",["-p",r,...u],e);l.timedOut?i=!0:l.out&&(s=ux(l.out))}}return s?{text:s}:i?c():{error:o?"unreadable document":`needs unzip${n===".doc"||n===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}import{homedir as fx}from"node:os";import{join as XA,resolve as YA}from"node:path";function Tn(t,e=process.env){if(t===void 0||t===fx()){let r=e.CODEX_HOME?.trim();if(r)return YA(r)}return XA(t??fx(),".codex")}var _I=4e3,vI=400,xI="claude",bI=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"]),wI=new Set([".md",".mdx",".markdown",".rst",".adoc"]);function $I(t,e){let r=Ga(t).toLowerCase();return wI.has(r)?"markdown":bI.has(r)?"code":/^#{1,6}\s+\S/m.test(e)&&!/^#!/.test(e)?"markdown":"prose"}var kI=/^(?![\s})\]]|$)/,vx=/^(\/\*\*?|\*\/?|\/\/|#(?!include|define|!)|"""|\'\'\'|--|@\w+)/;function SI(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()&&kI.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(vx,"").trim()).find(Boolean),m=e==="code"&&(l.find(p=>!vx.test(p))||d)||l[0]||"";u.heading=m.slice(0,80)}return r}var TI=t=>t>=55296&&t<=56319,EI=t=>t>=56320&&t<=57343;function kx(t,e={}){let r=Math.max(50,e.maxChunkTokens??vI),n=e.model??xI,o=$I(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),
|
|
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[
|
|
86
|
-
`);r.push(`PACKED ~${R(t.packedTokens)} of ~${R(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${R(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 ${R(t.budget)}: ${s.map(a=>`${a.id} (~${R(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 ${R(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${R(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),h=f>a/2?f+1:a;TI(m.charCodeAt(h-1))&&EI(m.charCodeAt(h))&&h--,s.push(m.slice(0,h)),i.push(p+1),m=m.slice(h)}s.push(m),i.push(p+1)});let c=[0];for(let m of s)c.push(c[c.length-1]+At(m+`
|
|
84
|
+
`,n));let u=(m,p)=>c[p]-c[m],l=[];for(let m of SI(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 h=p===m.start;l.push({start:p,end:f,heading:h?m.heading:`${m.heading} (cont.)`,hard:h&&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,h=m.end;for(;f<h&&!s[f].trim();)f++;for(;h>f&&!s[h-1].trim();)h--;let g=s.slice(f,h).join(`
|
|
85
|
+
`);return{id:`${t.name}#${p+1}`,source:t.name,startLine:i[f]??f+1,endLine:i[h-1]??h,heading:m.heading,text:g,tokens:At(g,n),score:0}})}var zI=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 Va(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||zI.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 Sx(t,e){let r=[...new Set(Va(e))];if(r.length===0||t.length===0)return;let n=t.map(i=>{let a=[...Va(i.text),...Va(i.heading),...Va(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 Tx(t,e={}){let r=t.map(o=>kx(o,e)),n=e.query?.trim()||void 0;return n&&Sx(r.flat(),n),zx(t,r,n,e)}async function Ex(t,e={}){let r=t.map(s=>kx(s,e)),n=e.query?.trim()||void 0,o;if(n&&(Sx(r.flat(),n),e.semantic)){let{semanticRerank:s}=await Promise.resolve().then(()=>(_x(),yx));o=(await s(r.flat(),n,{model:typeof e.semantic=="string"?e.semantic:void 0})).note}return{...zx(t,r,n,e),semanticNote:o}}function zx(t,e,r,n){let o=Math.max(1,n.budget??_I),s=e.flat(),i=[],a=[],c=[],u=0,l=(p,f)=>{if(!i.includes(p)){if(u+p.tokens>o){c.some(h=>h.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 h=p.get(f);h?l(h,!0):a.push(f)}}if(r){d==="outline"&&(d="query");for(let p of[...s].filter(f=>f.score>0).sort((f,h)=>h.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((h,g)=>h+g.tokens,0),chunks:e[f].length,selected:e[f].filter(h=>i.includes(h)).length}))}}function zp(t,e){let r=t.slice(0,e).map(n=>` ${n.id} L${n.startLine}-${n.endLine} ~${R(n.tokens)} ${n.heading}`);return t.length>e&&r.push(` \u2026 ${t.length-e} more`),r}function Rx(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}: ~${R(t.totalTokens)} tokens in ${t.chunks.length} chunks. Nothing packed: pass a query, or chunk ids from this list.`),r.push(...zp(t.chunks,e)),r.join(`
|
|
86
|
+
`);r.push(`PACKED ~${R(t.packedTokens)} of ~${R(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${R(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 ${R(t.budget)}: ${s.map(a=>`${a.id} (~${R(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 ${R(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${R(a.tokens)} tokens. Raise the budget to at least ${a.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`),r.push(...zp(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(...zp(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 ~${R(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 RI=new Set(["node_modules",".git","dist","build",".next","target","__pycache__",".venv","venv","vendor"]),Ja={files:500,fileBytes:5*1024*1024,totalBytes:50*1024*1024},Px=["-c","core.fsmonitor=false"];function PI(t){try{let e=bx("git",[...Px,"-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&&wx(K(t,r))).sort()}catch{return}}function CI(t){let e=bx("git",[...Px,"-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 Cx(t,e){let r=$x(t,e);return r===""||r!==".."&&!r.startsWith(".."+yI)&&!hI(r)}var OI=new Set([".npmrc",".pypirc",".netrc","_netrc",".git-credentials",".pgpass",".htpasswd",".vault-token",".credentials.json","oauth_creds.json","credentials.tfrc.json"]),AI=[[".codex",["auth.json"]],[".cargo",["credentials","credentials.toml"]],[".gem",["credentials"]]],II=new Set([".pem",".key",".p12",".pfx",".keystore",".jks"]);function xx(t){let e=Wa(t),r=e.toLowerCase();if(r===".env"||r.startsWith(".env."))return"an .env file";if(OI.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(II.has(Ga(r)))return`a key or certificate store (${Ga(r)})`;let n=t.split(/[\\/]+/),o=(n[n.length-2]??"").toLowerCase();if(r==="credentials"&&o===".aws")return"AWS credentials";if(AI.some(([s,i])=>s===o&&i.includes(r)))return`a credentials file (${o}/${e})`}function NI(){let t=Ap(),e=[...[".ssh",".aws",".gnupg",".kube",".docker",".azure",K(".config","gcloud"),K(".config","gh"),K(".config","github-copilot"),K("Library","Keychains"),".password-store"].map(r=>K(t,r)),K(It(),".credentials.json"),K(Tn(),"auth.json"),"/etc/shadow","/etc/gshadow","/etc/sudoers","/etc/master.passwd","/etc/ssh"];return[...new Set([...e,...e.map(Zr)])]}function MI(){let t=Ap(),e=[pp(),K(t,".claude.json"),`${pp()}.backup`,K(t,".claude.json.backup"),K(It(),"backups"),K(t,".claude","backups"),...[It(),K(t,".claude")].flatMap(r=>[K(r,"settings.json"),K(r,"settings.local.json")]),K(t,".cursor","mcp.json"),K(Tn(),"config.toml"),K(t,".codex","config.toml"),K(t,".gemini","settings.json"),K(t,".gemini","config","mcp_config.json"),K(t,".gemini","antigravity","mcp_config.json"),K(t,"Library","Application Support","Claude","claude_desktop_config.json"),K(process.env.APPDATA||K(t,"AppData","Roaming"),"Claude","claude_desktop_config.json"),K(t,".config","Claude","claude_desktop_config.json"),K(process.env.COPILOT_HOME||K(t,".copilot"),"mcp-config.json"),K(t,".copilot","mcp-config.json"),...Op().map(r=>K(r,"Claude","Claude Extensions Settings")),...Ox().map(r=>K(r,"mcp.json")),K(t,".codeium","windsurf","mcp_config.json"),...Op().map(r=>K(r,"zed","settings.json"))];return[...new Set([...e,...e.map(Zr)])]}function Op(){let t=Ap();return[...new Set([K(t,"Library","Application Support"),process.env.APPDATA||K(t,"AppData","Roaming"),process.env.XDG_CONFIG_HOME||K(t,".config"),K(t,".config")])]}function Ox(){return Op().flatMap(t=>["Code","Code - Insiders"].map(e=>K(t,e,"User")))}function jI(){let t=Ox().map(e=>K(e,"profiles"));return[...new Set([...t,...t.map(Zr)])]}function Zr(t){for(let e of[Cp.native,Cp])try{return e(t)}catch{}return gI(t)}function Rp(t,e){let r=process.platform==="darwin"||process.platform==="win32"?n=>n.toLowerCase():n=>n;return e.find(n=>Cx(r(n),r(t)))}function Pp(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 ZI(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?[]:NI(),a=o?[]:MI(),c=o?[]:jI(),u=[],l=[],d=0,m=new Set,p="",f=0,h=!1,g=(_,v)=>{if(u.length>=Ja.files){(v||l.length<20)&&l.push(`${_}: over ${Ja.files} files`);return}let y;try{y=v?mI(_):dI(_)}catch(H){l.push(`${_}: ${Pp(H)}`);return}if(y.isSymbolicLink()){let H;try{H=Zr(Cp(_))}catch{return}Cx(p,H)||l.push(`${_}: symlink pointing outside the folder (not followed)`);return}if(i.length>0){let H=Zr(_),ie=Rp(H,i);if(ie){v&&l.push(`${_}: refused, ${ie} holds credentials${s}`);return}let Re=Rp(H,a)??(Wa(H).toLowerCase()==="mcp.json"?Rp(H,c):void 0);if(Re){l.push(`${_}: refused, ${Re} can hold API keys (an MCP server's env)${s}`);return}}if(y.isDirectory()){let H=Wa(_);if(!v&&RI.has(H))return;if(!v&&H.startsWith(".")){f++;return}let ie=v?PI(_):void 0;if(v&&(h=ie!==void 0),ie){ie.length===0&&CI(_)&&l.push(`${_}: ignored by git (.gitignore); pack reads folders as git does, so ignored files stay out. Name a file to pack it anyway`);for(let D of ie)g(K(_,D),!1);return}let Re;try{Re=fI(_).sort()}catch(D){l.push(`${_}: ${Pp(D)}`);return}for(let D of Re)g(K(_,D),!1);return}if(!y.isFile()){v&&l.push(`${_}: not a regular file`);return}if(!o){let H=xx(_)??xx(Zr(_));if(H){l.push(`${_}: ${H}, likely holding secrets; not packed${s}`);return}}if(!v&&Wa(_).startsWith(".")&&!h){f++;return}let x=Zr(_);if(m.has(x))return;if(y.size>Ja.fileBytes||d+y.size>Ja.totalBytes){l.push(`${_}: too large (${Math.round(y.size/1024)} KB)`);return}let $=$x(n,_),I=$&&!$.startsWith("..")?$:_;if(Fa.has(Ga(_).toLowerCase())){if(r.defer){d+=y.size,m.add(x),u.push({name:I,text:""}),r.defer.push({slot:u.length-1,path:_});return}let H=dx(_);"error"in H?l.push(`${_}: ${H.error}`):(d+=y.size,m.add(x),u.push({name:I,text:H.text}));return}let U;try{U=pI(_)}catch(H){l.push(`${_}: ${Pp(H)}`);return}if(U.subarray(0,8e3).includes(0)){v&&l.push(`${_}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);return}d+=y.size,m.add(x),u.push({name:I,text:U.toString("utf8")})};for(let _ of t){if(!wx(_)){l.push(`${_}: not found`);continue}p=Zr(_),f=0,h=!1,g(_,!0),f>0&&l.push(`${_}: ${f} hidden file(s) or folder(s) not read (name one to pack it)`)}return{sources:u,skipped:l}}async function Ax(t,e={}){let r=[],{sources:n,skipped:o}=ZI(t,{...e,defer:r}),s=lt()+(e.budgetMs??Is),i=new Set;for(let a of r){let c=await Ha(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 DI=["openai/session","openai/subject"];function Nx(t,e=process.env){let r=e.CONTEXT_DOCTOR_RESULTS?.trim().toLowerCase();return r==="full"||r==="compact"?r:t&&typeof t=="object"&&DI.some(n=>typeof t[n]=="string")?"compact":"full"}var xo=t=>Math.round(t);function Mx(t,e){let r=t.findings[0],n=t.totalTokens>0?Math.round(t.totalEstSavings/t.totalTokens*100):0,o=[`~${R(t.totalTokens)} tokens in ${t.messageCount} messages (${t.sourceFormat})${t.usagePct!==void 0?`, ${t.usagePct.toFixed(0)}% of the window`:""}; ~${R(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,xo(c)])),i={total_tokens:xo(t.totalTokens),messages:t.messageCount,recoverable_tokens:xo(t.totalEstSavings),by_category:s,findings:t.findings.slice(0,6).map(a=>`${a.severity}${a.estSavings>0?` ~${R(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:xo(a.tokens),preview:a.preview}))}}}function jx(t,e){let[r,...n]=t.findings,o=[`~${R(t.totalTokens)} tokens, ${t.turns} turns${t.usagePct!==void 0?`, ~${t.usagePct}% of the window`:""} (estimate); ~${R(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?` ~${R(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 LI(t,e){let r=n=>n.slice(n.lastIndexOf("#")+1);return t===e?`#${r(t)}`:`#${r(t)}-${r(e)}`}function qI(t){let e=t.replace(/\s*\(cont\.\)$/,""),r=e.split(" > ");return r[r.length-1]||e}function Zx(t,e,r=120){let n=new Map;for(let d of t.chunks){let m=n.get(d.source)??[],p=qI(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((h,g)=>h+g.tokens,0);return{name:d,tokens:xo(f),sections:p.map(h=>`${LI(h.first,h.last)} ${h.heading} ~${R(h.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}: ~${R(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:xo(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 UI,lstatSync as dr,mkdirSync as Ux,readdirSync as FI,readFileSync as Ip,realpathSync as Ka,rmSync as HI,writeFileSync as Dx}from"node:fs";import{homedir as wo}from"node:os";import{isAbsolute as BI,join as it,relative as VI,sep as JI}from"node:path";var bt={briefTargetTokens:400,briefChars:6e3,titleChars:80,modelChars:100,blocks:20,labelChars:80,blockChars:2e4,totalChars:6e4,kept:100,readBytes:512*1024};function Mp(t=wo()){return it(t,".context-doctor","handoffs")}var WI=/^\d{8}-\d{6}-[a-z0-9]+(?:-[a-z0-9]+)*$/;function Fx(t){return typeof t=="string"&&t.length<=80&&WI.test(t)}function GI(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/g,"")||"handoff"}function KI(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 jp(t){let e=[],r=bt;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 bo="masked by context-doctor",Fe=(t,e,r=()=>!0)=>({kind:t,re:e,replace:n=>r(n[0])?`[${t.replace(/^an? /,"")} ${bo}]`:void 0}),XI=t=>/[0-9]/.test(t)&&/[A-Z]/.test(t)&&/[a-z]/.test(t),YI=[Fe("a private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|$)/g),Fe("an Anthropic key",/(?<![A-Za-z0-9_.-])sk-ant-[A-Za-z0-9_-]{20,}/g),Fe("an OpenAI key",/(?<![A-Za-z0-9_.-])sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}/g,XI),Fe("an AWS access key",/(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g),Fe("a GitHub token",/(?<![A-Za-z0-9])(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/g),Fe("a GitLab token",/(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20,}/g),Fe("a Slack token",/(?<![A-Za-z0-9])xox[abposr]-[A-Za-z0-9-]{10,}/g),Fe("a Slack webhook",/https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9_/-]+/g),Fe("a Google API key",/(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{30,}/g),Fe("an npm token",/(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g),Fe("a Stripe key",/(?<![A-Za-z0-9])(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g),Fe("a Stripe webhook secret",/(?<![A-Za-z0-9])whsec_[A-Za-z0-9]{20,}/g),Fe("a Hugging Face token",/(?<![A-Za-z0-9])hf_[A-Za-z0-9]{30,}/g),Fe("a SendGrid key",/(?<![A-Za-z0-9])SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g),Fe("a Twilio key",/(?<![A-Za-z0-9])SK[0-9a-f]{32}(?![A-Za-z0-9])/g),Fe("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]}:[${bo}]@`},{kind:"a bearer token",re:/\b(Bearer|Basic|Token)(\s+)([A-Za-z0-9._~+/=-]{16,})/g,replace:t=>`${t[1]}${t[2]}[${bo}]`},{kind:"a database password",re:/(\bmysql(?:dump|admin)?\b[^\n]*?\s-p)([^\s-][^\s]*)/g,replace:t=>`${t[1]}[${bo}]`}],Hx="(?: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?)",QI=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${Hx}["']?\\s*[:=]\\s*["']?)([^\\s"'\`,;()<>{}\\[\\]]{3,})(?=$|[\\s"'\`,;)\\]}])`,"gim"),eN=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${Hx}["']?\\s*[:=]\\s*)(["'])([^"'\\n]{3,500})\\2`,"gim"),tN=/^(?: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,rN=/^(?:your[_-]|<|\$\{?|%|\{\{|changeme|placeholder|example|dummy)|(?:[_-]here)(?:[_-]?\d+)?$/i;function Lx(t){return!(tN.test(t)||rN.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 Dr(t){let e=0,r=new Set,n=String(t??"");for(let o of YI)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(eN,(o,s,i,a)=>Lx(a.trim())?(e++,r.add("a password or secret assignment"),`${s}${i}[${bo}]${i}`):o),n=n.replace(QI,(o,s,i)=>Lx(i)?(e++,r.add("a password or secret assignment"),`${s}[${bo}]`):o),{text:n,count:e,kinds:[...r]}}function nN(t){let e=Math.max(0,...(t.match(/`+/g)??[]).map(r=>r.length));return"`".repeat(Math.max(3,e+1))}function Np(t,e){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function oN(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=nN(s.text);o.push("",`### ${Np(s.label,bt.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 sN(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)*$p(e.model),r.nowSource="turns");let n=go(e.model);return n&&(r.afterUsd=jr(r.after,n),r.afterCachedUsd=r.after/1e6*n.cacheReadPerM,r.now!==void 0&&(r.nowUsd=jr(r.now,n),r.nowCachedUsd=r.now/1e6*n.cacheReadPerM)),r}function Bx(t){let e=(o,s)=>o!==void 0?` (${Kt(o)} at list price, ${Kt(s??0)} cached)`:"";if(t.now===void 0)return`A new chat starts from ~${R(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: ~${R(t.now)} tokens re-read on every turn${r}${e(t.nowUsd,t.nowCachedUsd)}.`,`After: ~${R(t.after)} in a new chat${e(t.afterUsd,t.afterCachedUsd)}, plus the app's own system prompt, which every chat carries.`,`Saves ~${R(n)} tokens per further turn${t.now>0?` (${Math.round(n/t.now*100)}%)`:""}; on a subscription that is usage limit.`].join(`
|
|
100
|
+
`)}function Xa(t,e){let r=VI(t,e);return r===""||r!==".."&&!r.startsWith(".."+JI)&&!BI(r)}var En=class extends Error{};function Ya(t,e){let r=i=>{if(e)throw new En(i)},n;try{n=Ka(t)}catch{return r("the home directory cannot be read")}let o=it(t,".context-doctor"),s=Mp(t);for(let i of[o,s]){let a;try{a=dr(i)}catch{if(!e)return;try{Ux(i,{mode:448}),a=dr(i)}catch(u){return r(`cannot create ${xt(i,t)} (${u.code??"error"})`)}}if(a.isSymbolicLink())return r(`${xt(i,t)} is a symbolic link; handoffs are only written to a real folder in the home directory`);if(!a.isDirectory())return r(`${xt(i,t)} is not a folder`);let c;try{c=Ka(i)}catch{return r(`${xt(i,t)} cannot be read`)}if(!Xa(n,c))return r(`${xt(i,t)} resolves outside the home directory`)}return s}function qx(t,e){let r=Date.parse(t.created);return Number.isFinite(r)&&r<=e+6e4?r:0}function iN(t){let e=r=>typeof r.order=="number"&&Number.isFinite(r.order)?r.order:0;return(r,n)=>qx(n,t)-qx(r,t)||e(n)-e(r)||(r.id<n.id?1:r.id>n.id?-1:0)}var aN=0;function Qa(t=wo()){let e=Ya(t,!1);if(!e)return[];let r;try{r=FI(e)}catch{return[]}let n=[];for(let o of r){if(!Fx(o))continue;let s=it(e,o);try{if(!dr(s).isDirectory())continue;let i=it(s,"meta.json");if(!dr(i).isFile())continue;let a=JSON.parse(Ip(i,"utf8"));if(a?.id!==o||typeof a.created!="string")continue;n.push(a)}catch{continue}}return n.sort(iN(Date.now()))}function Zp(t,e=wo()){let r=t==="latest"?Qa(e)[0]?.id:t;if(!Fx(r))return;let n=Ya(e,!1);if(!n)return;let o=it(n,r),s=it(o,"handoff.md");if(Xa(n,s))try{let i=dr(s);if(!i.isFile()||i.size>bt.readBytes||!dr(o).isDirectory()||!dr(it(o,"meta.json")).isFile())return;let a=JSON.parse(Ip(it(o,"meta.json"),"utf8"));return a?.id!==r?void 0:{meta:a,markdown:Ip(s,"utf8")}}catch{return}}function cN(t,e,r){let n=Ya(t,!1);if(!n)return 0;let o=Qa(t).filter(i=>i.id!==r),s=0;for(let i of o.slice(Math.max(0,e-1))){let a=it(n,i.id);try{if(!Xa(n,a)||!dr(a).isDirectory()||!dr(it(a,"meta.json")).isFile()||!Xa(Ka(n),Ka(a)))continue;HI(a,{recursive:!0,force:!0}),s++}catch{}}return s}function lr(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 Vx(t,{home:e=wo(),now:r=new Date,store:n=!0}={}){let o=jp(t);if(o.length)throw new Error(o.join(" "));let s=new Set,i=0,a=x=>{let $=Dr(x);return i+=$.count,$.kinds.forEach(I=>s.add(I)),$.text},c=a(lr(t.brief)),u=Np(t.title?.trim()?a(lr(t.title,{keepNewlines:!1})):c.split(`
|
|
102
|
+
`).find(x=>x.trim())?.replace(/^#+\s*/,"")||"handoff",bt.titleChars),l=(t.verbatim??[]).map(x=>({label:Np(a(lr(x.label,{keepNewlines:!1})),bt.labelChars),text:a(lr(x.text))})),d=t.model===void 0?void 0:a(lr(String(t.model),{keepNewlines:!1})).slice(0,bt.modelChars)||void 0,m=r.toISOString(),p=oN(u,m,c,l),f=`${KI(r)}-${GI(u)}`,h={id:f,title:u,created:m,model:d,tokens:At(p,d),briefTokens:At(c,d),blocks:l.map(x=>({label:x.label,tokens:At(x.text,d)})),masked:i,order:Date.now()*1e3+aN++%1e3},g=sN(h.tokens,{...t,model:d});if(!n)return{meta:h,markdown:p,maskedKinds:[...s],math:g,rotated:0};let _=Ya(e,!0),v="";for(let x=1;x<=200;x++){let $=x===1?f:`${f}-${x}`,I=it(_,$);try{Ux(I,{mode:448}),h.id=$,v=I;break}catch(U){if(U.code!=="EEXIST")throw new En(`cannot create a handoff folder in ${xt(_,e)} (${U.code??"error"})`)}}if(!v)throw new En(`too many handoffs saved in the same second in ${xt(_,e)}`);try{Dx(it(v,"handoff.md"),p,{mode:384,flag:"wx"}),Dx(it(v,"meta.json"),JSON.stringify(h,null,2)+`
|
|
103
|
+
`,{mode:384,flag:"wx"})}catch(x){throw new En(`cannot write the handoff in ${xt(v,e)} (${x.code??"error"})`)}let y=cN(e,bt.kept,h.id);if(!UI(it(v,"handoff.md")))throw new En(`the handoff in ${xt(v,e)} is gone`);return{meta:h,markdown:p,dir:v,maskedKinds:[...s],math:g,rotated:y}}function xt(t,e=wo()){return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function Jx(t,e=wo()){return e&&e.length>1?String(t).split(e).join("~"):String(t)}import{lookup as uN}from"node:dns";import{request as lN}from"node:http";import{request as dN}from"node:https";import{isIP as Gx}from"node:net";import{mkdtempSync as fN,rmSync as pN,writeFileSync as mN}from"node:fs";import{tmpdir as hN}from"node:os";import{extname as gN,join as Wx}from"node:path";var Ke={files:10,bytes:5*1024*1024,totalBytes:20*1024*1024,timeoutMs:2e4,redirects:3,callMs:6e4},yN={"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 Kx(t=process.env){return t.CONTEXT_DOCTOR_TEST_LOOPBACK_FILES==="1"}function Dp(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 _N(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 Xx(t){let e=t.replace(/^\[|\]$/g,""),r=Gx(e);if(r===4)return Dp(e);if(r===6){let n=_N(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:Dp(`${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?Dp(`${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 Lp(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^127\./.test(e)}function vN(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=Kx(e)&&Lp(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"}:Gx(n)&&Xx(n)?{error:"a private or loopback address"}:{url:r}}function xN(t){return(e,r,n)=>{uN(e,r,(o,s,i)=>{if(o)return n(o);if((Array.isArray(s)?s:[{address:s,family:i??4}]).find(u=>Xx(u.address)&&!(t&&Lp(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 bN(t,e,r,n){return new Promise(o=>{let s=Kx(e)&&Lp(t.hostname),i=t.protocol==="https:"?dN:lN,a=!1,c=m=>{a||(a=!0,clearTimeout(l),o(m))},u=Math.max(1,r-lt()),l=setTimeout(()=>{d.destroy(),c({status:0,error:"timed out"})},u),d=i(t,{method:"GET",lookup:xN(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<Ke.bytes?`over the ${Ke.totalBytes/1024/1024} MB total for one call`:`too large (over ${Ke.bytes/1024/1024} MB)`,h=Number(m.headers["content-length"]);if(Number.isFinite(h)&&h>n)return d.destroy(),c({status:p,error:f});let g=[],_=0;m.on("data",v=>{if(_+=v.length,_>n){d.destroy(),c({status:p,error:f});return}g.push(v)}),m.on("end",()=>c({status:p,body:Buffer.concat(g)})),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 wN(t,e=process.env,{deadline:r,maxBytes:n=Ke.bytes}={}){let o=Math.min(lt()+Ke.timeoutMs,r??1/0),s=Math.max(0,Math.min(n,Ke.bytes)),i=t;for(let a=0;a<=Ke.redirects;a++){let c=vN(i,e);if("error"in c)return{error:a===0?`refused: ${c.error}`:`refused a redirect: ${c.error}`};if(lt()>=o)return{error:"timed out"};let u=await bN(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 ${Ke.redirects} redirects`}}function $N(t){return((t.file_name??"").split(/[\\/]/).pop()?.replace(/[^\w.\- ]+/g,"_").trim()||String(t.file_id||"file").replace(/[^\w.-]+/g,"_")).slice(0,80)}async function Yx(t,e=process.env){let r=[],n=[],o=0,s=lt()+Ke.callMs;for(let i of t.slice(0,Ke.files)){let a=$N(i);if(lt()>=s){n.push(`${a}: not read, the ${Ke.callMs/1e3} s allowed for one call ran out`);continue}let c=await wN(String(i.download_url??""),e,{deadline:s,maxBytes:Ke.totalBytes-o});if("error"in c){n.push(`${a}: ${c.error}`);continue}o+=c.body.length;let u=gN(a).toLowerCase(),l=Fa.has(u)?u:yN[(i.mime_type??"").split(";")[0].trim().toLowerCase()];if(l){let d=fN(Wx(hN(),"cd-file-"));try{let m=Wx(d,`upload${l}`);mN(m,c.body,{mode:384});let p=await Ha(m,Math.min(lt()+Is,s));"error"in p?n.push(`${a}: ${p.error}`):r.push({name:a,text:p.text})}finally{pN(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>Ke.files&&n.push(`${t.length-Ke.files} more file(s): at most ${Ke.files} per call`),{sources:r,skipped:n}}import{isIP as kN}from"node:net";var Qx={bodyBytes:10*1024*1024,bodyMs:3e4},SN=["https://chatgpt.com","https://chat.openai.com"],eb=["localhost","127.0.0.1","::1"];function ec(t){return(t??"").split(",").map(e=>e.trim()).filter(Boolean)}function tc(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 tb(t,e,r,n=process.env,o={}){let s=[...ec(e),...ec(n.CONTEXT_DOCTOR_ALLOWED_HOSTS)],i=new Set([...SN,...ec(r),...ec(n.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map(u=>u.toLowerCase().replace(/\/+$/,"")));if(s.includes("*"))return{hosts:"*",origins:i,ipLiterals:o.ipLiterals};let a=tc(t),c=new Set([...eb,...s.map(tc)]);return a&&a!=="0.0.0.0"&&a!=="::"&&c.add(a),{hosts:c,origins:i,ipLiterals:o.ipLiterals}}function rb(t,e){if(t.hosts!=="*"){let n=tc(String(e.host??""));if(!n)return"the request has no Host header";if(!t.hosts.has(n)&&!(t.ipLiterals&&kN(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=tc(o.host);if(!(eb.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 nb(t,e=Qx.bodyBytes,r=Qx.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 ON,existsSync as rc,openSync as AN,readdirSync as nc,readSync as IN,statSync as Fp}from"node:fs";import{homedir as Hp}from"node:os";import{basename as ub,dirname as NN,isAbsolute as MN,join as zn,resolve as lb}from"node:path";import{readdirSync as MU,readFileSync as jU,statSync as ZU,existsSync as DU,openSync as TN,readSync as EN,closeSync as zN}from"node:fs";import{StringDecoder as RN}from"node:string_decoder";import{homedir as PN}from"node:os";import{join as CN}from"node:path";function ob(t,e=PN()){return CN(It(e),"projects",t.replace(/[^A-Za-z0-9]/g,"-"))}function qp(t,e){let r=TN(t,"r"),n=new RN("utf8"),o=Buffer.allocUnsafe(4*1024*1024),s="";try{for(;;){let i=EN(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{zN(r)}}var Ns=2e5,jN=8e6,sb=16384;function Up(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 ZN(t){if(t.length<=Ns)return{whole:t};let e=Ns/2;return{head:t.slice(0,e+sb),tail:t.slice(-(e+sb)),length:t.length}}var ib=t=>"whole"in t?t.whole.length:Ns;function DN(t){if("whole"in t){let a=Dr(lr(t.whole));return{text:a.text,masked:a.count}}let e=Ns/2,r=Dr(lr(t.head)),n=lr(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=Dr(n);return{text:`${r.text.slice(0,e)}
|
|
106
|
+
[\u2026 ${t.length-Ns} characters \u2026]
|
|
107
|
+
${i.text.slice(-e)}`,masked:r.count+i.count+o}}function ab(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 LN(t,e=jN){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 h=f.trim();if(!h)return;s++;let g=ZN(h);for(r.push({n:s,at:typeof m=="string"?m:void 0,kind:p,raw:g,compactedBy:0,c:i}),o+=ib(g);o>e&&n<r.length-1;)o-=ib(r[n].raw),r[n].raw={whole:""},n++;n>1024&&(r.splice(0,n),n=0),c.size>1e5&&c.clear()};qp(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 g=p.payload;if(p.type==="compacted"||g.type==="context_compacted"){i++;return}if(p.type!=="response_item")return;if(g.type==="message"&&(g.role==="user"||g.role==="assistant"))return u(p.timestamp,g.role,Up(g.content));if(g.type==="function_call"||g.type==="custom_tool_call"||g.type==="local_shell_call"){let _=String(g.name??(g.type==="local_shell_call"?"shell":g.type));typeof g.call_id=="string"&&c.set(g.call_id,_);let v=g.arguments??g.input??g.action;if(typeof v=="string")try{v=JSON.parse(v)}catch{}return u(p.timestamp,"tool call",ab(_,v))}return/_call_output$/.test(String(g.type))?u(p.timestamp,`tool output (${c.get(g.call_id)??"tool"})`,Up(g.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 h=f.content;if(p.type==="user"){if(typeof h=="string")return u(p.timestamp,"user",h);if(!Array.isArray(h))return;for(let g of h)g?.type==="tool_result"?u(p.timestamp,`tool output (${c.get(g.tool_use_id)??"tool"})`,Up(g.content)):typeof g?.text=="string"&&u(p.timestamp,"user",g.text);return}if(p.type==="assistant"&&Array.isArray(h))for(let g of h)g?.type==="text"?u(p.timestamp,"assistant",String(g.text??"")):g?.type==="tool_use"&&(typeof g.id=="string"&&c.set(g.id,String(g.name??"tool")),u(p.timestamp,"tool call",ab(String(g.name??"tool"),g.input)))});let l=0;return{entries:r.slice(n).map(({c:m,raw:p,...f})=>{let h=DN(p);return l+=h.masked,{...f,text:h.text,compactedBy:i-m}}),total:s,compactions:i,masked:l}}function qN(t){try{let e=AN(t,"r");try{let r=Buffer.alloc(65536),n=IN(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{ON(e)}}catch{return}}function cb(t){let e;try{for(let r of nc(t)){if(!r.endsWith(".jsonl"))continue;let n=zn(t,r),o=Fp(n).mtimeMs;(!e||o>e.at)&&(e={path:n,at:o})}}catch{}return e}function UN(t,e){let r=zn(Tn(e),"sessions");if(!rc(r))return;let n=Date.now()-7*864e5,o=[],s=(i,a)=>{let c;try{c=nc(i)}catch{return}for(let u of c){let l=zn(i,u),d;try{d=Fp(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=>qN(i.path)===lb(t))}function db(t=process.env,e=process.cwd(),r=Hp(),n={}){let o=t.CLAUDE_CODE_SESSION_ID?.trim();if(o&&/^[\w.-]+$/.test(o)){let a=FN(o,r);if(a&&a.endsWith(`${o}.jsonl`)){if(n.envMayBeStale){let c=cb(NN(a));if(c&&c.path!==a&&c.at>Fp(a).mtimeMs)return{path:c.path,how:`the newest Claude Code session in this project (${ub(c.path,".jsonl")}; CLAUDE_CODE_SESSION_ID still names ${o}, as after /clear)`}}return{path:a,how:`this Claude Code session (${o})`}}}let s=cb(ob(e,r)),i=UN(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 FN(t,e=Hp()){if((MN(t)||t.includes("/")||t.includes("\\"))&&rc(t))return lb(t);if(!/^[\w.-]+$/.test(t))return;let r=zn(It(e),"projects"),n=[];try{n=nc(r)}catch{}for(let a of n){let c=zn(r,a,`${t}.jsonl`);if(rc(c))return c}let o=zn(Tn(e),"sessions"),s,i=(a,c)=>{if(s)return;let u;try{u=nc(a)}catch{return}for(let l of u){let d=zn(a,l);if(l.endsWith(".jsonl")&&l.includes(t)){s=d;return}c<3&&!l.includes(".")&&i(d,c+1)}};return rc(o)&&i(o,0),s}function fb(t,e,r={}){let n=LN(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=Tx(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 pb(t,e=Hp()){let r=ub(t.path).replace(/\.jsonl$/,"").slice(0,48),n=[`RECALL from ${t.how}${t.how.includes(r)?"":` (${r})`}: ${t.entries} entries, ~${R(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 ~${R(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 ZM=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],DM={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function cm(t,e,r){if(Nx(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 nw(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 O&&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 ow({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new Aa({name:"context-doctor",version:"0.46.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=g=>({isError:!0,content:[{type:"text",text:g}]});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[g,_]of a.blocks.entries()){if(_.turn>1e5)return m(`sketch.blocks[${g}].turn is ${_.turn}; the most that makes sense is 100000.`);if(_.repeated!==void 0&&(_.repeated<1||_.repeated>1e3))return m(`sketch.blocks[${g}].repeated is ${_.repeated}; give 1 to 1000.`);for(let[v,y]of Object.entries(DM)){let x=_[v];if(typeof x=="number"&&!(x>0))return m(`sketch.blocks[${g}].${v} is ${x}; a size is above 0.`);if(typeof x=="number"&&x>y)return m(`sketch.blocks[${g}].${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=Yv({...a,model:a.model??c},{record:!t}),h=p+Xv(f);return cm(u?._meta,h,()=>{let g=jx(f,h);return{...g,text:p+g.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=Uv(Ev(i),c),d=Wv(l);return cm(u?._meta,d,()=>Mx(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(ZM)).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 nw(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=Vv(i,{strategies:a,keepRecent:c,maxToolResultTokens:u}),m=d.tokensBefore-d.tokensAfter;m>0&&!t&&La({ev:"optimize",src:"mcp",saved:m,model:d.conversation?.model});let p=`Saved ~${R(m)} tokens (${R(d.tokensBefore)} \u2192 ${R(d.tokensAfter)}) via ${d.applied.length} change(s):
|
|
112
112
|
`+d.applied.map(_=>`- [${_.strategy}] message #${_.messageIndex}: ${_.note} (~${R(_.tokensSaved)})`).join(`
|
|
113
|
-
`)+l,f=1e5,
|
|
113
|
+
`)+l,f=1e5,h=JSON.stringify(d.conversation),g=[{type:"text",text:p},h.length<=f?{type:"text",text:h}:{type:"text",text:`[optimized conversation is ${h.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&&g.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:
|
|
117
|
-
Skipped: ${v.slice(0,10).join("; ")}${v.length>10?` (+${v.length-10} more)`:""}`:"",$=
|
|
116
|
+
`+d.prunedDigest}),{content:g}});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:h}=i,g=I=>({content:[{type:"text",text:I}],isError:!0});if((c?.length??0)>50)return g(`${c.length} paths; pass at most 50 (a folder counts as one).`);if((m?.length??0)>200)return g(`${m.length} ids; ask for at most 200.`);if(d!==void 0&&d>2e5)return g(`max_tokens ${d}; the most is 200000.`);if(c?.length&&!r)return g("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 Ax(c):{sources:[],skipped:[]};if(t&&h?.length){let I=await Yx(h);_.push(...I.sources),v.push(...I.skipped)}if(u&&_.push({name:"text",text:u}),_.length===0)return g(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 Ex(_,{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)`:""}`:"",$=Rx(y)+x;return y.mode!=="outline"?{content:[{type:"text",text:$}]}:cm(a?._meta,$,()=>{let I=Zx(y,$);return{...I,text:I.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 ${bt.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${bt.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=jp(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 nw(n,`Save a handoff of this chat on this computer (${xt(Mp())}) to start a new chat from? "${Dr(c??i.split(`
|
|
120
|
+
`)[0]).text.slice(0,80)}"${y?`, with ${y} verbatim block(s): ${Dr(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 h;try{h=Vx({...m,verbatim:f},{store:e})}catch(y){let x=Jx(y.message);return{isError:!0,content:[{type:"text",text:`Not saved: ${t?"the server could not store the handoff":x}.`}]}}let g=h.meta,_=`brief ~${R(g.briefTokens)}${g.blocks.length?`, ${g.blocks.length} verbatim block(s) ~${R(g.blocks.reduce((y,x)=>y+x.tokens,0))}`:""}`,v=[h.dir?`Handoff saved: ${g.id} (~${R(g.tokens)} tokens: ${_}) in ${xt(h.dir)}.`:`Handoff ready (~${R(g.tokens)} tokens: ${_}), not stored: this server runs over HTTP and keeps nothing.`];return g.masked>0&&v.push(`Masked ${g.masked} secret-looking string(s) (${h.maskedKinds.join(", ")}) before saving; the user re-adds them by hand in the new chat if needed.`),g.briefTokens>bt.briefTargetTokens&&v.push(`The brief is ~${g.briefTokens} tokens; the target is \u2264${bt.briefTargetTokens}. It is saved; tighter is cheaper next time.`),v.push(Bx(h.math)),h.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:Zp("latest")?.markdown??i}]})),n.registerResource("handoff",new Ia("handoff://{id}",{list:async()=>({resources:Qa().slice(0,20).map(a=>({uri:`handoff://${a.id}`,name:a.id,title:a.title,description:`~${R(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=Zp(String(Array.isArray(c)?c[0]:c));if(!u)throw new O(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=db(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=fb(c.path,i,{budget:u,how:c.how});return{content:[{type:"text",text:pb(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:[...sw.general,...i&&i!=="general"?sw[i]:[]].map((c,u)=>`${u+1}. ${c}`).join(`
|
|
122
|
+
`)}]})),LM(n),n}function LM(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 sw={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 qM(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 fc=process.argv.slice(2);if(fc.includes("--http")){let t=a=>{let c=fc.indexOf(a);return c>=0?fc[c+1]:void 0},e=Number(t("--port"))>0?Number(t("--port")):8808,r=t("--host")??"127.0.0.1",n=fc.includes("--store-handoffs"),o=tb(r,t("--allowed-hosts"),t("--allowed-origins")),{createServer:s}=await import("node:http"),{StreamableHTTPServerTransport:i}=await Promise.resolve().then(()=>(rw(),tw));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=rb(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 nb(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"))&&qM(a,"accept","application/json, text/event-stream");let h=ow({http:!0,storeHandoffs:n}),g=new i({sessionIdGenerator:void 0,enableJsonResponse:!f});c.on("close",()=>{g.close(),h.close()}),await h.connect(g),await g.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 Ma;await ow().connect(t)}
|