From 56167c47a27678d54308a79a6218c7249b522b0c Mon Sep 17 00:00:00 2001 From: Alex Newman Date: Sat, 18 Oct 2025 20:45:41 -0400 Subject: [PATCH] feat: Implement Claude-mem MCP Search Server with session and observation search capabilities - Added search functionality for observations and sessions using full-text search. - Implemented formatting functions for search results with citations. - Created multiple tools for searching by various criteria including concept, file, type, and advanced search. - Integrated structured filters and pagination options for search queries. - Established error handling for search operations and server initialization. --- plugin/.mcp.json | 8 + plugin/hooks/hooks.json | 10 +- plugin/scripts/search-server.js | 137 +++++++ plugin/scripts/worker.js | 194 ---------- scripts/build-hooks.js | 34 +- scripts/replay-transcript.ts | 4 +- src/bin/hooks/worker.ts | 2 +- src/sdk/worker.ts | 2 +- src/servers/search-server.ts | 465 +++++++++++++++++++++++ test-socket.js | 18 - test-worker.sh | 48 --- tests/database-schema.test.ts | 203 ---------- tests/hooks-database-integration.test.ts | 253 ------------ tests/sdk-prompts-parser.test.ts | 336 ---------------- tests/session-lifecycle.test.ts | 286 -------------- 15 files changed, 651 insertions(+), 1349 deletions(-) create mode 100644 plugin/.mcp.json create mode 100755 plugin/scripts/search-server.js delete mode 100755 plugin/scripts/worker.js create mode 100644 src/servers/search-server.ts delete mode 100644 test-socket.js delete mode 100755 test-worker.sh delete mode 100644 tests/database-schema.test.ts delete mode 100644 tests/hooks-database-integration.test.ts delete mode 100644 tests/sdk-prompts-parser.test.ts delete mode 100644 tests/session-lifecycle.test.ts diff --git a/plugin/.mcp.json b/plugin/.mcp.json new file mode 100644 index 00000000..4a7a486c --- /dev/null +++ b/plugin/.mcp.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "claude-mem-search": { + "type": "stdio", + "command": "${CLAUDE_PLUGIN_ROOT}/scripts/search-server.js" + } + } +} diff --git a/plugin/hooks/hooks.json b/plugin/hooks/hooks.json index 63838f0f..ff17b567 100644 --- a/plugin/hooks/hooks.json +++ b/plugin/hooks/hooks.json @@ -6,7 +6,7 @@ "hooks": [ { "type": "command", - "command": "bun ${CLAUDE_PLUGIN_ROOT}/scripts/context-hook.js", + "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/context-hook.js", "timeout": 180000 } ] @@ -17,7 +17,7 @@ "hooks": [ { "type": "command", - "command": "bun ${CLAUDE_PLUGIN_ROOT}/scripts/new-hook.js", + "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/new-hook.js", "timeout": 60000 } ] @@ -29,7 +29,7 @@ "hooks": [ { "type": "command", - "command": "bun ${CLAUDE_PLUGIN_ROOT}/scripts/save-hook.js", + "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/save-hook.js", "timeout": 180000 } ] @@ -40,7 +40,7 @@ "hooks": [ { "type": "command", - "command": "bun ${CLAUDE_PLUGIN_ROOT}/scripts/summary-hook.js", + "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/summary-hook.js", "timeout": 60000 } ] @@ -51,7 +51,7 @@ "hooks": [ { "type": "command", - "command": "bun ${CLAUDE_PLUGIN_ROOT}/scripts/cleanup-hook.js", + "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/cleanup-hook.js", "timeout": 60000 } ] diff --git a/plugin/scripts/search-server.js b/plugin/scripts/search-server.js new file mode 100755 index 00000000..c68f3517 --- /dev/null +++ b/plugin/scripts/search-server.js @@ -0,0 +1,137 @@ +#!/usr/bin/env node +#!/usr/bin/env node +var Bi=Object.defineProperty;var Qi=(s,t)=>{for(var r in t)Bi(s,r,{get:t[r],enumerable:!0})};import*as ie from"fs";import{stat as No}from"fs/promises";import{join as Ec}from"path";import{homedir as wc}from"os";import{dirname as Rc,join as On}from"path";import{cwd as dn}from"process";import{randomUUID as Tc}from"crypto";var Gi=Object.create,Ji=Object.getPrototypeOf,cs=Object.defineProperty,Wi=Object.getOwnPropertyNames,Ki=Object.prototype.hasOwnProperty,Yi=(s,t,r)=>{r=s!=null?Gi(Ji(s)):{};let e=t||!s||!s.__esModule?cs(r,"default",{value:s,enumerable:!0}):r;for(let n of Wi(s))Ki.call(e,n)||cs(e,n,{get:()=>s[n],enumerable:!0});return e},ce=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports),Xi=(s,t)=>{for(var r in t)cs(s,r,{get:t[r],enumerable:!0,configurable:!0,set:e=>t[r]=()=>e})},eo=ce((s,t)=>{(function(r,e){typeof s=="object"&&typeof t<"u"?e(s):typeof define=="function"&&define.amd?define(["exports"],e):e(r.URI=r.URI||{})})(s,function(r){function e(){for(var v=arguments.length,h=Array(v),S=0;S1){h[0]=h[0].slice(0,-1);for(var C=h.length-1,I=1;I= 0x80 (not a basic code point)","invalid-input":"Invalid input"},j=d-p,w=Math.floor,k=String.fromCharCode;function D(v){throw new RangeError(F[v])}function z(v,h){for(var S=[],C=v.length;C--;)S[C]=h(v[C]);return S}function H(v,h){var S=v.split("@"),C="";S.length>1&&(C=S[0]+"@",v=S[1]),v=v.replace(N,".");var I=v.split("."),W=z(I,h).join(".");return C+W}function Y(v){for(var h=[],S=0,C=v.length;S=55296&&I<=56319&&S>1,h+=w(h/S);h>j*_>>1;I+=d)h=w(h/j);return w(I+(j+1)*h/(h+g))},ue=function(h){var S=[],C=h.length,I=0,W=O,me=$,we=h.lastIndexOf(E);we<0&&(we=0);for(var ke=0;ke=128&&D("not-basic"),S.push(h.charCodeAt(ke));for(var Ze=we>0?we+1:0;Ze=C&&D("invalid-input");var De=se(h.charCodeAt(Ze++));(De>=d||De>w((b-I)/Me))&&D("overflow"),I+=De*Me;var Re=Ve<=me?p:Ve>=me+_?_:Ve-me;if(Dew(b/Le)&&D("overflow"),Me*=Le}var Oe=S.length+1;me=le(I-xe,Oe,xe==0),w(I/Oe)>b-W&&D("overflow"),W+=w(I/Oe),I%=Oe,S.splice(I++,0,W)}return String.fromCodePoint.apply(String,S)},Be=function(h){var S=[];h=Y(h);var C=h.length,I=O,W=0,me=$,we=!0,ke=!1,Ze=void 0;try{for(var xe=h[Symbol.iterator](),Me;!(we=(Me=xe.next()).done);we=!0){var Ve=Me.value;Ve<128&&S.push(k(Ve))}}catch(rr){ke=!0,Ze=rr}finally{try{!we&&xe.return&&xe.return()}finally{if(ke)throw Ze}}var De=S.length,Re=De;for(De&&S.push(E);Re=I&<w((b-W)/pt)&&D("overflow"),W+=(Le-I)*pt,I=Le;var kt=!0,tr=!1,Nt=void 0;try{for(var fa=h[Symbol.iterator](),$a;!(kt=($a=fa.next()).done);kt=!0){var Aa=$a.value;if(Aab&&D("overflow"),Aa==I){for(var Mr=W,Lr=d;;Lr+=d){var Dt=Lr<=me?p:Lr>=me+_?_:Lr-me;if(Mr>6|192).toString(16).toUpperCase()+"%"+(h&63|128).toString(16).toUpperCase():S="%"+(h>>12|224).toString(16).toUpperCase()+"%"+(h>>6&63|128).toString(16).toUpperCase()+"%"+(h&63|128).toString(16).toUpperCase(),S}function M(v){for(var h="",S=0,C=v.length;S=194&&I<224){if(C-S>=6){var W=parseInt(v.substr(S+4,2),16);h+=String.fromCharCode((I&31)<<6|W&63)}else h+=v.substr(S,6);S+=6}else if(I>=224){if(C-S>=9){var me=parseInt(v.substr(S+4,2),16),we=parseInt(v.substr(S+7,2),16);h+=String.fromCharCode((I&15)<<12|(me&63)<<6|we&63)}else h+=v.substr(S,9);S+=9}else h+=v.substr(S,3),S+=3}return h}function X(v,h){function S(C){var I=M(C);return I.match(h.UNRESERVED)?I:C}return v.scheme&&(v.scheme=String(v.scheme).replace(h.PCT_ENCODED,S).toLowerCase().replace(h.NOT_SCHEME,"")),v.userinfo!==void 0&&(v.userinfo=String(v.userinfo).replace(h.PCT_ENCODED,S).replace(h.NOT_USERINFO,P).replace(h.PCT_ENCODED,a)),v.host!==void 0&&(v.host=String(v.host).replace(h.PCT_ENCODED,S).toLowerCase().replace(h.NOT_HOST,P).replace(h.PCT_ENCODED,a)),v.path!==void 0&&(v.path=String(v.path).replace(h.PCT_ENCODED,S).replace(v.scheme?h.NOT_PATH:h.NOT_PATH_NOSCHEME,P).replace(h.PCT_ENCODED,a)),v.query!==void 0&&(v.query=String(v.query).replace(h.PCT_ENCODED,S).replace(h.NOT_QUERY,P).replace(h.PCT_ENCODED,a)),v.fragment!==void 0&&(v.fragment=String(v.fragment).replace(h.PCT_ENCODED,S).replace(h.NOT_FRAGMENT,P).replace(h.PCT_ENCODED,a)),v}function de(v){return v.replace(/^0*(.*)/,"$1")||"0"}function L(v,h){var S=v.match(h.IPV4ADDRESS)||[],C=R(S,2),I=C[1];return I?I.split(".").map(de).join("."):v}function V(v,h){var S=v.match(h.IPV6ADDRESS)||[],C=R(S,3),I=C[1],W=C[2];if(I){for(var me=I.toLowerCase().split("::").reverse(),we=R(me,2),ke=we[0],Ze=we[1],xe=Ze?Ze.split(":").map(de):[],Me=ke.split(":").map(de),Ve=h.IPV4ADDRESS.test(Me[Me.length-1]),De=Ve?7:8,Re=Me.length-De,Le=Array(De),Oe=0;Oe1){var Ie=Le.slice(0,ot.index),lt=Le.slice(ot.index+ot.length);ht=Ie.join(":")+"::"+lt.join(":")}else ht=Le.join(":");return W&&(ht+="%"+W),ht}else return v}var ye=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Se="".match(/(){0}/)[1]===void 0;function oe(v){var h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},S={},C=h.iri!==!1?y:f;h.reference==="suffix"&&(v=(h.scheme?h.scheme+":":"")+"//"+v);var I=v.match(ye);if(I){Se?(S.scheme=I[1],S.userinfo=I[3],S.host=I[4],S.port=parseInt(I[5],10),S.path=I[6]||"",S.query=I[7],S.fragment=I[8],isNaN(S.port)&&(S.port=I[5])):(S.scheme=I[1]||void 0,S.userinfo=v.indexOf("@")!==-1?I[3]:void 0,S.host=v.indexOf("//")!==-1?I[4]:void 0,S.port=parseInt(I[5],10),S.path=I[6]||"",S.query=v.indexOf("?")!==-1?I[7]:void 0,S.fragment=v.indexOf("#")!==-1?I[8]:void 0,isNaN(S.port)&&(S.port=v.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?I[4]:void 0)),S.host&&(S.host=V(L(S.host,C),C)),S.scheme===void 0&&S.userinfo===void 0&&S.host===void 0&&S.port===void 0&&!S.path&&S.query===void 0?S.reference="same-document":S.scheme===void 0?S.reference="relative":S.fragment===void 0?S.reference="absolute":S.reference="uri",h.reference&&h.reference!=="suffix"&&h.reference!==S.reference&&(S.error=S.error||"URI is not a "+h.reference+" reference.");var W=Fe[(h.scheme||S.scheme||"").toLowerCase()];if(!h.unicodeSupport&&(!W||!W.unicodeSupport)){if(S.host&&(h.domainHost||W&&W.domainHost))try{S.host=$e.toASCII(S.host.replace(C.PCT_ENCODED,M).toLowerCase())}catch(me){S.error=S.error||"Host's domain name can not be converted to ASCII via punycode: "+me}X(S,f)}else X(S,C);W&&W.parse&&W.parse(S,h)}else S.error=S.error||"URI can not be parsed.";return S}function Ae(v,h){var S=h.iri!==!1?y:f,C=[];return v.userinfo!==void 0&&(C.push(v.userinfo),C.push("@")),v.host!==void 0&&C.push(V(L(String(v.host),S),S).replace(S.IPV6ADDRESS,function(I,W,me){return"["+W+(me?"%25"+me:"")+"]"})),(typeof v.port=="number"||typeof v.port=="string")&&(C.push(":"),C.push(String(v.port))),C.length?C.join(""):void 0}var je=/^\.\.?\//,Pe=/^\/\.(\/|$)/,Ge=/^\/\.\.(\/|$)/,Ue=/^\/?(?:.|\n)*?(?=\/|$)/;function Xe(v){for(var h=[];v.length;)if(v.match(je))v=v.replace(je,"");else if(v.match(Pe))v=v.replace(Pe,"/");else if(v.match(Ge))v=v.replace(Ge,"/"),h.pop();else if(v==="."||v==="..")v="";else{var S=v.match(Ue);if(S){var C=S[0];v=v.slice(C.length),h.push(C)}else throw new Error("Unexpected dot segment condition")}return h.join("")}function Ne(v){var h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},S=h.iri?y:f,C=[],I=Fe[(h.scheme||v.scheme||"").toLowerCase()];if(I&&I.serialize&&I.serialize(v,h),v.host&&!S.IPV6ADDRESS.test(v.host)){if(h.domainHost||I&&I.domainHost)try{v.host=h.iri?$e.toUnicode(v.host):$e.toASCII(v.host.replace(S.PCT_ENCODED,M).toLowerCase())}catch(we){v.error=v.error||"Host's domain name can not be converted to "+(h.iri?"Unicode":"ASCII")+" via punycode: "+we}}X(v,S),h.reference!=="suffix"&&v.scheme&&(C.push(v.scheme),C.push(":"));var W=Ae(v,h);if(W!==void 0&&(h.reference!=="suffix"&&C.push("//"),C.push(W),v.path&&v.path.charAt(0)!=="/"&&C.push("/")),v.path!==void 0){var me=v.path;!h.absolutePath&&(!I||!I.absolutePath)&&(me=Xe(me)),W===void 0&&(me=me.replace(/^\/\//,"/%2F")),C.push(me)}return v.query!==void 0&&(C.push("?"),C.push(v.query)),v.fragment!==void 0&&(C.push("#"),C.push(v.fragment)),C.join("")}function He(v,h){var S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},C=arguments[3],I={};return C||(v=oe(Ne(v,S),S),h=oe(Ne(h,S),S)),S=S||{},!S.tolerant&&h.scheme?(I.scheme=h.scheme,I.userinfo=h.userinfo,I.host=h.host,I.port=h.port,I.path=Xe(h.path||""),I.query=h.query):(h.userinfo!==void 0||h.host!==void 0||h.port!==void 0?(I.userinfo=h.userinfo,I.host=h.host,I.port=h.port,I.path=Xe(h.path||""),I.query=h.query):(h.path?(h.path.charAt(0)==="/"?I.path=Xe(h.path):((v.userinfo!==void 0||v.host!==void 0||v.port!==void 0)&&!v.path?I.path="/"+h.path:v.path?I.path=v.path.slice(0,v.path.lastIndexOf("/")+1)+h.path:I.path=h.path,I.path=Xe(I.path)),I.query=h.query):(I.path=v.path,h.query!==void 0?I.query=h.query:I.query=v.query),I.userinfo=v.userinfo,I.host=v.host,I.port=v.port),I.scheme=v.scheme),I.fragment=h.fragment,I}function ft(v,h,S){var C=c({scheme:"null"},S);return Ne(He(oe(v,C),oe(h,C),C,!0),C)}function it(v,h){return typeof v=="string"?v=Ne(oe(v,h),h):i(v)==="object"&&(v=oe(Ne(v,h),h)),v}function Ia(v,h,S){return typeof v=="string"?v=Ne(oe(v,S),S):i(v)==="object"&&(v=Ne(v,S)),typeof h=="string"?h=Ne(oe(h,S),S):i(h)==="object"&&(h=Ne(h,S)),v===h}function ts(v,h){return v&&v.toString().replace(!h||!h.iri?f.ESCAPE:y.ESCAPE,P)}function St(v,h){return v&&v.toString().replace(!h||!h.iri?f.PCT_ENCODED:y.PCT_ENCODED,M)}var ua={scheme:"http",domainHost:!0,parse:function(h,S){return h.host||(h.error=h.error||"HTTP URIs must have a host."),h},serialize:function(h,S){var C=String(h.scheme).toLowerCase()==="https";return(h.port===(C?443:80)||h.port==="")&&(h.port=void 0),h.path||(h.path="/"),h}},Vs={scheme:"https",domainHost:ua.domainHost,parse:ua.parse,serialize:ua.serialize};function Hs(v){return typeof v.secure=="boolean"?v.secure:String(v.scheme).toLowerCase()==="wss"}var da={scheme:"ws",domainHost:!0,parse:function(h,S){var C=h;return C.secure=Hs(C),C.resourceName=(C.path||"/")+(C.query?"?"+C.query:""),C.path=void 0,C.query=void 0,C},serialize:function(h,S){if((h.port===(Hs(h)?443:80)||h.port==="")&&(h.port=void 0),typeof h.secure=="boolean"&&(h.scheme=h.secure?"wss":"ws",h.secure=void 0),h.resourceName){var C=h.resourceName.split("?"),I=R(C,2),W=I[0],me=I[1];h.path=W&&W!=="/"?W:void 0,h.query=me,h.resourceName=void 0}return h.fragment=void 0,h}},Bs={scheme:"wss",domainHost:da.domainHost,parse:da.parse,serialize:da.serialize},Ti={},ki=!0,Qs="[A-Za-z0-9\\-\\.\\_\\~"+(ki?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Tt="[0-9A-Fa-f]",Ci=n(n("%[EFef]"+Tt+"%"+Tt+Tt+"%"+Tt+Tt)+"|"+n("%[89A-Fa-f]"+Tt+"%"+Tt+Tt)+"|"+n("%"+Tt+Tt)),Oi="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",Ii="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",$i=e(Ii,'[\\"\\\\]'),Ai="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",ji=new RegExp(Qs,"g"),Fr=new RegExp(Ci,"g"),Ni=new RegExp(e("[^]",Oi,"[\\.]",'[\\"]',$i),"g"),Gs=new RegExp(e("[^]",Qs,Ai),"g"),Di=Gs;function rs(v){var h=M(v);return h.match(ji)?h:v}var Js={scheme:"mailto",parse:function(h,S){var C=h,I=C.to=C.path?C.path.split(","):[];if(C.path=void 0,C.query){for(var W=!1,me={},we=C.query.split("&"),ke=0,Ze=we.length;ke{t.exports=function r(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if(i=e.length,i!=n.length)return!1;for(a=i;a--!==0;)if(!r(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(o=Object.keys(e),i=o.length,i!==Object.keys(n).length)return!1;for(a=i;a--!==0;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;a--!==0;){var c=o[a];if(!r(e[c],n[c]))return!1}return!0}return e!==e&&n!==n}}),to=ce((s,t)=>{t.exports=function(e){for(var n=0,i=e.length,a=0,o;a=55296&&o<=56319&&a{t.exports={copy:r,checkDataType:e,checkDataTypes:n,coerceToTypes:a,toHash:o,getProperty:f,escapeQuotes:y,equal:Rs(),ucs2length:to(),varOccurences:R,varReplace:m,schemaHasRules:b,schemaHasRulesExcept:d,schemaUnknownRules:p,toQuotedString:_,getPathExpr:g,getPath:x,getData:E,unescapeFragment:A,unescapeJsonPointer:j,escapeFragment:N,escapeJsonPointer:F};function r(w,k){k=k||{};for(var D in w)k[D]=w[D];return k}function e(w,k,D,z){var H=z?" !== ":" === ",Y=z?" || ":" && ",_e=z?"!":"",se=z?"":"!";switch(w){case"null":return k+H+"null";case"array":return _e+"Array.isArray("+k+")";case"object":return"("+_e+k+Y+"typeof "+k+H+'"object"'+Y+se+"Array.isArray("+k+"))";case"integer":return"(typeof "+k+H+'"number"'+Y+se+"("+k+" % 1)"+Y+k+H+k+(D?Y+_e+"isFinite("+k+")":"")+")";case"number":return"(typeof "+k+H+'"'+w+'"'+(D?Y+_e+"isFinite("+k+")":"")+")";default:return"typeof "+k+H+'"'+w+'"'}}function n(w,k,D){switch(w.length){case 1:return e(w[0],k,D,!0);default:var z="",H=o(w);H.array&&H.object&&(z=H.null?"(":"(!"+k+" || ",z+="typeof "+k+' !== "object")',delete H.null,delete H.array,delete H.object),H.number&&delete H.integer;for(var Y in H)z+=(z?" && ":"")+e(Y,k,D,!0);return z}}var i=o(["string","number","integer","boolean","null"]);function a(w,k){if(Array.isArray(k)){for(var D=[],z=0;z=k)throw new Error("Cannot access property/index "+z+" levels up, current level is "+k);return D[k-z]}if(z>k)throw new Error("Cannot access data "+z+" levels up, current level is "+k);if(Y="data"+(k-z||""),!H)return Y}for(var se=Y,ve=H.split("/"),le=0;le{var r=Yr();t.exports=e;function e(n){r.copy(n,this)}}),ro=ce((s,t)=>{var r=t.exports=function(i,a,o){typeof a=="function"&&(o=a,a={}),o=a.cb||o;var c=typeof o=="function"?o:o.pre||function(){},l=o.post||function(){};e(a,c,l,i,"",i)};r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},r.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},r.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function e(i,a,o,c,l,f,y,R,m,b){if(c&&typeof c=="object"&&!Array.isArray(c)){a(c,l,f,y,R,m,b);for(var d in c){var p=c[d];if(Array.isArray(p)){if(d in r.arrayKeywords)for(var _=0;_{var r=eo(),e=Rs(),n=Yr(),i=xn(),a=ro();t.exports=o,o.normalizeId=x,o.fullPath=p,o.url=$,o.ids=O,o.inlineRef=m,o.schema=c;function o(E,T,A){var N=this._refs[A];if(typeof N=="string")if(this._refs[N])N=this._refs[N];else return o.call(this,E,T,N);if(N=N||this._schemas[A],N instanceof i)return m(N.schema,this._opts.inlineRefs)?N.schema:N.validate||this._compile(N);var F=c.call(this,T,A),j,w,k;return F&&(j=F.schema,T=F.root,k=F.baseId),j instanceof i?w=j.validate||E.call(this,j.schema,T,void 0,k):j!==void 0&&(w=m(j,this._opts.inlineRefs)?j:E.call(this,j,T,void 0,k)),w}function c(E,T){var A=r.parse(T),N=_(A),F=p(this._getId(E.schema));if(Object.keys(E.schema).length===0||N!==F){var j=x(N),w=this._refs[j];if(typeof w=="string")return l.call(this,E,w,A);if(w instanceof i)w.validate||this._compile(w),E=w;else if(w=this._schemas[j],w instanceof i){if(w.validate||this._compile(w),j==x(T))return{schema:w,root:E,baseId:F};E=w}else return;if(!E.schema)return;F=p(this._getId(E.schema))}return y.call(this,A,F,E.schema,E)}function l(E,T,A){var N=c.call(this,E,T);if(N){var F=N.schema,j=N.baseId;E=N.root;var w=this._getId(F);return w&&(j=$(j,w)),y.call(this,A,j,F,E)}}var f=n.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function y(E,T,A,N){if(E.fragment=E.fragment||"",E.fragment.slice(0,1)=="/"){for(var F=E.fragment.split("/"),j=1;j{var r=Ts();t.exports={Validation:i(e),MissingRef:i(n)};function e(a){this.message="validation failed",this.errors=a,this.ajv=this.validation=!0}n.message=function(a,o){return"can't resolve reference "+o+" from id "+a};function n(a,o,c){this.message=c||n.message(a,o),this.missingRef=r.url(a,o),this.missingSchema=r.normalizeId(r.fullPath(this.missingRef))}function i(a){return a.prototype=Object.create(Error.prototype),a.prototype.constructor=a,a}}),En=ce((s,t)=>{t.exports=function(r,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var n=typeof e.cycles=="boolean"?e.cycles:!1,i=e.cmp&&function(o){return function(c){return function(l,f){var y={key:l,value:c[l]},R={key:f,value:c[f]};return o(y,R)}}}(e.cmp),a=[];return function o(c){if(c&&c.toJSON&&typeof c.toJSON=="function"&&(c=c.toJSON()),c!==void 0){if(typeof c=="number")return isFinite(c)?""+c:"null";if(typeof c!="object")return JSON.stringify(c);var l,f;if(Array.isArray(c)){for(f="[",l=0;l{t.exports=function(e,n,i){var a="",o=e.schema.$async===!0,c=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),l=e.self._getId(e.schema);if(e.opts.strictKeywords){var f=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(f){var y="unknown keyword: "+f;if(e.opts.strictKeywords==="log")e.logger.warn(y);else throw new Error(y)}}if(e.isTop&&(a+=" var validate = ",o&&(e.async=!0,a+="async "),a+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",l&&(e.opts.sourceCode||e.opts.processCode)&&(a+=" "+("/*# sourceURL="+l+" */")+" ")),typeof e.schema=="boolean"||!(c||e.schema.$ref)){var n="false schema",R=e.level,m=e.dataLevel,b=e.schema[n],d=e.schemaPath+e.util.getProperty(n),p=e.errSchemaPath+"/"+n,T=!e.opts.allErrors,F,_="data"+(m||""),E="valid"+R;if(e.schema===!1){e.isTop?T=!0:a+=" var "+E+" = false; ";var g=g||[];g.push(a),a="",e.createErrors!==!1?(a+=" { keyword: '"+(F||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",e.opts.messages!==!1&&(a+=" , message: 'boolean schema is false' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+_+" "),a+=" } "):a+=" {} ";var x=a;a=g.pop(),!e.compositeRule&&T?e.async?a+=" throw new ValidationError(["+x+"]); ":a+=" validate.errors = ["+x+"]; return false; ":a+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?o?a+=" return data; ":a+=" validate.errors = null; return true; ":a+=" var "+E+" = true; ";return e.isTop&&(a+=" }; return validate; "),a}if(e.isTop){var $=e.isTop,R=e.level=0,m=e.dataLevel=0,_="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var O="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(O);else throw new Error(O)}a+=" var vErrors = null; ",a+=" var errors = 0; ",a+=" if (rootData === undefined) rootData = data; "}else{var{level:R,dataLevel:m}=e,_="data"+(m||"");if(l&&(e.baseId=e.resolve.url(e.baseId,l)),o&&!e.async)throw new Error("async schema in sync schema");a+=" var errs_"+R+" = errors;"}var E="valid"+R,T=!e.opts.allErrors,A="",N="",F,j=e.schema.type,w=Array.isArray(j);if(j&&e.opts.nullable&&e.schema.nullable===!0&&(w?j.indexOf("null")==-1&&(j=j.concat("null")):j!="null"&&(j=[j,"null"],w=!0)),w&&j.length==1&&(j=j[0],w=!1),e.schema.$ref&&c){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(c=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(a+=" "+e.RULES.all.$comment.code(e,"$comment")),j){if(e.opts.coerceTypes)var k=e.util.coerceToTypes(e.opts.coerceTypes,j);var D=e.RULES.types[j];if(k||w||D===!0||D&&!Ue(D)){var d=e.schemaPath+".type",p=e.errSchemaPath+"/type",d=e.schemaPath+".type",p=e.errSchemaPath+"/type",z=w?"checkDataTypes":"checkDataType";if(a+=" if ("+e.util[z](j,_,e.opts.strictNumbers,!0)+") { ",k){var H="dataType"+R,Y="coerced"+R;a+=" var "+H+" = typeof "+_+"; var "+Y+" = undefined; ",e.opts.coerceTypes=="array"&&(a+=" if ("+H+" == 'object' && Array.isArray("+_+") && "+_+".length == 1) { "+_+" = "+_+"[0]; "+H+" = typeof "+_+"; if ("+e.util.checkDataType(e.schema.type,_,e.opts.strictNumbers)+") "+Y+" = "+_+"; } "),a+=" if ("+Y+" !== undefined) ; ";var _e=k;if(_e)for(var se,ve=-1,le=_e.length-1;ve{var r=Ts(),e=Yr(),n=ks(),i=En(),a=wn(),o=e.ucs2length,c=Rs(),l=n.Validation;t.exports=f;function f(x,$,O,E){var T=this,A=this._opts,N=[void 0],F={},j=[],w={},k=[],D={},z=[];$=$||{schema:x,refVal:N,refs:F};var H=y.call(this,x,$,E),Y=this._compilations[H.index];if(H.compiling)return Y.callValidate=ue;var _e=this._formats,se=this.RULES;try{var ve=Be(x,$,O,E);Y.validate=ve;var le=Y.callValidate;return le&&(le.schema=ve.schema,le.errors=null,le.refs=ve.refs,le.refVal=ve.refVal,le.root=ve.root,le.$async=ve.$async,A.sourceCode&&(le.source=ve.source)),ve}finally{R.call(this,x,$,E)}function ue(){var L=Y.validate,V=L.apply(this,arguments);return ue.errors=L.errors,V}function Be(L,V,ye,Se){var oe=!V||V&&V.schema==L;if(V.schema!=$.schema)return f.call(T,L,V,ye,Se);var Ae=L.$async===!0,je=a({isTop:!0,schema:L,isRoot:oe,baseId:Se,root:V,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:n.MissingRef,RULES:se,validate:a,util:e,resolve:r,resolveRef:We,usePattern:M,useDefault:X,useCustomRule:de,opts:A,formats:_e,logger:T.logger,self:T});je=g(N,p)+g(j,b)+g(k,d)+g(z,_)+je,A.processCode&&(je=A.processCode(je,L));var Pe;try{var Ge=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",je);Pe=Ge(T,se,_e,$,N,k,z,c,o,l),N[0]=Pe}catch(Ue){throw T.logger.error("Error compiling schema, function code:",je),Ue}return Pe.schema=L,Pe.errors=null,Pe.refs=F,Pe.refVal=N,Pe.root=oe?Pe:V,Ae&&(Pe.$async=!0),A.sourceCode===!0&&(Pe.source={code:je,patterns:j,defaults:k}),Pe}function We(L,V,ye){V=r.url(L,V);var Se=F[V],oe,Ae;if(Se!==void 0)return oe=N[Se],Ae="refVal["+Se+"]",P(oe,Ae);if(!ye&&$.refs){var je=$.refs[V];if(je!==void 0)return oe=$.refVal[je],Ae=Qe(V,oe),P(oe,Ae)}Ae=Qe(V);var Pe=r.call(T,Be,$,V);if(Pe===void 0){var Ge=O&&O[V];Ge&&(Pe=r.inlineRef(Ge,A.inlineRefs)?Ge:f.call(T,Ge,$,O,L))}if(Pe===void 0)$e(V);else return Fe(V,Pe),P(Pe,Ae)}function Qe(L,V){var ye=N.length;return N[ye]=V,F[L]=ye,"refVal"+ye}function $e(L){delete F[L]}function Fe(L,V){var ye=F[L];N[ye]=V}function P(L,V){return typeof L=="object"||typeof L=="boolean"?{code:V,schema:L,inline:!0}:{code:V,$async:L&&!!L.$async}}function M(L){var V=w[L];return V===void 0&&(V=w[L]=j.length,j[V]=L),"pattern"+V}function X(L){switch(typeof L){case"boolean":case"number":return""+L;case"string":return e.toQuotedString(L);case"object":if(L===null)return"null";var V=i(L),ye=D[V];return ye===void 0&&(ye=D[V]=k.length,k[ye]=L),"default"+ye}}function de(L,V,ye,Se){if(T._opts.validateSchema!==!1){var oe=L.definition.dependencies;if(oe&&!oe.every(function(ft){return Object.prototype.hasOwnProperty.call(ye,ft)}))throw new Error("parent schema must have all required keywords: "+oe.join(","));var Ae=L.definition.validateSchema;if(Ae){var je=Ae(V);if(!je){var Pe="keyword schema is invalid: "+T.errorsText(Ae.errors);if(T._opts.validateSchema=="log")T.logger.error(Pe);else throw new Error(Pe)}}}var Ge=L.definition.compile,Ue=L.definition.inline,Xe=L.definition.macro,Ne;if(Ge)Ne=Ge.call(T,V,ye,Se);else if(Xe)Ne=Xe.call(T,V,ye,Se),A.validateSchema!==!1&&T.validateSchema(Ne,!0);else if(Ue)Ne=Ue.call(T,Se,L.keyword,V,ye);else if(Ne=L.definition.validate,!Ne)return;if(Ne===void 0)throw new Error('custom keyword "'+L.keyword+'"failed to compile');var He=z.length;return z[He]=Ne,{code:"customRule"+He,validate:Ne}}}function y(x,$,O){var E=m.call(this,x,$,O);return E>=0?{index:E,compiling:!0}:(E=this._compilations.length,this._compilations[E]={schema:x,root:$,baseId:O},{index:E,compiling:!1})}function R(x,$,O){var E=m.call(this,x,$,O);E>=0&&this._compilations.splice(E,1)}function m(x,$,O){for(var E=0;E{var r=t.exports=function(){this._cache={}};r.prototype.put=function(n,i){this._cache[n]=i},r.prototype.get=function(n){return this._cache[n]},r.prototype.del=function(n){delete this._cache[n]},r.prototype.clear=function(){this._cache={}}}),no=ce((s,t)=>{var r=Yr(),e=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,n=[0,31,28,31,30,31,30,31,31,30,31,30,31],i=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,a=/^(?=.{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,o=/^(?:[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,c=/^(?:[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,l=/^(?:(?:[^\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,f=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,y=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,R=/^(?:\/(?:[^~/]|~0|~1)*)*$/,m=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,b=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;t.exports=d;function d(N){return N=N=="full"?"full":"fast",r.copy(d[N])}d.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":l,url:f,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,hostname:a,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:A,uuid:y,"json-pointer":R,"json-pointer-uri-fragment":m,"relative-json-pointer":b},d.full={date:_,time:g,"date-time":$,uri:E,"uri-reference":c,"uri-template":l,url:f,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:a,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:A,uuid:y,"json-pointer":R,"json-pointer-uri-fragment":m,"relative-json-pointer":b};function p(N){return N%4===0&&(N%100!==0||N%400===0)}function _(N){var F=N.match(e);if(!F)return!1;var j=+F[1],w=+F[2],k=+F[3];return w>=1&&w<=12&&k>=1&&k<=(w==2&&p(j)?29:n[w])}function g(N,F){var j=N.match(i);if(!j)return!1;var w=j[1],k=j[2],D=j[3],z=j[5];return(w<=23&&k<=59&&D<=59||w==23&&k==59&&D==60)&&(!F||z)}var x=/t|\s/i;function $(N){var F=N.split(x);return F.length==2&&_(F[0])&&g(F[1],!0)}var O=/\/|:/;function E(N){return O.test(N)&&o.test(N)}var T=/[^\\]\\Z/;function A(N){if(T.test(N))return!1;try{return new RegExp(N),!0}catch{return!1}}}),io=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.errSchemaPath+"/"+n,y=!e.opts.allErrors,R="data"+(c||""),m="valid"+o,b,d;if(l=="#"||l=="#/")e.isRoot?(b=e.async,d="validate"):(b=e.root.schema.$async===!0,d="root.refVal[0]");else{var p=e.resolveRef(e.baseId,l,e.isRoot);if(p===void 0){var _=e.MissingRefError.message(e.baseId,l);if(e.opts.missingRefs=="fail"){e.logger.error(_);var g=g||[];g.push(a),a="",e.createErrors!==!1?(a+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(f)+" , params: { ref: '"+e.util.escapeQuotes(l)+"' } ",e.opts.messages!==!1&&(a+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(l)+"' "),e.opts.verbose&&(a+=" , schema: "+e.util.toQuotedString(l)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+R+" "),a+=" } "):a+=" {} ";var x=a;a=g.pop(),!e.compositeRule&&y?e.async?a+=" throw new ValidationError(["+x+"]); ":a+=" validate.errors = ["+x+"]; return false; ":a+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",y&&(a+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(_),y&&(a+=" if (true) { ");else throw new e.MissingRefError(e.baseId,l,_)}else if(p.inline){var $=e.util.copy(e);$.level++;var O="valid"+$.level;$.schema=p.schema,$.schemaPath="",$.errSchemaPath=l;var E=e.validate($).replace(/validate\.schema/g,p.code);a+=" "+E+" ",y&&(a+=" if ("+O+") { ")}else b=p.$async===!0||e.async&&p.$async!==!1,d=p.code}if(d){var g=g||[];g.push(a),a="",e.opts.passContext?a+=" "+d+".call(this, ":a+=" "+d+"( ",a+=" "+R+", (dataPath || '')",e.errorPath!='""'&&(a+=" + "+e.errorPath);var T=c?"data"+(c-1||""):"parentData",A=c?e.dataPathArr[c]:"parentDataProperty";a+=" , "+T+" , "+A+", rootData) ";var N=a;if(a=g.pop(),b){if(!e.async)throw new Error("async schema referenced by sync schema");y&&(a+=" var "+m+"; "),a+=" try { await "+N+"; ",y&&(a+=" "+m+" = true; "),a+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",y&&(a+=" "+m+" = false; "),a+=" } ",y&&(a+=" if ("+m+") { ")}else a+=" if (!"+N+") { if (vErrors === null) vErrors = "+d+".errors; else vErrors = vErrors.concat("+d+".errors); errors = vErrors.length; } ",y&&(a+=" else { ")}return a}}),oo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.schema[n],c=e.schemaPath+e.util.getProperty(n),l=e.errSchemaPath+"/"+n,f=!e.opts.allErrors,y=e.util.copy(e),R="";y.level++;var m="valid"+y.level,b=y.baseId,d=!0,p=o;if(p)for(var _,g=-1,x=p.length-1;g0||_===!1:e.util.schemaHasRules(_,e.RULES.all))&&(d=!1,y.schema=_,y.schemaPath=c+"["+g+"]",y.errSchemaPath=l+"/"+g,a+=" "+e.validate(y)+" ",y.baseId=b,f&&(a+=" if ("+m+") { ",R+="}"));return f&&(d?a+=" if (true) { ":a+=" "+R.slice(0,-1)+" "),a}}),lo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="valid"+o,d="errs__"+o,p=e.util.copy(e),_="";p.level++;var g="valid"+p.level,x=l.every(function(F){return e.opts.strictKeywords?typeof F=="object"&&Object.keys(F).length>0||F===!1:e.util.schemaHasRules(F,e.RULES.all)});if(x){var $=p.baseId;a+=" var "+d+" = errors; var "+b+" = false; ";var O=e.compositeRule;e.compositeRule=p.compositeRule=!0;var E=l;if(E)for(var T,A=-1,N=E.length-1;A{t.exports=function(e,n,i){var a=" ",o=e.schema[n],c=e.errSchemaPath+"/"+n,l=!e.opts.allErrors,f=e.util.toQuotedString(o);return e.opts.$comment===!0?a+=" console.log("+f+");":typeof e.opts.$comment=="function"&&(a+=" self._opts.$comment("+f+", "+e.util.toQuotedString(c)+", validate.root.schema);"),a}}),uo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="valid"+o,d=e.opts.$data&&l&&l.$data,p;d?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",p="schema"+o):p=l,d||(a+=" var schema"+o+" = validate.schema"+f+";"),a+="var "+b+" = equal("+m+", schema"+o+"); if (!"+b+") { ";var _=_||[];_.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { allowedValue: schema"+o+" } ",e.opts.messages!==!1&&(a+=" , message: 'should be equal to constant' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var g=a;return a=_.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",R&&(a+=" else { "),a}}),fo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="valid"+o,d="errs__"+o,p=e.util.copy(e),_="";p.level++;var g="valid"+p.level,x="i"+o,$=p.dataLevel=e.dataLevel+1,O="data"+$,E=e.baseId,T=e.opts.strictKeywords?typeof l=="object"&&Object.keys(l).length>0||l===!1:e.util.schemaHasRules(l,e.RULES.all);if(a+="var "+d+" = errors;var "+b+";",T){var A=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=l,p.schemaPath=f,p.errSchemaPath=y,a+=" var "+g+" = false; for (var "+x+" = 0; "+x+" < "+m+".length; "+x+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,x,e.opts.jsonPointers,!0);var N=m+"["+x+"]";p.dataPathArr[$]=x;var F=e.validate(p);p.baseId=E,e.util.varOccurences(F,O)<2?a+=" "+e.util.varReplace(F,O,N)+" ":a+=" var "+O+" = "+N+"; "+F+" ",a+=" if ("+g+") break; } ",e.compositeRule=p.compositeRule=A,a+=" "+_+" if (!"+g+") {"}else a+=" if ("+m+".length == 0) {";var j=j||[];j.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: {} ",e.opts.messages!==!1&&(a+=" , message: 'should contain a valid item' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var w=a;return a=j.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+w+"]); ":a+=" validate.errors = ["+w+"]; return false; ":a+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { ",T&&(a+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } "),e.opts.allErrors&&(a+=" } "),a}}),ho=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="errs__"+o,d=e.util.copy(e),p="";d.level++;var _="valid"+d.level,g={},x={},$=e.opts.ownProperties;for(A in l)if(A!="__proto__"){var O=l[A],E=Array.isArray(O)?x:g;E[A]=O}a+="var "+b+" = errors;";var T=e.errorPath;a+="var missing"+o+";";for(var A in x)if(E=x[A],E.length){if(a+=" if ( "+m+e.util.getProperty(A)+" !== undefined ",$&&(a+=" && Object.prototype.hasOwnProperty.call("+m+", '"+e.util.escapeQuotes(A)+"') "),R){a+=" && ( ";var N=E;if(N)for(var F,j=-1,w=N.length-1;j0||O===!1:e.util.schemaHasRules(O,e.RULES.all))&&(a+=" "+_+" = true; if ( "+m+e.util.getProperty(A)+" !== undefined ",$&&(a+=" && Object.prototype.hasOwnProperty.call("+m+", '"+e.util.escapeQuotes(A)+"') "),a+=") { ",d.schema=O,d.schemaPath=f+e.util.getProperty(A),d.errSchemaPath=y+"/"+e.util.escapeFragment(A),a+=" "+e.validate(d)+" ",d.baseId=ue,a+=" } ",R&&(a+=" if ("+_+") { ",p+="}"))}return R&&(a+=" "+p+" if ("+b+" == errors) {"),a}}),po=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="valid"+o,d=e.opts.$data&&l&&l.$data,p;d?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",p="schema"+o):p=l;var _="i"+o,g="schema"+o;d||(a+=" var "+g+" = validate.schema"+f+";"),a+="var "+b+";",d&&(a+=" if (schema"+o+" === undefined) "+b+" = true; else if (!Array.isArray(schema"+o+")) "+b+" = false; else {"),a+=""+b+" = false;for (var "+_+"=0; "+_+"<"+g+".length; "+_+"++) if (equal("+m+", "+g+"["+_+"])) { "+b+" = true; break; }",d&&(a+=" } "),a+=" if (!"+b+") { ";var x=x||[];x.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { allowedValues: schema"+o+" } ",e.opts.messages!==!1&&(a+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var $=a;return a=x.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+$+"]); ":a+=" validate.errors = ["+$+"]; return false; ":a+=" var err = "+$+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",R&&(a+=" else { "),a}}),mo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||"");if(e.opts.format===!1)return R&&(a+=" if (true) { "),a;var b=e.opts.$data&&l&&l.$data,d;b?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",d="schema"+o):d=l;var p=e.opts.unknownFormats,_=Array.isArray(p);if(b){var g="format"+o,x="isObject"+o,$="formatType"+o;a+=" var "+g+" = formats["+d+"]; var "+x+" = typeof "+g+" == 'object' && !("+g+" instanceof RegExp) && "+g+".validate; var "+$+" = "+x+" && "+g+".type || 'string'; if ("+x+") { ",e.async&&(a+=" var async"+o+" = "+g+".async; "),a+=" "+g+" = "+g+".validate; } if ( ",b&&(a+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),a+=" (",p!="ignore"&&(a+=" ("+d+" && !"+g+" ",_&&(a+=" && self._opts.unknownFormats.indexOf("+d+") == -1 "),a+=") || "),a+=" ("+g+" && "+$+" == '"+i+"' && !(typeof "+g+" == 'function' ? ",e.async?a+=" (async"+o+" ? await "+g+"("+m+") : "+g+"("+m+")) ":a+=" "+g+"("+m+") ",a+=" : "+g+".test("+m+"))))) {"}else{var g=e.formats[l];if(!g){if(p=="ignore")return e.logger.warn('unknown format "'+l+'" ignored in schema at path "'+e.errSchemaPath+'"'),R&&(a+=" if (true) { "),a;if(_&&p.indexOf(l)>=0)return R&&(a+=" if (true) { "),a;throw new Error('unknown format "'+l+'" is used in schema at path "'+e.errSchemaPath+'"')}var x=typeof g=="object"&&!(g instanceof RegExp)&&g.validate,$=x&&g.type||"string";if(x){var O=g.async===!0;g=g.validate}if($!=i)return R&&(a+=" if (true) { "),a;if(O){if(!e.async)throw new Error("async format in sync schema");var E="formats"+e.util.getProperty(l)+".validate";a+=" if (!(await "+E+"("+m+"))) { "}else{a+=" if (! ";var E="formats"+e.util.getProperty(l);x&&(E+=".validate"),typeof g=="function"?a+=" "+E+"("+m+") ":a+=" "+E+".test("+m+") ",a+=") { "}}var T=T||[];T.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { format: ",b?a+=""+d:a+=""+e.util.toQuotedString(l),a+=" } ",e.opts.messages!==!1&&(a+=` , message: 'should match format "`,b?a+="' + "+d+" + '":a+=""+e.util.escapeQuotes(l),a+=`"' `),e.opts.verbose&&(a+=" , schema: ",b?a+="validate.schema"+f:a+=""+e.util.toQuotedString(l),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var A=a;return a=T.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+A+"]); ":a+=" validate.errors = ["+A+"]; return false; ":a+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",R&&(a+=" else { "),a}}),vo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="valid"+o,d="errs__"+o,p=e.util.copy(e);p.level++;var _="valid"+p.level,g=e.schema.then,x=e.schema.else,$=g!==void 0&&(e.opts.strictKeywords?typeof g=="object"&&Object.keys(g).length>0||g===!1:e.util.schemaHasRules(g,e.RULES.all)),O=x!==void 0&&(e.opts.strictKeywords?typeof x=="object"&&Object.keys(x).length>0||x===!1:e.util.schemaHasRules(x,e.RULES.all)),E=p.baseId;if($||O){var T;p.createErrors=!1,p.schema=l,p.schemaPath=f,p.errSchemaPath=y,a+=" var "+d+" = errors; var "+b+" = true; ";var A=e.compositeRule;e.compositeRule=p.compositeRule=!0,a+=" "+e.validate(p)+" ",p.baseId=E,p.createErrors=!0,a+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.compositeRule=p.compositeRule=A,$?(a+=" if ("+_+") { ",p.schema=e.schema.then,p.schemaPath=e.schemaPath+".then",p.errSchemaPath=e.errSchemaPath+"/then",a+=" "+e.validate(p)+" ",p.baseId=E,a+=" "+b+" = "+_+"; ",$&&O?(T="ifClause"+o,a+=" var "+T+" = 'then'; "):T="'then'",a+=" } ",O&&(a+=" else { ")):a+=" if (!"+_+") { ",O&&(p.schema=e.schema.else,p.schemaPath=e.schemaPath+".else",p.errSchemaPath=e.errSchemaPath+"/else",a+=" "+e.validate(p)+" ",p.baseId=E,a+=" "+b+" = "+_+"; ",$&&O?(T="ifClause"+o,a+=" var "+T+" = 'else'; "):T="'else'",a+=" } "),a+=" if (!"+b+") { var err = ",e.createErrors!==!1?(a+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { failingKeyword: "+T+" } ",e.opts.messages!==!1&&(a+=` , message: 'should match "' + `+T+` + '" schema' `),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&R&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } ",R&&(a+=" else { ")}else R&&(a+=" if (true) { ");return a}}),go=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="valid"+o,d="errs__"+o,p=e.util.copy(e),_="";p.level++;var g="valid"+p.level,x="i"+o,$=p.dataLevel=e.dataLevel+1,O="data"+$,E=e.baseId;if(a+="var "+d+" = errors;var "+b+";",Array.isArray(l)){var T=e.schema.additionalItems;if(T===!1){a+=" "+b+" = "+m+".length <= "+l.length+"; ";var A=y;y=e.errSchemaPath+"/additionalItems",a+=" if (!"+b+") { ";var N=N||[];N.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { limit: "+l.length+" } ",e.opts.messages!==!1&&(a+=" , message: 'should NOT have more than "+l.length+" items' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var F=a;a=N.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+F+"]); ":a+=" validate.errors = ["+F+"]; return false; ":a+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",y=A,R&&(_+="}",a+=" else { ")}var j=l;if(j){for(var w,k=-1,D=j.length-1;k0||w===!1:e.util.schemaHasRules(w,e.RULES.all)){a+=" "+g+" = true; if ("+m+".length > "+k+") { ";var z=m+"["+k+"]";p.schema=w,p.schemaPath=f+"["+k+"]",p.errSchemaPath=y+"/"+k,p.errorPath=e.util.getPathExpr(e.errorPath,k,e.opts.jsonPointers,!0),p.dataPathArr[$]=k;var H=e.validate(p);p.baseId=E,e.util.varOccurences(H,O)<2?a+=" "+e.util.varReplace(H,O,z)+" ":a+=" var "+O+" = "+z+"; "+H+" ",a+=" } ",R&&(a+=" if ("+g+") { ",_+="}")}}if(typeof T=="object"&&(e.opts.strictKeywords?typeof T=="object"&&Object.keys(T).length>0||T===!1:e.util.schemaHasRules(T,e.RULES.all))){p.schema=T,p.schemaPath=e.schemaPath+".additionalItems",p.errSchemaPath=e.errSchemaPath+"/additionalItems",a+=" "+g+" = true; if ("+m+".length > "+l.length+") { for (var "+x+" = "+l.length+"; "+x+" < "+m+".length; "+x+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,x,e.opts.jsonPointers,!0);var z=m+"["+x+"]";p.dataPathArr[$]=x;var H=e.validate(p);p.baseId=E,e.util.varOccurences(H,O)<2?a+=" "+e.util.varReplace(H,O,z)+" ":a+=" var "+O+" = "+z+"; "+H+" ",R&&(a+=" if (!"+g+") break; "),a+=" } } ",R&&(a+=" if ("+g+") { ",_+="}")}}else if(e.opts.strictKeywords?typeof l=="object"&&Object.keys(l).length>0||l===!1:e.util.schemaHasRules(l,e.RULES.all)){p.schema=l,p.schemaPath=f,p.errSchemaPath=y,a+=" for (var "+x+" = 0; "+x+" < "+m+".length; "+x+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,x,e.opts.jsonPointers,!0);var z=m+"["+x+"]";p.dataPathArr[$]=x;var H=e.validate(p);p.baseId=E,e.util.varOccurences(H,O)<2?a+=" "+e.util.varReplace(H,O,z)+" ":a+=" var "+O+" = "+z+"; "+H+" ",R&&(a+=" if (!"+g+") break; "),a+=" }"}return R&&(a+=" "+_+" if ("+d+" == errors) {"),a}}),rn=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,E,m="data"+(c||""),b=e.opts.$data&&l&&l.$data,d;b?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",d="schema"+o):d=l;var p=n=="maximum",_=p?"exclusiveMaximum":"exclusiveMinimum",g=e.schema[_],x=e.opts.$data&&g&&g.$data,$=p?"<":">",O=p?">":"<",E=void 0;if(!(b||typeof l=="number"||l===void 0))throw new Error(n+" must be number");if(!(x||g===void 0||typeof g=="number"||typeof g=="boolean"))throw new Error(_+" must be number or boolean");if(x){var T=e.util.getData(g.$data,c,e.dataPathArr),A="exclusive"+o,N="exclType"+o,F="exclIsNumber"+o,j="op"+o,w="' + "+j+" + '";a+=" var schemaExcl"+o+" = "+T+"; ",T="schemaExcl"+o,a+=" var "+A+"; var "+N+" = typeof "+T+"; if ("+N+" != 'boolean' && "+N+" != 'undefined' && "+N+" != 'number') { ";var E=_,k=k||[];k.push(a),a="",e.createErrors!==!1?(a+=" { keyword: '"+(E||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: {} ",e.opts.messages!==!1&&(a+=" , message: '"+_+" should be boolean' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var D=a;a=k.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+D+"]); ":a+=" validate.errors = ["+D+"]; return false; ":a+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else if ( ",b&&(a+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),a+=" "+N+" == 'number' ? ( ("+A+" = "+d+" === undefined || "+T+" "+$+"= "+d+") ? "+m+" "+O+"= "+T+" : "+m+" "+O+" "+d+" ) : ( ("+A+" = "+T+" === true) ? "+m+" "+O+"= "+d+" : "+m+" "+O+" "+d+" ) || "+m+" !== "+m+") { var op"+o+" = "+A+" ? '"+$+"' : '"+$+"='; ",l===void 0&&(E=_,y=e.errSchemaPath+"/"+_,d=T,b=x)}else{var F=typeof g=="number",w=$;if(F&&b){var j="'"+w+"'";a+=" if ( ",b&&(a+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),a+=" ( "+d+" === undefined || "+g+" "+$+"= "+d+" ? "+m+" "+O+"= "+g+" : "+m+" "+O+" "+d+" ) || "+m+" !== "+m+") { "}else{F&&l===void 0?(A=!0,E=_,y=e.errSchemaPath+"/"+_,d=g,O+="="):(F&&(d=Math[p?"min":"max"](g,l)),g===(F?d:!0)?(A=!0,E=_,y=e.errSchemaPath+"/"+_,O+="="):(A=!1,w+="="));var j="'"+w+"'";a+=" if ( ",b&&(a+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),a+=" "+m+" "+O+" "+d+" || "+m+" !== "+m+") { "}}E=E||n;var k=k||[];k.push(a),a="",e.createErrors!==!1?(a+=" { keyword: '"+(E||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { comparison: "+j+", limit: "+d+", exclusive: "+A+" } ",e.opts.messages!==!1&&(a+=" , message: 'should be "+w+" ",b?a+="' + "+d:a+=""+d+"'"),e.opts.verbose&&(a+=" , schema: ",b?a+="validate.schema"+f:a+=""+l,a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var D=a;return a=k.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+D+"]); ":a+=" validate.errors = ["+D+"]; return false; ":a+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",R&&(a+=" else { "),a}}),an=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,_,m="data"+(c||""),b=e.opts.$data&&l&&l.$data,d;if(b?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",d="schema"+o):d=l,!(b||typeof l=="number"))throw new Error(n+" must be number");var p=n=="maxItems"?">":"<";a+="if ( ",b&&(a+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),a+=" "+m+".length "+p+" "+d+") { ";var _=n,g=g||[];g.push(a),a="",e.createErrors!==!1?(a+=" { keyword: '"+(_||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(a+=" , message: 'should NOT have ",n=="maxItems"?a+="more":a+="fewer",a+=" than ",b?a+="' + "+d+" + '":a+=""+l,a+=" items' "),e.opts.verbose&&(a+=" , schema: ",b?a+="validate.schema"+f:a+=""+l,a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var x=a;return a=g.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+x+"]); ":a+=" validate.errors = ["+x+"]; return false; ":a+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",R&&(a+=" else { "),a}}),sn=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,_,m="data"+(c||""),b=e.opts.$data&&l&&l.$data,d;if(b?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",d="schema"+o):d=l,!(b||typeof l=="number"))throw new Error(n+" must be number");var p=n=="maxLength"?">":"<";a+="if ( ",b&&(a+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),e.opts.unicode===!1?a+=" "+m+".length ":a+=" ucs2length("+m+") ",a+=" "+p+" "+d+") { ";var _=n,g=g||[];g.push(a),a="",e.createErrors!==!1?(a+=" { keyword: '"+(_||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(a+=" , message: 'should NOT be ",n=="maxLength"?a+="longer":a+="shorter",a+=" than ",b?a+="' + "+d+" + '":a+=""+l,a+=" characters' "),e.opts.verbose&&(a+=" , schema: ",b?a+="validate.schema"+f:a+=""+l,a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var x=a;return a=g.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+x+"]); ":a+=" validate.errors = ["+x+"]; return false; ":a+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",R&&(a+=" else { "),a}}),nn=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,_,m="data"+(c||""),b=e.opts.$data&&l&&l.$data,d;if(b?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",d="schema"+o):d=l,!(b||typeof l=="number"))throw new Error(n+" must be number");var p=n=="maxProperties"?">":"<";a+="if ( ",b&&(a+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),a+=" Object.keys("+m+").length "+p+" "+d+") { ";var _=n,g=g||[];g.push(a),a="",e.createErrors!==!1?(a+=" { keyword: '"+(_||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(a+=" , message: 'should NOT have ",n=="maxProperties"?a+="more":a+="fewer",a+=" than ",b?a+="' + "+d+" + '":a+=""+l,a+=" properties' "),e.opts.verbose&&(a+=" , schema: ",b?a+="validate.schema"+f:a+=""+l,a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var x=a;return a=g.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+x+"]); ":a+=" validate.errors = ["+x+"]; return false; ":a+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",R&&(a+=" else { "),a}}),yo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b=e.opts.$data&&l&&l.$data,d;if(b?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",d="schema"+o):d=l,!(b||typeof l=="number"))throw new Error(n+" must be number");a+="var division"+o+";if (",b&&(a+=" "+d+" !== undefined && ( typeof "+d+" != 'number' || "),a+=" (division"+o+" = "+m+" / "+d+", ",e.opts.multipleOfPrecision?a+=" Math.abs(Math.round(division"+o+") - division"+o+") > 1e-"+e.opts.multipleOfPrecision+" ":a+=" division"+o+" !== parseInt(division"+o+") ",a+=" ) ",b&&(a+=" ) "),a+=" ) { ";var p=p||[];p.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { multipleOf: "+d+" } ",e.opts.messages!==!1&&(a+=" , message: 'should be multiple of ",b?a+="' + "+d:a+=""+d+"'"),e.opts.verbose&&(a+=" , schema: ",b?a+="validate.schema"+f:a+=""+l,a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var _=a;return a=p.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+_+"]); ":a+=" validate.errors = ["+_+"]; return false; ":a+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",R&&(a+=" else { "),a}}),_o=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="errs__"+o,d=e.util.copy(e);d.level++;var p="valid"+d.level;if(e.opts.strictKeywords?typeof l=="object"&&Object.keys(l).length>0||l===!1:e.util.schemaHasRules(l,e.RULES.all)){d.schema=l,d.schemaPath=f,d.errSchemaPath=y,a+=" var "+b+" = errors; ";var _=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.createErrors=!1;var g;d.opts.allErrors&&(g=d.opts.allErrors,d.opts.allErrors=!1),a+=" "+e.validate(d)+" ",d.createErrors=!0,g&&(d.opts.allErrors=g),e.compositeRule=d.compositeRule=_,a+=" if ("+p+") { ";var x=x||[];x.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: {} ",e.opts.messages!==!1&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var $=a;a=x.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+$+"]); ":a+=" validate.errors = ["+$+"]; return false; ":a+=" var err = "+$+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { errors = "+b+"; if (vErrors !== null) { if ("+b+") vErrors.length = "+b+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else a+=" var err = ",e.createErrors!==!1?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: {} ",e.opts.messages!==!1&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",R&&(a+=" if (false) { ");return a}}),bo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="valid"+o,d="errs__"+o,p=e.util.copy(e),_="";p.level++;var g="valid"+p.level,x=p.baseId,$="prevValid"+o,O="passingSchemas"+o;a+="var "+d+" = errors , "+$+" = false , "+b+" = false , "+O+" = null; ";var E=e.compositeRule;e.compositeRule=p.compositeRule=!0;var T=l;if(T)for(var A,N=-1,F=T.length-1;N0||A===!1:e.util.schemaHasRules(A,e.RULES.all))?(p.schema=A,p.schemaPath=f+"["+N+"]",p.errSchemaPath=y+"/"+N,a+=" "+e.validate(p)+" ",p.baseId=x):a+=" var "+g+" = true; ",N&&(a+=" if ("+g+" && "+$+") { "+b+" = false; "+O+" = ["+O+", "+N+"]; } else { ",_+="}"),a+=" if ("+g+") { "+b+" = "+$+" = true; "+O+" = "+N+"; }";return e.compositeRule=p.compositeRule=E,a+=""+_+"if (!"+b+") { var err = ",e.createErrors!==!1?(a+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { passingSchemas: "+O+" } ",e.opts.messages!==!1&&(a+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&R&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+="} else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; }",e.opts.allErrors&&(a+=" } "),a}}),So=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b=e.opts.$data&&l&&l.$data,d;b?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",d="schema"+o):d=l;var p=b?"(new RegExp("+d+"))":e.usePattern(l);a+="if ( ",b&&(a+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),a+=" !"+p+".test("+m+") ) { ";var _=_||[];_.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { pattern: ",b?a+=""+d:a+=""+e.util.toQuotedString(l),a+=" } ",e.opts.messages!==!1&&(a+=` , message: 'should match pattern "`,b?a+="' + "+d+" + '":a+=""+e.util.escapeQuotes(l),a+=`"' `),e.opts.verbose&&(a+=" , schema: ",b?a+="validate.schema"+f:a+=""+e.util.toQuotedString(l),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var g=a;return a=_.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",R&&(a+=" else { "),a}}),xo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="errs__"+o,d=e.util.copy(e),p="";d.level++;var _="valid"+d.level,g="key"+o,x="idx"+o,$=d.dataLevel=e.dataLevel+1,O="data"+$,E="dataProperties"+o,T=Object.keys(l||{}).filter(ve),A=e.schema.patternProperties||{},N=Object.keys(A).filter(ve),F=e.schema.additionalProperties,j=T.length||N.length,w=F===!1,k=typeof F=="object"&&Object.keys(F).length,D=e.opts.removeAdditional,z=w||k||D,H=e.opts.ownProperties,Y=e.baseId,_e=e.schema.required;if(_e&&!(e.opts.$data&&_e.$data)&&_e.length8)a+=" || validate.schema"+f+".hasOwnProperty("+g+") ";else{var le=T;if(le)for(var ue,Be=-1,We=le.length-1;Be0||Ue===!1:e.util.schemaHasRules(Ue,e.RULES.all)){var Xe=e.util.getProperty(ue),Se=m+Xe,Ne=Ae&&Ue.default!==void 0;d.schema=Ue,d.schemaPath=f+Xe,d.errSchemaPath=y+"/"+e.util.escapeFragment(ue),d.errorPath=e.util.getPath(e.errorPath,ue,e.opts.jsonPointers),d.dataPathArr[$]=e.util.toQuotedString(ue);var oe=e.validate(d);if(d.baseId=Y,e.util.varOccurences(oe,O)<2){oe=e.util.varReplace(oe,O,Se);var He=Se}else{var He=O;a+=" var "+O+" = "+Se+"; "}if(Ne)a+=" "+oe+" ";else{if(se&&se[ue]){a+=" if ( "+He+" === undefined ",H&&(a+=" || ! Object.prototype.hasOwnProperty.call("+m+", '"+e.util.escapeQuotes(ue)+"') "),a+=") { "+_+" = false; ";var M=e.errorPath,de=y,ft=e.util.escapeQuotes(ue);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(M,ue,e.opts.jsonPointers)),y=e.errSchemaPath+"/required";var L=L||[];L.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { missingProperty: '"+ft+"' } ",e.opts.messages!==!1&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+ft+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var V=a;a=L.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+V+"]); ":a+=" validate.errors = ["+V+"]; return false; ":a+=" var err = "+V+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",y=de,e.errorPath=M,a+=" } else { "}else R?(a+=" if ( "+He+" === undefined ",H&&(a+=" || ! Object.prototype.hasOwnProperty.call("+m+", '"+e.util.escapeQuotes(ue)+"') "),a+=") { "+_+" = true; } else { "):(a+=" if ("+He+" !== undefined ",H&&(a+=" && Object.prototype.hasOwnProperty.call("+m+", '"+e.util.escapeQuotes(ue)+"') "),a+=" ) { ");a+=" "+oe+" } "}}R&&(a+=" if ("+_+") { ",p+="}")}}if(N.length){var it=N;if(it)for(var $e,Ia=-1,ts=it.length-1;Ia0||Ue===!1:e.util.schemaHasRules(Ue,e.RULES.all)){d.schema=Ue,d.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty($e),d.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment($e),H?a+=" "+E+" = "+E+" || Object.keys("+m+"); for (var "+x+"=0; "+x+"<"+E+".length; "+x+"++) { var "+g+" = "+E+"["+x+"]; ":a+=" for (var "+g+" in "+m+") { ",a+=" if ("+e.usePattern($e)+".test("+g+")) { ",d.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers);var Se=m+"["+g+"]";d.dataPathArr[$]=g;var oe=e.validate(d);d.baseId=Y,e.util.varOccurences(oe,O)<2?a+=" "+e.util.varReplace(oe,O,Se)+" ":a+=" var "+O+" = "+Se+"; "+oe+" ",R&&(a+=" if (!"+_+") break; "),a+=" } ",R&&(a+=" else "+_+" = true; "),a+=" } ",R&&(a+=" if ("+_+") { ",p+="}")}}}return R&&(a+=" "+p+" if ("+b+" == errors) {"),a}}),Eo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="errs__"+o,d=e.util.copy(e),p="";d.level++;var _="valid"+d.level;if(a+="var "+b+" = errors;",e.opts.strictKeywords?typeof l=="object"&&Object.keys(l).length>0||l===!1:e.util.schemaHasRules(l,e.RULES.all)){d.schema=l,d.schemaPath=f,d.errSchemaPath=y;var g="key"+o,x="idx"+o,$="i"+o,O="' + "+g+" + '",E=d.dataLevel=e.dataLevel+1,T="data"+E,A="dataProperties"+o,N=e.opts.ownProperties,F=e.baseId;N&&(a+=" var "+A+" = undefined; "),N?a+=" "+A+" = "+A+" || Object.keys("+m+"); for (var "+x+"=0; "+x+"<"+A+".length; "+x+"++) { var "+g+" = "+A+"["+x+"]; ":a+=" for (var "+g+" in "+m+") { ",a+=" var startErrs"+o+" = errors; ";var j=g,w=e.compositeRule;e.compositeRule=d.compositeRule=!0;var k=e.validate(d);d.baseId=F,e.util.varOccurences(k,T)<2?a+=" "+e.util.varReplace(k,T,j)+" ":a+=" var "+T+" = "+j+"; "+k+" ",e.compositeRule=d.compositeRule=w,a+=" if (!"+_+") { for (var "+$+"=startErrs"+o+"; "+$+"{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="valid"+o,d=e.opts.$data&&l&&l.$data,p;d?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",p="schema"+o):p=l;var _="schema"+o;if(!d)if(l.length0||T===!1:e.util.schemaHasRules(T,e.RULES.all))||(g[g.length]=$)}}else var g=l;if(d||g.length){var A=e.errorPath,N=d||g.length>=e.opts.loopRequired,F=e.opts.ownProperties;if(R)if(a+=" var missing"+o+"; ",N){d||(a+=" var "+_+" = validate.schema"+f+"; ");var j="i"+o,w="schema"+o+"["+j+"]",k="' + "+w+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(A,w,e.opts.jsonPointers)),a+=" var "+b+" = true; ",d&&(a+=" if (schema"+o+" === undefined) "+b+" = true; else if (!Array.isArray(schema"+o+")) "+b+" = false; else {"),a+=" for (var "+j+" = 0; "+j+" < "+_+".length; "+j+"++) { "+b+" = "+m+"["+_+"["+j+"]] !== undefined ",F&&(a+=" && Object.prototype.hasOwnProperty.call("+m+", "+_+"["+j+"]) "),a+="; if (!"+b+") break; } ",d&&(a+=" } "),a+=" if (!"+b+") { ";var D=D||[];D.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { missingProperty: '"+k+"' } ",e.opts.messages!==!1&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+k+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var z=a;a=D.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+z+"]); ":a+=" validate.errors = ["+z+"]; return false; ":a+=" var err = "+z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else{a+=" if ( ";var H=g;if(H)for(var Y,j=-1,_e=H.length-1;j<_e;){Y=H[j+=1],j&&(a+=" || ");var se=e.util.getProperty(Y),ve=m+se;a+=" ( ( "+ve+" === undefined ",F&&(a+=" || ! Object.prototype.hasOwnProperty.call("+m+", '"+e.util.escapeQuotes(Y)+"') "),a+=") && (missing"+o+" = "+e.util.toQuotedString(e.opts.jsonPointers?Y:se)+") ) "}a+=") { ";var w="missing"+o,k="' + "+w+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(A,w,!0):A+" + "+w);var D=D||[];D.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { missingProperty: '"+k+"' } ",e.opts.messages!==!1&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+k+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var z=a;a=D.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+z+"]); ":a+=" validate.errors = ["+z+"]; return false; ":a+=" var err = "+z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else if(N){d||(a+=" var "+_+" = validate.schema"+f+"; ");var j="i"+o,w="schema"+o+"["+j+"]",k="' + "+w+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(A,w,e.opts.jsonPointers)),d&&(a+=" if ("+_+" && !Array.isArray("+_+")) { var err = ",e.createErrors!==!1?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { missingProperty: '"+k+"' } ",e.opts.messages!==!1&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+k+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+_+" !== undefined) { "),a+=" for (var "+j+" = 0; "+j+" < "+_+".length; "+j+"++) { if ("+m+"["+_+"["+j+"]] === undefined ",F&&(a+=" || ! Object.prototype.hasOwnProperty.call("+m+", "+_+"["+j+"]) "),a+=") { var err = ",e.createErrors!==!1?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { missingProperty: '"+k+"' } ",e.opts.messages!==!1&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+k+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",d&&(a+=" } ")}else{var le=g;if(le)for(var Y,ue=-1,Be=le.length-1;ue{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m="data"+(c||""),b="valid"+o,d=e.opts.$data&&l&&l.$data,p;if(d?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",p="schema"+o):p=l,(l||d)&&e.opts.uniqueItems!==!1){d&&(a+=" var "+b+"; if ("+p+" === false || "+p+" === undefined) "+b+" = true; else if (typeof "+p+" != 'boolean') "+b+" = false; else { "),a+=" var i = "+m+".length , "+b+" = true , j; if (i > 1) { ";var _=e.schema.items&&e.schema.items.type,g=Array.isArray(_);if(!_||_=="object"||_=="array"||g&&(_.indexOf("object")>=0||_.indexOf("array")>=0))a+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+m+"[i], "+m+"[j])) { "+b+" = false; break outer; } } } ";else{a+=" var itemIndices = {}, item; for (;i--;) { var item = "+m+"[i]; ";var x="checkDataType"+(g?"s":"");a+=" if ("+e.util[x](_,"item",e.opts.strictNumbers,!0)+") continue; ",g&&(a+=` if (typeof item == 'string') item = '"' + item; `),a+=" if (typeof itemIndices[item] == 'number') { "+b+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}a+=" } ",d&&(a+=" } "),a+=" if (!"+b+") { ";var $=$||[];$.push(a),a="",e.createErrors!==!1?(a+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(a+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(a+=" , schema: ",d?a+="validate.schema"+f:a+=""+l,a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var O=a;a=$.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+O+"]); ":a+=" validate.errors = ["+O+"]; return false; ":a+=" var err = "+O+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",R&&(a+=" else { ")}else R&&(a+=" if (true) { ");return a}}),Ro=ce((s,t)=>{t.exports={$ref:io(),allOf:oo(),anyOf:lo(),$comment:co(),const:uo(),contains:fo(),dependencies:ho(),enum:po(),format:mo(),if:vo(),items:go(),maximum:rn(),minimum:rn(),maxItems:an(),minItems:an(),maxLength:sn(),minLength:sn(),maxProperties:nn(),minProperties:nn(),multipleOf:yo(),not:_o(),oneOf:bo(),pattern:So(),properties:xo(),propertyNames:Eo(),required:wo(),uniqueItems:Po(),validate:wn()}}),To=ce((s,t)=>{var r=Ro(),e=Yr().toHash;t.exports=function(){var i=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],a=["type","$comment"],o=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],c=["number","integer","string","array","object","boolean","null"];return i.all=e(a),i.types=e(c),i.forEach(function(l){l.rules=l.rules.map(function(f){var y;if(typeof f=="object"){var R=Object.keys(f)[0];y=f[R],f=R,y.forEach(function(b){a.push(b),i.all[b]=!0})}a.push(f);var m=i.all[f]={keyword:f,code:r[f],implements:y};return m}),i.all.$comment={keyword:"$comment",code:r.$comment},l.type&&(i.types[l.type]=l)}),i.keywords=e(a.concat(o)),i.custom={},i}}),ko=ce((s,t)=>{var r=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];t.exports=function(e,n){for(var i=0;i{var r=ks().MissingRef;t.exports=e;function e(n,i,a){var o=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof i=="function"&&(a=i,i=void 0);var c=l(n).then(function(){var y=o._addSchema(n,void 0,i);return y.validate||f(y)});return a&&c.then(function(y){a(null,y)},a),c;function l(y){var R=y.$schema;return R&&!o.getSchema(R)?e.call(o,{$ref:R},!0):Promise.resolve()}function f(y){try{return o._compile(y)}catch(m){if(m instanceof r)return R(m);throw m}function R(m){var b=m.missingSchema;if(_(b))throw new Error("Schema "+b+" is loaded but "+m.missingRef+" cannot be resolved");var d=o._loadingSchemas[b];return d||(d=o._loadingSchemas[b]=o._opts.loadSchema(b),d.then(p,p)),d.then(function(g){if(!_(b))return l(g).then(function(){_(b)||o.addSchema(g,b,void 0,i)})}).then(function(){return f(y)});function p(){delete o._loadingSchemas[b]}function _(g){return o._refs[g]||o._schemas[g]}}}}}),Oo=ce((s,t)=>{t.exports=function(e,n,i){var a=" ",o=e.level,c=e.dataLevel,l=e.schema[n],f=e.schemaPath+e.util.getProperty(n),y=e.errSchemaPath+"/"+n,R=!e.opts.allErrors,m,b="data"+(c||""),d="valid"+o,p="errs__"+o,_=e.opts.$data&&l&&l.$data,g;_?(a+=" var schema"+o+" = "+e.util.getData(l.$data,c,e.dataPathArr)+"; ",g="schema"+o):g=l;var x=this,$="definition"+o,O=x.definition,E="",T,A,N,F,j;if(_&&O.$data){j="keywordValidate"+o;var w=O.validateSchema;a+=" var "+$+" = RULES.custom['"+n+"'].definition; var "+j+" = "+$+".validate;"}else{if(F=e.useCustomRule(x,l,e.schema,e),!F)return;g="validate.schema"+f,j=F.code,T=O.compile,A=O.inline,N=O.macro}var k=j+".errors",D="i"+o,z="ruleErr"+o,H=O.async;if(H&&!e.async)throw new Error("async keyword in sync schema");if(A||N||(a+=""+k+" = null;"),a+="var "+p+" = errors;var "+d+";",_&&O.$data&&(E+="}",a+=" if ("+g+" === undefined) { "+d+" = true; } else { ",w&&(E+="}",a+=" "+d+" = "+$+".validateSchema("+g+"); if ("+d+") { ")),A)O.statements?a+=" "+F.validate+" ":a+=" "+d+" = "+F.validate+"; ";else if(N){var Y=e.util.copy(e),E="";Y.level++;var _e="valid"+Y.level;Y.schema=F.validate,Y.schemaPath="";var se=e.compositeRule;e.compositeRule=Y.compositeRule=!0;var ve=e.validate(Y).replace(/validate\.schema/g,j);e.compositeRule=Y.compositeRule=se,a+=" "+ve}else{var le=le||[];le.push(a),a="",a+=" "+j+".call( ",e.opts.passContext?a+="this":a+="self",T||O.schema===!1?a+=" , "+b+" ":a+=" , "+g+" , "+b+" , validate.schema"+e.schemaPath+" ",a+=" , (dataPath || '')",e.errorPath!='""'&&(a+=" + "+e.errorPath);var ue=c?"data"+(c-1||""):"parentData",Be=c?e.dataPathArr[c]:"parentDataProperty";a+=" , "+ue+" , "+Be+" , rootData ) ";var We=a;a=le.pop(),O.errors===!1?(a+=" "+d+" = ",H&&(a+="await "),a+=""+We+"; "):H?(k="customErrors"+o,a+=" var "+k+" = null; try { "+d+" = await "+We+"; } catch (e) { "+d+" = false; if (e instanceof ValidationError) "+k+" = e.errors; else throw e; } "):a+=" "+k+" = null; "+d+" = "+We+"; "}if(O.modifying&&(a+=" if ("+ue+") "+b+" = "+ue+"["+Be+"];"),a+=""+E,O.valid)R&&(a+=" if (true) { ");else{a+=" if ( ",O.valid===void 0?(a+=" !",N?a+=""+_e:a+=""+d):a+=" "+!O.valid+" ",a+=") { ",m=x.keyword;var le=le||[];le.push(a),a="";var le=le||[];le.push(a),a="",e.createErrors!==!1?(a+=" { keyword: '"+(m||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(y)+" , params: { keyword: '"+x.keyword+"' } ",e.opts.messages!==!1&&(a+=` , message: 'should pass "`+x.keyword+`" keyword validation' `),e.opts.verbose&&(a+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+b+" "),a+=" } "):a+=" {} ";var Qe=a;a=le.pop(),!e.compositeRule&&R?e.async?a+=" throw new ValidationError(["+Qe+"]); ":a+=" validate.errors = ["+Qe+"]; return false; ":a+=" var err = "+Qe+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var $e=a;a=le.pop(),A?O.errors?O.errors!="full"&&(a+=" for (var "+D+"="+p+"; "+D+"{t.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}}),Io=ce((s,t)=>{var r=Pn();t.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:r.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:r.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}}),$o=ce((s,t)=>{var r=/^[a-z_$][a-z0-9_$-]*$/i,e=Oo(),n=Io();t.exports={add:i,get:a,remove:o,validate:c};function i(l,f){var y=this.RULES;if(y.keywords[l])throw new Error("Keyword "+l+" is already defined");if(!r.test(l))throw new Error("Keyword "+l+" is not a valid identifier");if(f){this.validateKeyword(f,!0);var R=f.type;if(Array.isArray(R))for(var m=0;m{t.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),jo=ce((s,t)=>{var r=ao(),e=Ts(),n=so(),i=xn(),a=En(),o=no(),c=To(),l=ko(),f=Yr();t.exports=p,p.prototype.validate=_,p.prototype.compile=g,p.prototype.addSchema=x,p.prototype.addMetaSchema=$,p.prototype.validateSchema=O,p.prototype.getSchema=T,p.prototype.removeSchema=F,p.prototype.addFormat=se,p.prototype.errorsText=_e,p.prototype._addSchema=w,p.prototype._compile=k,p.prototype.compileAsync=Co();var y=$o();p.prototype.addKeyword=y.add,p.prototype.getKeyword=y.get,p.prototype.removeKeyword=y.remove,p.prototype.validateKeyword=y.validate;var R=ks();p.ValidationError=R.Validation,p.MissingRefError=R.MissingRef,p.$dataMetaSchema=l;var m="http://json-schema.org/draft-07/schema",b=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],d=["/properties"];function p(P){if(!(this instanceof p))return new p(P);P=this._opts=f.copy(P)||{},$e(this),this._schemas={},this._refs={},this._fragments={},this._formats=o(P.format),this._cache=P.cache||new n,this._loadingSchemas={},this._compilations=[],this.RULES=c(),this._getId=D(P),P.loopRequired=P.loopRequired||1/0,P.errorDataPath=="property"&&(P._errorDataPathProperty=!0),P.serialize===void 0&&(P.serialize=a),this._metaOpts=Qe(this),P.formats&&ue(this),P.keywords&&Be(this),ve(this),typeof P.meta=="object"&&this.addMetaSchema(P.meta),P.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),le(this)}function _(P,M){var X;if(typeof P=="string"){if(X=this.getSchema(P),!X)throw new Error('no schema with key or ref "'+P+'"')}else{var de=this._addSchema(P);X=de.validate||this._compile(de)}var L=X(M);return X.$async!==!0&&(this.errors=X.errors),L}function g(P,M){var X=this._addSchema(P,void 0,M);return X.validate||this._compile(X)}function x(P,M,X,de){if(Array.isArray(P)){for(var L=0;L-1}var rc=tc;function ac(s,t){var r=this.__data__,e=Za(r,s);return e<0?(++this.size,r.push([s,t])):r[e][1]=t,this}var sc=ac;function ea(s){var t=-1,r=s==null?0:s.length;for(this.clear();++t{if(!s||s.trim()==="")return null;let t=s.split(",").map(i=>i.trim()).filter(Boolean);if(t.length===0)return null;let r=t.some(i=>i.startsWith("!")),e=t.some(i=>!i.startsWith("!"));if(r&&e)return null;let n=t.map(i=>i.replace(/^!/,"").toLowerCase());return{include:r?[]:n,exclude:r?n:[],isExclusive:r}});function Pc(){return process.env.CLAUDE_CONFIG_DIR??Ec(wc(),".claude")}function un(s){if(!s)return!1;if(typeof s=="boolean")return s;let t=s.toLowerCase().trim();return["1","true","yes","on"].includes(t)}var kc={name:"BASH_MAX_OUTPUT_LENGTH",default:3e4,validate:s=>{if(!s)return{effective:3e4,status:"valid"};let e=parseInt(s,10);return isNaN(e)||e<=0?{effective:3e4,status:"invalid",message:`Invalid value "${s}" (using default: 30000)`}:e>15e4?{effective:15e4,status:"capped",message:`Capped from ${e} to 150000`}:{effective:e,status:"valid"}}},Cc={name:"CLAUDE_CODE_MAX_OUTPUT_TOKENS",default:32e3,validate:s=>{if(!s)return{effective:32e3,status:"valid"};let t=parseInt(s,10);return isNaN(t)||t<=0?{effective:32e3,status:"invalid",message:`Invalid value "${s}" (using default: 32000)`}:t>32e3?{effective:32e3,status:"capped",message:`Capped from ${t} to 32000`}:{effective:t,status:"valid"}}};function Oc(){return{originalCwd:dn(),totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,startTime:Date.now(),lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:dn(),modelUsage:{},mainLoopModelOverride:void 0,maxRateLimitFallbackActive:!1,initialMainLoopModel:null,modelStrings:null,isNonInteractiveSession:!0,isInteractive:!1,clientType:"cli",sessionIngressToken:void 0,oauthTokenFromFd:void 0,apiKeyFromFd:void 0,flagSettingsPath:void 0,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,sessionId:Tc(),loggerProvider:null,eventLogger:null,meterProvider:null,agentColorMap:new Map,agentColorIndex:0,envVarValidators:[kc,Cc],lastAPIRequest:null,inMemoryErrorLog:[]}}var Ic=Oc();function $c(){return Ic.sessionId}var sp=wa(()=>un(process.env.DEBUG)||un(process.env.DEBUG_SDK)||process.argv.includes("--debug")||process.argv.includes("-d")||Ac()||process.argv.some(s=>s.startsWith("--debug="))),np=wa(()=>{let s=process.argv.find(r=>r.startsWith("--debug="));if(!s)return null;let t=s.substring(8);return xc(t)}),Ac=wa(()=>process.argv.includes("--debug-to-stderr")||process.argv.includes("-d2e"));function jc(){return process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??On(Pc(),"debug",`${$c()}.txt`)}var ip=wa(()=>{try{let s=jc(),t=Rc(s),r=On(t,"latest");if(ga().existsSync(t)||ga().mkdirSync(t),ga().existsSync(r))try{ga().unlinkSync(r)}catch{}ga().symlinkSync(s,r)}catch{}});var u={};Xi(u,{void:()=>yu,util:()=>Ee,unknown:()=>vu,union:()=>xu,undefined:()=>hu,tuple:()=>Pu,transformer:()=>pn,symbol:()=>fu,string:()=>Fn,strictObject:()=>Su,setErrorMap:()=>Fc,set:()=>ku,record:()=>Ru,quotelessJson:()=>Nc,promise:()=>ju,preprocess:()=>Fu,pipeline:()=>Mu,ostring:()=>Lu,optional:()=>Nu,onumber:()=>qu,oboolean:()=>zu,objectUtil:()=>us,object:()=>bu,number:()=>Mn,nullable:()=>Du,null:()=>pu,never:()=>gu,nativeEnum:()=>Au,nan:()=>cu,map:()=>Tu,makeIssue:()=>Ma,literal:()=>Iu,lazy:()=>Ou,late:()=>ou,isValid:()=>ar,isDirty:()=>fs,isAsync:()=>ba,isAborted:()=>ds,intersection:()=>wu,instanceof:()=>lu,getParsedType:()=>Lt,getErrorMap:()=>Fa,function:()=>Cu,enum:()=>$u,effect:()=>pn,discriminatedUnion:()=>Eu,defaultErrorMap:()=>Br,datetimeRegex:()=>jn,date:()=>du,custom:()=>Dn,coerce:()=>Uu,boolean:()=>Ln,bigint:()=>uu,array:()=>_u,any:()=>mu,addIssueToContext:()=>Q,ZodVoid:()=>Gr,ZodUnknown:()=>qt,ZodUnion:()=>ur,ZodUndefined:()=>lr,ZodType:()=>fe,ZodTuple:()=>Ct,ZodTransformer:()=>dt,ZodSymbol:()=>Qr,ZodString:()=>Bt,ZodSet:()=>Wr,ZodSchema:()=>fe,ZodRecord:()=>qa,ZodReadonly:()=>yr,ZodPromise:()=>Gt,ZodPipeline:()=>xa,ZodParsedType:()=>K,ZodOptional:()=>ut,ZodObject:()=>rt,ZodNumber:()=>sr,ZodNullable:()=>Ot,ZodNull:()=>cr,ZodNever:()=>wt,ZodNativeEnum:()=>mr,ZodNaN:()=>Kr,ZodMap:()=>Jr,ZodLiteral:()=>hr,ZodLazy:()=>fr,ZodIssueCode:()=>U,ZodIntersection:()=>dr,ZodFunction:()=>za,ZodFirstPartyTypeKind:()=>Z,ZodError:()=>ct,ZodEnum:()=>pr,ZodEffects:()=>dt,ZodDiscriminatedUnion:()=>La,ZodDefault:()=>vr,ZodDate:()=>or,ZodCatch:()=>gr,ZodBranded:()=>Sa,ZodBoolean:()=>ir,ZodBigInt:()=>nr,ZodArray:()=>zt,ZodAny:()=>Qt,Schema:()=>fe,ParseStatus:()=>Ke,OK:()=>tt,NEVER:()=>Zu,INVALID:()=>ae,EMPTY_PATH:()=>Mc,DIRTY:()=>Hr,BRAND:()=>iu});var Ee;(function(s){s.assertEqual=n=>{};function t(n){}s.assertIs=t;function r(n){throw new Error}s.assertNever=r,s.arrayToEnum=n=>{let i={};for(let a of n)i[a]=a;return i},s.getValidEnumValues=n=>{let i=s.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),a={};for(let o of i)a[o]=n[o];return s.objectValues(a)},s.objectValues=n=>s.objectKeys(n).map(function(i){return n[i]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&i.push(a);return i},s.find=(n,i)=>{for(let a of n)if(i(a))return a},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function e(n,i=" | "){return n.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}s.joinValues=e,s.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(Ee||(Ee={}));var us;(function(s){s.mergeShapes=(t,r)=>({...t,...r})})(us||(us={}));var K=Ee.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Lt=s=>{switch(typeof s){case"undefined":return K.undefined;case"string":return K.string;case"number":return Number.isNaN(s)?K.nan:K.number;case"boolean":return K.boolean;case"function":return K.function;case"bigint":return K.bigint;case"symbol":return K.symbol;case"object":return Array.isArray(s)?K.array:s===null?K.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?K.promise:typeof Map<"u"&&s instanceof Map?K.map:typeof Set<"u"&&s instanceof Set?K.set:typeof Date<"u"&&s instanceof Date?K.date:K.object;default:return K.unknown}},U=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"]),Nc=s=>JSON.stringify(s,null,2).replace(/"([^"]+)":/g,"$1:"),ct=class s extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(i){return i.message},e={_errors:[]},n=i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(n);else if(a.code==="invalid_return_type")n(a.returnTypeError);else if(a.code==="invalid_arguments")n(a.argumentsError);else if(a.path.length===0)e._errors.push(r(a));else{let o=e,c=0;for(;cr.message){let r={},e=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(t(n))}else e.push(t(n));return{formErrors:e,fieldErrors:r}}get formErrors(){return this.flatten()}};ct.create=s=>new ct(s);var Dc=(s,t)=>{let r;switch(s.code){case U.invalid_type:s.received===K.undefined?r="Required":r=`Expected ${s.expected}, received ${s.received}`;break;case U.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(s.expected,Ee.jsonStringifyReplacer)}`;break;case U.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ee.joinValues(s.keys,", ")}`;break;case U.invalid_union:r="Invalid input";break;case U.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ee.joinValues(s.options)}`;break;case U.invalid_enum_value:r=`Invalid enum value. Expected ${Ee.joinValues(s.options)}, received '${s.received}'`;break;case U.invalid_arguments:r="Invalid function arguments";break;case U.invalid_return_type:r="Invalid function return type";break;case U.invalid_date:r="Invalid date";break;case U.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(r=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?r=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?r=`Invalid input: must end with "${s.validation.endsWith}"`:Ee.assertNever(s.validation):s.validation!=="regex"?r=`Invalid ${s.validation}`:r="Invalid";break;case U.too_small:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:r="Invalid input";break;case U.too_big:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?r=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:r="Invalid input";break;case U.custom:r="Invalid input";break;case U.invalid_intersection_types:r="Intersection results could not be merged";break;case U.not_multiple_of:r=`Number must be a multiple of ${s.multipleOf}`;break;case U.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ee.assertNever(s)}return{message:r}},Br=Dc,In=Br;function Fc(s){In=s}function Fa(){return In}var Ma=s=>{let{data:t,path:r,errorMaps:e,issueData:n}=s,i=[...r,...n.path||[]],a={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let o="",c=e.filter(l=>!!l).slice().reverse();for(let l of c)o=l(a,{data:t,defaultError:o}).message;return{...n,path:i,message:o}},Mc=[];function Q(s,t){let r=Fa(),e=Ma({issueData:t,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,r,r===Br?void 0:Br].filter(n=>!!n)});s.common.issues.push(e)}var Ke=class s{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let e=[];for(let n of r){if(n.status==="aborted")return ae;n.status==="dirty"&&t.dirty(),e.push(n.value)}return{status:t.value,value:e}}static async mergeObjectAsync(t,r){let e=[];for(let n of r){let i=await n.key,a=await n.value;e.push({key:i,value:a})}return s.mergeObjectSync(t,e)}static mergeObjectSync(t,r){let e={};for(let n of r){let{key:i,value:a}=n;if(i.status==="aborted"||a.status==="aborted")return ae;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||n.alwaysSet)&&(e[i.value]=a.value)}return{status:t.value,value:e}}},ae=Object.freeze({status:"aborted"}),Hr=s=>({status:"dirty",value:s}),tt=s=>({status:"valid",value:s}),ds=s=>s.status==="aborted",fs=s=>s.status==="dirty",ar=s=>s.status==="valid",ba=s=>typeof Promise<"u"&&s instanceof Promise,te;(function(s){s.errToObj=t=>typeof t=="string"?{message:t}:t||{},s.toString=t=>typeof t=="string"?t:t?.message})(te||(te={}));var mt=class{constructor(t,r,e,n){this._cachedPath=[],this.parent=t,this.data=r,this._path=e,this._key=n}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}},fn=(s,t)=>{if(ar(t))return{success:!0,data:t.value};if(!s.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 ct(s.common.issues);return this._error=r,this._error}}};function he(s){if(!s)return{};let{errorMap:t,invalid_type_error:r,required_error:e,description:n}=s;if(t&&(r||e))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:n}:{errorMap:(a,o)=>{let{message:c}=s;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??e??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:n}}var fe=class{get description(){return this._def.description}_getType(t){return Lt(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Lt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Ke,ctx:{common:t.parent.common,data:t.data,parsedType:Lt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(ba(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let e=this.safeParse(t,r);if(e.success)return e.data;throw e.error}safeParse(t,r){let e={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Lt(t)},n=this._parseSync({data:t,path:e.path,parent:e});return fn(e,n)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Lt(t)};if(!this["~standard"].async)try{let e=this._parseSync({data:t,path:[],parent:r});return ar(e)?{value:e.value}:{issues:r.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(e=>ar(e)?{value:e.value}:{issues:r.common.issues})}async parseAsync(t,r){let e=await this.safeParseAsync(t,r);if(e.success)return e.data;throw e.error}async safeParseAsync(t,r){let e={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Lt(t)},n=this._parse({data:t,path:e.path,parent:e}),i=await(ba(n)?n:Promise.resolve(n));return fn(e,i)}refine(t,r){let e=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,i)=>{let a=t(n),o=()=>i.addIssue({code:U.custom,...e(n)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(t,r){return this._refinement((e,n)=>t(e)?!0:(n.addIssue(typeof r=="function"?r(e,n):r),!1))}_refinement(t){return new dt({schema:this,typeName:Z.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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 ut.create(this,this._def)}nullable(){return Ot.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zt.create(this)}promise(){return Gt.create(this,this._def)}or(t){return ur.create([this,t],this._def)}and(t){return dr.create(this,t,this._def)}transform(t){return new dt({...he(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new vr({...he(this._def),innerType:this,defaultValue:r,typeName:Z.ZodDefault})}brand(){return new Sa({typeName:Z.ZodBranded,type:this,...he(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new gr({...he(this._def),innerType:this,catchValue:r,typeName:Z.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return xa.create(this,t)}readonly(){return yr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Lc=/^c[^\s-]{8,}$/i,qc=/^[0-9a-z]+$/,zc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Uc=/^[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,Zc=/^[a-z0-9_-]{21}$/i,Vc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hc=/^[-+]?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)?)??$/,Bc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Qc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",is,Gc=/^(?:(?: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])$/,Jc=/^(?:(?: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])$/,Wc=/^(([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]))$/,Kc=/^(([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])$/,Yc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Xc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$n="((\\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])))",eu=new RegExp(`^${$n}$`);function An(s){let t="[0-5]\\d";s.precision?t=`${t}\\.\\d{${s.precision}}`:s.precision==null&&(t=`${t}(\\.\\d+)?`);let r=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function tu(s){return new RegExp(`^${An(s)}$`)}function jn(s){let t=`${$n}T${An(s)}`,r=[];return r.push(s.local?"Z?":"Z"),s.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function ru(s,t){return!!((t==="v4"||!t)&&Gc.test(s)||(t==="v6"||!t)&&Wc.test(s))}function au(s,t){if(!Vc.test(s))return!1;try{let[r]=s.split(".");if(!r)return!1;let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(e));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||t&&n.alg!==t)}catch{return!1}}function su(s,t){return!!((t==="v4"||!t)&&Jc.test(s)||(t==="v6"||!t)&&Kc.test(s))}var Bt=class s extends fe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==K.string){let i=this._getOrReturnCtx(t);return Q(i,{code:U.invalid_type,expected:K.string,received:i.parsedType}),ae}let e=new Ke,n;for(let i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(n=this._getOrReturnCtx(t,n),Q(n,{code:U.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),e.dirty());else if(i.kind==="length"){let a=t.data.length>i.value,o=t.data.lengtht.test(n),{validation:r,code:U.invalid_string,...te.errToObj(e)})}_addCheck(t){return new s({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...te.errToObj(t)})}url(t){return this._addCheck({kind:"url",...te.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...te.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...te.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...te.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...te.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...te.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...te.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...te.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...te.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...te.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...te.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...te.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...te.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...te.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...te.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...te.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...te.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...te.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...te.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...te.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...te.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...te.errToObj(r)})}nonempty(t){return this.min(1,te.errToObj(t))}trim(){return new s({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew Bt({checks:[],typeName:Z.ZodString,coerce:s?.coerce??!1,...he(s)});function nu(s,t){let r=(s.toString().split(".")[1]||"").length,e=(t.toString().split(".")[1]||"").length,n=r>e?r:e,i=Number.parseInt(s.toFixed(n).replace(".","")),a=Number.parseInt(t.toFixed(n).replace(".",""));return i%a/10**n}var sr=class s extends fe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==K.number){let i=this._getOrReturnCtx(t);return Q(i,{code:U.invalid_type,expected:K.number,received:i.parsedType}),ae}let e,n=new Ke;for(let i of this._def.checks)i.kind==="int"?Ee.isInteger(t.data)||(e=this._getOrReturnCtx(t,e),Q(e,{code:U.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(e=this._getOrReturnCtx(t,e),Q(e,{code:U.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?nu(t.data,i.value)!==0&&(e=this._getOrReturnCtx(t,e),Q(e,{code:U.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(e=this._getOrReturnCtx(t,e),Q(e,{code:U.not_finite,message:i.message}),n.dirty()):Ee.assertNever(i);return{status:n.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,te.toString(r))}gt(t,r){return this.setLimit("min",t,!1,te.toString(r))}lte(t,r){return this.setLimit("max",t,!0,te.toString(r))}lt(t,r){return this.setLimit("max",t,!1,te.toString(r))}setLimit(t,r,e,n){return new s({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:e,message:te.toString(n)}]})}_addCheck(t){return new s({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:te.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:te.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:te.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:te.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:te.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:te.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:te.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:te.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:te.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.valuet.kind==="int"||t.kind==="multipleOf"&&Ee.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let e of this._def.checks){if(e.kind==="finite"||e.kind==="int"||e.kind==="multipleOf")return!0;e.kind==="min"?(r===null||e.value>r)&&(r=e.value):e.kind==="max"&&(t===null||e.valuenew sr({checks:[],typeName:Z.ZodNumber,coerce:s?.coerce||!1,...he(s)});var nr=class s extends fe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==K.bigint)return this._getInvalidInput(t);let e,n=new Ke;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(e=this._getOrReturnCtx(t,e),Q(e,{code:U.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(e=this._getOrReturnCtx(t,e),Q(e,{code:U.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):Ee.assertNever(i);return{status:n.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Q(r,{code:U.invalid_type,expected:K.bigint,received:r.parsedType}),ae}gte(t,r){return this.setLimit("min",t,!0,te.toString(r))}gt(t,r){return this.setLimit("min",t,!1,te.toString(r))}lte(t,r){return this.setLimit("max",t,!0,te.toString(r))}lt(t,r){return this.setLimit("max",t,!1,te.toString(r))}setLimit(t,r,e,n){return new s({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:e,message:te.toString(n)}]})}_addCheck(t){return new s({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:te.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:te.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:te.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:te.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:te.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew nr({checks:[],typeName:Z.ZodBigInt,coerce:s?.coerce??!1,...he(s)});var ir=class extends fe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==K.boolean){let e=this._getOrReturnCtx(t);return Q(e,{code:U.invalid_type,expected:K.boolean,received:e.parsedType}),ae}return tt(t.data)}};ir.create=s=>new ir({typeName:Z.ZodBoolean,coerce:s?.coerce||!1,...he(s)});var or=class s extends fe{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==K.date){let i=this._getOrReturnCtx(t);return Q(i,{code:U.invalid_type,expected:K.date,received:i.parsedType}),ae}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return Q(i,{code:U.invalid_date}),ae}let e=new Ke,n;for(let i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(n=this._getOrReturnCtx(t,n),Q(n,{code:U.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),e.dirty()):Ee.assertNever(i);return{status:e.value,value:new Date(t.data.getTime())}}_addCheck(t){return new s({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:te.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:te.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew or({checks:[],coerce:s?.coerce||!1,typeName:Z.ZodDate,...he(s)});var Qr=class extends fe{_parse(t){if(this._getType(t)!==K.symbol){let e=this._getOrReturnCtx(t);return Q(e,{code:U.invalid_type,expected:K.symbol,received:e.parsedType}),ae}return tt(t.data)}};Qr.create=s=>new Qr({typeName:Z.ZodSymbol,...he(s)});var lr=class extends fe{_parse(t){if(this._getType(t)!==K.undefined){let e=this._getOrReturnCtx(t);return Q(e,{code:U.invalid_type,expected:K.undefined,received:e.parsedType}),ae}return tt(t.data)}};lr.create=s=>new lr({typeName:Z.ZodUndefined,...he(s)});var cr=class extends fe{_parse(t){if(this._getType(t)!==K.null){let e=this._getOrReturnCtx(t);return Q(e,{code:U.invalid_type,expected:K.null,received:e.parsedType}),ae}return tt(t.data)}};cr.create=s=>new cr({typeName:Z.ZodNull,...he(s)});var Qt=class extends fe{constructor(){super(...arguments),this._any=!0}_parse(t){return tt(t.data)}};Qt.create=s=>new Qt({typeName:Z.ZodAny,...he(s)});var qt=class extends fe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return tt(t.data)}};qt.create=s=>new qt({typeName:Z.ZodUnknown,...he(s)});var wt=class extends fe{_parse(t){let r=this._getOrReturnCtx(t);return Q(r,{code:U.invalid_type,expected:K.never,received:r.parsedType}),ae}};wt.create=s=>new wt({typeName:Z.ZodNever,...he(s)});var Gr=class extends fe{_parse(t){if(this._getType(t)!==K.undefined){let e=this._getOrReturnCtx(t);return Q(e,{code:U.invalid_type,expected:K.void,received:e.parsedType}),ae}return tt(t.data)}};Gr.create=s=>new Gr({typeName:Z.ZodVoid,...he(s)});var zt=class s extends fe{_parse(t){let{ctx:r,status:e}=this._processInputParams(t),n=this._def;if(r.parsedType!==K.array)return Q(r,{code:U.invalid_type,expected:K.array,received:r.parsedType}),ae;if(n.exactLength!==null){let a=r.data.length>n.exactLength.value,o=r.data.lengthn.maxLength.value&&(Q(r,{code:U.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),e.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>n.type._parseAsync(new mt(r,a,r.path,o)))).then(a=>Ke.mergeArray(e,a));let i=[...r.data].map((a,o)=>n.type._parseSync(new mt(r,a,r.path,o)));return Ke.mergeArray(e,i)}get element(){return this._def.type}min(t,r){return new s({...this._def,minLength:{value:t,message:te.toString(r)}})}max(t,r){return new s({...this._def,maxLength:{value:t,message:te.toString(r)}})}length(t,r){return new s({...this._def,exactLength:{value:t,message:te.toString(r)}})}nonempty(t){return this.min(1,t)}};zt.create=(s,t)=>new zt({type:s,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...he(t)});function Vr(s){if(s instanceof rt){let t={};for(let r in s.shape){let e=s.shape[r];t[r]=ut.create(Vr(e))}return new rt({...s._def,shape:()=>t})}else return s instanceof zt?new zt({...s._def,type:Vr(s.element)}):s instanceof ut?ut.create(Vr(s.unwrap())):s instanceof Ot?Ot.create(Vr(s.unwrap())):s instanceof Ct?Ct.create(s.items.map(t=>Vr(t))):s}var rt=class s extends fe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Ee.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==K.object){let l=this._getOrReturnCtx(t);return Q(l,{code:U.invalid_type,expected:K.object,received:l.parsedType}),ae}let{status:e,ctx:n}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof wt&&this._def.unknownKeys==="strip"))for(let l in n.data)a.includes(l)||o.push(l);let c=[];for(let l of a){let f=i[l],y=n.data[l];c.push({key:{status:"valid",value:l},value:f._parse(new mt(n,y,n.path,l)),alwaysSet:l in n.data})}if(this._def.catchall instanceof wt){let l=this._def.unknownKeys;if(l==="passthrough")for(let f of o)c.push({key:{status:"valid",value:f},value:{status:"valid",value:n.data[f]}});else if(l==="strict")o.length>0&&(Q(n,{code:U.unrecognized_keys,keys:o}),e.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let f of o){let y=n.data[f];c.push({key:{status:"valid",value:f},value:l._parse(new mt(n,y,n.path,f)),alwaysSet:f in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let l=[];for(let f of c){let y=await f.key,R=await f.value;l.push({key:y,value:R,alwaysSet:f.alwaysSet})}return l}).then(l=>Ke.mergeObjectSync(e,l)):Ke.mergeObjectSync(e,c)}get shape(){return this._def.shape()}strict(t){return te.errToObj,new s({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,e)=>{let n=this._def.errorMap?.(r,e).message??e.defaultError;return r.code==="unrecognized_keys"?{message:te.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new s({...this._def,unknownKeys:"strip"})}passthrough(){return new s({...this._def,unknownKeys:"passthrough"})}extend(t){return new s({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new s({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Z.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new s({...this._def,catchall:t})}pick(t){let r={};for(let e of Ee.objectKeys(t))t[e]&&this.shape[e]&&(r[e]=this.shape[e]);return new s({...this._def,shape:()=>r})}omit(t){let r={};for(let e of Ee.objectKeys(this.shape))t[e]||(r[e]=this.shape[e]);return new s({...this._def,shape:()=>r})}deepPartial(){return Vr(this)}partial(t){let r={};for(let e of Ee.objectKeys(this.shape)){let n=this.shape[e];t&&!t[e]?r[e]=n:r[e]=n.optional()}return new s({...this._def,shape:()=>r})}required(t){let r={};for(let e of Ee.objectKeys(this.shape))if(t&&!t[e])r[e]=this.shape[e];else{let i=this.shape[e];for(;i instanceof ut;)i=i._def.innerType;r[e]=i}return new s({...this._def,shape:()=>r})}keyof(){return Nn(Ee.objectKeys(this.shape))}};rt.create=(s,t)=>new rt({shape:()=>s,unknownKeys:"strip",catchall:wt.create(),typeName:Z.ZodObject,...he(t)});rt.strictCreate=(s,t)=>new rt({shape:()=>s,unknownKeys:"strict",catchall:wt.create(),typeName:Z.ZodObject,...he(t)});rt.lazycreate=(s,t)=>new rt({shape:s,unknownKeys:"strip",catchall:wt.create(),typeName:Z.ZodObject,...he(t)});var ur=class extends fe{_parse(t){let{ctx:r}=this._processInputParams(t),e=this._def.options;function n(i){for(let o of i)if(o.result.status==="valid")return o.result;for(let o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(o=>new ct(o.ctx.common.issues));return Q(r,{code:U.invalid_union,unionErrors:a}),ae}if(r.common.async)return Promise.all(e.map(async i=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(n);{let i,a=[];for(let c of e){let l={...r,common:{...r.common,issues:[]},parent:null},f=c._parseSync({data:r.data,path:r.path,parent:l});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let o=a.map(c=>new ct(c));return Q(r,{code:U.invalid_union,unionErrors:o}),ae}}get options(){return this._def.options}};ur.create=(s,t)=>new ur({options:s,typeName:Z.ZodUnion,...he(t)});var Mt=s=>s instanceof fr?Mt(s.schema):s instanceof dt?Mt(s.innerType()):s instanceof hr?[s.value]:s instanceof pr?s.options:s instanceof mr?Ee.objectValues(s.enum):s instanceof vr?Mt(s._def.innerType):s instanceof lr?[void 0]:s instanceof cr?[null]:s instanceof ut?[void 0,...Mt(s.unwrap())]:s instanceof Ot?[null,...Mt(s.unwrap())]:s instanceof Sa||s instanceof yr?Mt(s.unwrap()):s instanceof gr?Mt(s._def.innerType):[],La=class s extends fe{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==K.object)return Q(r,{code:U.invalid_type,expected:K.object,received:r.parsedType}),ae;let e=this.discriminator,n=r.data[e],i=this.optionsMap.get(n);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(Q(r,{code:U.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[e]}),ae)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,e){let n=new Map;for(let i of r){let a=Mt(i.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of a){if(n.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);n.set(o,i)}}return new s({typeName:Z.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...he(e)})}};function hs(s,t){let r=Lt(s),e=Lt(t);if(s===t)return{valid:!0,data:s};if(r===K.object&&e===K.object){let n=Ee.objectKeys(t),i=Ee.objectKeys(s).filter(o=>n.indexOf(o)!==-1),a={...s,...t};for(let o of i){let c=hs(s[o],t[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(r===K.array&&e===K.array){if(s.length!==t.length)return{valid:!1};let n=[];for(let i=0;i{if(ds(i)||ds(a))return ae;let o=hs(i.value,a.value);return o.valid?((fs(i)||fs(a))&&r.dirty(),{status:r.value,value:o.data}):(Q(e,{code:U.invalid_intersection_types}),ae)};return e.common.async?Promise.all([this._def.left._parseAsync({data:e.data,path:e.path,parent:e}),this._def.right._parseAsync({data:e.data,path:e.path,parent:e})]).then(([i,a])=>n(i,a)):n(this._def.left._parseSync({data:e.data,path:e.path,parent:e}),this._def.right._parseSync({data:e.data,path:e.path,parent:e}))}};dr.create=(s,t,r)=>new dr({left:s,right:t,typeName:Z.ZodIntersection,...he(r)});var Ct=class s extends fe{_parse(t){let{status:r,ctx:e}=this._processInputParams(t);if(e.parsedType!==K.array)return Q(e,{code:U.invalid_type,expected:K.array,received:e.parsedType}),ae;if(e.data.lengththis._def.items.length&&(Q(e,{code:U.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...e.data].map((a,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new mt(e,a,e.path,o)):null}).filter(a=>!!a);return e.common.async?Promise.all(i).then(a=>Ke.mergeArray(r,a)):Ke.mergeArray(r,i)}get items(){return this._def.items}rest(t){return new s({...this._def,rest:t})}};Ct.create=(s,t)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:s,typeName:Z.ZodTuple,rest:null,...he(t)})};var qa=class s extends fe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:e}=this._processInputParams(t);if(e.parsedType!==K.object)return Q(e,{code:U.invalid_type,expected:K.object,received:e.parsedType}),ae;let n=[],i=this._def.keyType,a=this._def.valueType;for(let o in e.data)n.push({key:i._parse(new mt(e,o,e.path,o)),value:a._parse(new mt(e,e.data[o],e.path,o)),alwaysSet:o in e.data});return e.common.async?Ke.mergeObjectAsync(r,n):Ke.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,e){return r instanceof fe?new s({keyType:t,valueType:r,typeName:Z.ZodRecord,...he(e)}):new s({keyType:Bt.create(),valueType:t,typeName:Z.ZodRecord,...he(r)})}},Jr=class extends fe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:e}=this._processInputParams(t);if(e.parsedType!==K.map)return Q(e,{code:U.invalid_type,expected:K.map,received:e.parsedType}),ae;let n=this._def.keyType,i=this._def.valueType,a=[...e.data.entries()].map(([o,c],l)=>({key:n._parse(new mt(e,o,e.path,[l,"key"])),value:i._parse(new mt(e,c,e.path,[l,"value"]))}));if(e.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of a){let l=await c.key,f=await c.value;if(l.status==="aborted"||f.status==="aborted")return ae;(l.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(l.value,f.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of a){let l=c.key,f=c.value;if(l.status==="aborted"||f.status==="aborted")return ae;(l.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(l.value,f.value)}return{status:r.value,value:o}}}};Jr.create=(s,t,r)=>new Jr({valueType:t,keyType:s,typeName:Z.ZodMap,...he(r)});var Wr=class s extends fe{_parse(t){let{status:r,ctx:e}=this._processInputParams(t);if(e.parsedType!==K.set)return Q(e,{code:U.invalid_type,expected:K.set,received:e.parsedType}),ae;let n=this._def;n.minSize!==null&&e.data.sizen.maxSize.value&&(Q(e,{code:U.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let i=this._def.valueType;function a(c){let l=new Set;for(let f of c){if(f.status==="aborted")return ae;f.status==="dirty"&&r.dirty(),l.add(f.value)}return{status:r.value,value:l}}let o=[...e.data.values()].map((c,l)=>i._parse(new mt(e,c,e.path,l)));return e.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(t,r){return new s({...this._def,minSize:{value:t,message:te.toString(r)}})}max(t,r){return new s({...this._def,maxSize:{value:t,message:te.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Wr.create=(s,t)=>new Wr({valueType:s,minSize:null,maxSize:null,typeName:Z.ZodSet,...he(t)});var za=class s extends fe{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==K.function)return Q(r,{code:U.invalid_type,expected:K.function,received:r.parsedType}),ae;function e(o,c){return Ma({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fa(),Br].filter(l=>!!l),issueData:{code:U.invalid_arguments,argumentsError:c}})}function n(o,c){return Ma({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fa(),Br].filter(l=>!!l),issueData:{code:U.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Gt){let o=this;return tt(async function(...c){let l=new ct([]),f=await o._def.args.parseAsync(c,i).catch(m=>{throw l.addIssue(e(c,m)),l}),y=await Reflect.apply(a,this,f);return await o._def.returns._def.type.parseAsync(y,i).catch(m=>{throw l.addIssue(n(y,m)),l})})}else{let o=this;return tt(function(...c){let l=o._def.args.safeParse(c,i);if(!l.success)throw new ct([e(c,l.error)]);let f=Reflect.apply(a,this,l.data),y=o._def.returns.safeParse(f,i);if(!y.success)throw new ct([n(f,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new s({...this._def,args:Ct.create(t).rest(qt.create())})}returns(t){return new s({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,e){return new s({args:t||Ct.create([]).rest(qt.create()),returns:r||qt.create(),typeName:Z.ZodFunction,...he(e)})}},fr=class extends fe{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};fr.create=(s,t)=>new fr({getter:s,typeName:Z.ZodLazy,...he(t)});var hr=class extends fe{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Q(r,{received:r.data,code:U.invalid_literal,expected:this._def.value}),ae}return{status:"valid",value:t.data}}get value(){return this._def.value}};hr.create=(s,t)=>new hr({value:s,typeName:Z.ZodLiteral,...he(t)});function Nn(s,t){return new pr({values:s,typeName:Z.ZodEnum,...he(t)})}var pr=class s extends fe{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),e=this._def.values;return Q(r,{expected:Ee.joinValues(e),received:r.parsedType,code:U.invalid_type}),ae}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),e=this._def.values;return Q(r,{received:r.data,code:U.invalid_enum_value,options:e}),ae}return tt(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return s.create(t,{...this._def,...r})}exclude(t,r=this._def){return s.create(this.options.filter(e=>!t.includes(e)),{...this._def,...r})}};pr.create=Nn;var mr=class extends fe{_parse(t){let r=Ee.getValidEnumValues(this._def.values),e=this._getOrReturnCtx(t);if(e.parsedType!==K.string&&e.parsedType!==K.number){let n=Ee.objectValues(r);return Q(e,{expected:Ee.joinValues(n),received:e.parsedType,code:U.invalid_type}),ae}if(this._cache||(this._cache=new Set(Ee.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let n=Ee.objectValues(r);return Q(e,{received:e.data,code:U.invalid_enum_value,options:n}),ae}return tt(t.data)}get enum(){return this._def.values}};mr.create=(s,t)=>new mr({values:s,typeName:Z.ZodNativeEnum,...he(t)});var Gt=class extends fe{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==K.promise&&r.common.async===!1)return Q(r,{code:U.invalid_type,expected:K.promise,received:r.parsedType}),ae;let e=r.parsedType===K.promise?r.data:Promise.resolve(r.data);return tt(e.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Gt.create=(s,t)=>new Gt({type:s,typeName:Z.ZodPromise,...he(t)});var dt=class extends fe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:e}=this._processInputParams(t),n=this._def.effect||null,i={addIssue:a=>{Q(e,a),a.fatal?r.abort():r.dirty()},get path(){return e.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let a=n.transform(e.data,i);if(e.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return ae;let c=await this._def.schema._parseAsync({data:o,path:e.path,parent:e});return c.status==="aborted"?ae:c.status==="dirty"||r.value==="dirty"?Hr(c.value):c});{if(r.value==="aborted")return ae;let o=this._def.schema._parseSync({data:a,path:e.path,parent:e});return o.status==="aborted"?ae:o.status==="dirty"||r.value==="dirty"?Hr(o.value):o}}if(n.type==="refinement"){let a=o=>{let c=n.refinement(o,i);if(e.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(e.common.async===!1){let o=this._def.schema._parseSync({data:e.data,path:e.path,parent:e});return o.status==="aborted"?ae:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:e.data,path:e.path,parent:e}).then(o=>o.status==="aborted"?ae:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(n.type==="transform")if(e.common.async===!1){let a=this._def.schema._parseSync({data:e.data,path:e.path,parent:e});if(!ar(a))return ae;let o=n.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:e.data,path:e.path,parent:e}).then(a=>ar(a)?Promise.resolve(n.transform(a.value,i)).then(o=>({status:r.value,value:o})):ae);Ee.assertNever(n)}};dt.create=(s,t,r)=>new dt({schema:s,typeName:Z.ZodEffects,effect:t,...he(r)});dt.createWithPreprocess=(s,t,r)=>new dt({schema:t,effect:{type:"preprocess",transform:s},typeName:Z.ZodEffects,...he(r)});var ut=class extends fe{_parse(t){return this._getType(t)===K.undefined?tt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ut.create=(s,t)=>new ut({innerType:s,typeName:Z.ZodOptional,...he(t)});var Ot=class extends fe{_parse(t){return this._getType(t)===K.null?tt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ot.create=(s,t)=>new Ot({innerType:s,typeName:Z.ZodNullable,...he(t)});var vr=class extends fe{_parse(t){let{ctx:r}=this._processInputParams(t),e=r.data;return r.parsedType===K.undefined&&(e=this._def.defaultValue()),this._def.innerType._parse({data:e,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};vr.create=(s,t)=>new vr({innerType:s,typeName:Z.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...he(t)});var gr=class extends fe{_parse(t){let{ctx:r}=this._processInputParams(t),e={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:e.data,path:e.path,parent:{...e}});return ba(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ct(e.common.issues)},input:e.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new ct(e.common.issues)},input:e.data})}}removeCatch(){return this._def.innerType}};gr.create=(s,t)=>new gr({innerType:s,typeName:Z.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...he(t)});var Kr=class extends fe{_parse(t){if(this._getType(t)!==K.nan){let e=this._getOrReturnCtx(t);return Q(e,{code:U.invalid_type,expected:K.nan,received:e.parsedType}),ae}return{status:"valid",value:t.data}}};Kr.create=s=>new Kr({typeName:Z.ZodNaN,...he(s)});var iu=Symbol("zod_brand"),Sa=class extends fe{_parse(t){let{ctx:r}=this._processInputParams(t),e=r.data;return this._def.type._parse({data:e,path:r.path,parent:r})}unwrap(){return this._def.type}},xa=class s extends fe{_parse(t){let{status:r,ctx:e}=this._processInputParams(t);if(e.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:e.data,path:e.path,parent:e});return i.status==="aborted"?ae:i.status==="dirty"?(r.dirty(),Hr(i.value)):this._def.out._parseAsync({data:i.value,path:e.path,parent:e})})();{let n=this._def.in._parseSync({data:e.data,path:e.path,parent:e});return n.status==="aborted"?ae:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:e.path,parent:e})}}static create(t,r){return new s({in:t,out:r,typeName:Z.ZodPipeline})}},yr=class extends fe{_parse(t){let r=this._def.innerType._parse(t),e=n=>(ar(n)&&(n.value=Object.freeze(n.value)),n);return ba(r)?r.then(n=>e(n)):e(r)}unwrap(){return this._def.innerType}};yr.create=(s,t)=>new yr({innerType:s,typeName:Z.ZodReadonly,...he(t)});function hn(s,t){let r=typeof s=="function"?s(t):typeof s=="string"?{message:s}:s;return typeof r=="string"?{message:r}:r}function Dn(s,t={},r){return s?Qt.create().superRefine((e,n)=>{let i=s(e);if(i instanceof Promise)return i.then(a=>{if(!a){let o=hn(t,e),c=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:c})}});if(!i){let a=hn(t,e),o=a.fatal??r??!0;n.addIssue({code:"custom",...a,fatal:o})}}):Qt.create()}var ou={object:rt.lazycreate},Z;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(Z||(Z={}));var lu=(s,t={message:`Input not instance of ${s.name}`})=>Dn(r=>r instanceof s,t),Fn=Bt.create,Mn=sr.create,cu=Kr.create,uu=nr.create,Ln=ir.create,du=or.create,fu=Qr.create,hu=lr.create,pu=cr.create,mu=Qt.create,vu=qt.create,gu=wt.create,yu=Gr.create,_u=zt.create,bu=rt.create,Su=rt.strictCreate,xu=ur.create,Eu=La.create,wu=dr.create,Pu=Ct.create,Ru=qa.create,Tu=Jr.create,ku=Wr.create,Cu=za.create,Ou=fr.create,Iu=hr.create,$u=pr.create,Au=mr.create,ju=Gt.create,pn=dt.create,Nu=ut.create,Du=Ot.create,Fu=dt.createWithPreprocess,Mu=xa.create,Lu=()=>Fn().optional(),qu=()=>Mn().optional(),zu=()=>Ln().optional(),Uu={string:s=>Bt.create({...s,coerce:!0}),number:s=>sr.create({...s,coerce:!0}),boolean:s=>ir.create({...s,coerce:!0}),bigint:s=>nr.create({...s,coerce:!0}),date:s=>or.create({...s,coerce:!0})},Zu=ae,qn="2025-06-18",Vu=[qn,"2025-03-26","2024-11-05","2024-10-07"],Ha="2.0",zn=u.union([u.string(),u.number().int()]),Un=u.string(),Hu=u.object({progressToken:u.optional(zn)}).passthrough(),vt=u.object({_meta:u.optional(Hu)}).passthrough(),at=u.object({method:u.string(),params:u.optional(vt)}),Pa=u.object({_meta:u.optional(u.object({}).passthrough())}).passthrough(),It=u.object({method:u.string(),params:u.optional(Pa)}),gt=u.object({_meta:u.optional(u.object({}).passthrough())}).passthrough(),Ba=u.union([u.string(),u.number().int()]),Zn=u.object({jsonrpc:u.literal(Ha),id:Ba}).merge(at).strict(),Bu=s=>Zn.safeParse(s).success,Vn=u.object({jsonrpc:u.literal(Ha)}).merge(It).strict(),Qu=s=>Vn.safeParse(s).success,Hn=u.object({jsonrpc:u.literal(Ha),id:Ba,result:gt}).strict(),mn=s=>Hn.safeParse(s).success,qe;(function(s){s[s.ConnectionClosed=-32e3]="ConnectionClosed",s[s.RequestTimeout=-32001]="RequestTimeout",s[s.ParseError=-32700]="ParseError",s[s.InvalidRequest=-32600]="InvalidRequest",s[s.MethodNotFound=-32601]="MethodNotFound",s[s.InvalidParams=-32602]="InvalidParams",s[s.InternalError=-32603]="InternalError"})(qe||(qe={}));var Bn=u.object({jsonrpc:u.literal(Ha),id:Ba,error:u.object({code:u.number().int(),message:u.string(),data:u.optional(u.unknown())})}).strict(),Gu=s=>Bn.safeParse(s).success,op=u.union([Zn,Vn,Hn,Bn]),Is=gt.strict(),$s=It.extend({method:u.literal("notifications/cancelled"),params:Pa.extend({requestId:Ba,reason:u.string().optional()})}),Ra=u.object({name:u.string(),title:u.optional(u.string())}).passthrough(),Qn=Ra.extend({version:u.string()}),Ju=u.object({experimental:u.optional(u.object({}).passthrough()),sampling:u.optional(u.object({}).passthrough()),elicitation:u.optional(u.object({}).passthrough()),roots:u.optional(u.object({listChanged:u.optional(u.boolean())}).passthrough())}).passthrough(),Gn=at.extend({method:u.literal("initialize"),params:vt.extend({protocolVersion:u.string(),capabilities:Ju,clientInfo:Qn})}),Wu=u.object({experimental:u.optional(u.object({}).passthrough()),logging:u.optional(u.object({}).passthrough()),completions:u.optional(u.object({}).passthrough()),prompts:u.optional(u.object({listChanged:u.optional(u.boolean())}).passthrough()),resources:u.optional(u.object({subscribe:u.optional(u.boolean()),listChanged:u.optional(u.boolean())}).passthrough()),tools:u.optional(u.object({listChanged:u.optional(u.boolean())}).passthrough())}).passthrough(),Ku=gt.extend({protocolVersion:u.string(),capabilities:Wu,serverInfo:Qn,instructions:u.optional(u.string())}),Jn=It.extend({method:u.literal("notifications/initialized")}),As=at.extend({method:u.literal("ping")}),Yu=u.object({progress:u.number(),total:u.optional(u.number()),message:u.optional(u.string())}).passthrough(),js=It.extend({method:u.literal("notifications/progress"),params:Pa.merge(Yu).extend({progressToken:zn})}),Qa=at.extend({params:vt.extend({cursor:u.optional(Un)}).optional()}),Ga=gt.extend({nextCursor:u.optional(Un)}),Wn=u.object({uri:u.string(),mimeType:u.optional(u.string()),_meta:u.optional(u.object({}).passthrough())}).passthrough(),Kn=Wn.extend({text:u.string()}),Ns=u.string().refine(s=>{try{return atob(s),!0}catch{return!1}},{message:"Invalid Base64 string"}),Yn=Wn.extend({blob:Ns}),Xn=Ra.extend({uri:u.string(),description:u.optional(u.string()),mimeType:u.optional(u.string()),_meta:u.optional(u.object({}).passthrough())}),Xu=Ra.extend({uriTemplate:u.string(),description:u.optional(u.string()),mimeType:u.optional(u.string()),_meta:u.optional(u.object({}).passthrough())}),ps=Qa.extend({method:u.literal("resources/list")}),ed=Ga.extend({resources:u.array(Xn)}),ms=Qa.extend({method:u.literal("resources/templates/list")}),td=Ga.extend({resourceTemplates:u.array(Xu)}),vs=at.extend({method:u.literal("resources/read"),params:vt.extend({uri:u.string()})}),rd=gt.extend({contents:u.array(u.union([Kn,Yn]))}),ad=It.extend({method:u.literal("notifications/resources/list_changed")}),sd=at.extend({method:u.literal("resources/subscribe"),params:vt.extend({uri:u.string()})}),nd=at.extend({method:u.literal("resources/unsubscribe"),params:vt.extend({uri:u.string()})}),id=It.extend({method:u.literal("notifications/resources/updated"),params:Pa.extend({uri:u.string()})}),od=u.object({name:u.string(),description:u.optional(u.string()),required:u.optional(u.boolean())}).passthrough(),ld=Ra.extend({description:u.optional(u.string()),arguments:u.optional(u.array(od)),_meta:u.optional(u.object({}).passthrough())}),gs=Qa.extend({method:u.literal("prompts/list")}),cd=Ga.extend({prompts:u.array(ld)}),ys=at.extend({method:u.literal("prompts/get"),params:vt.extend({name:u.string(),arguments:u.optional(u.record(u.string()))})}),Ds=u.object({type:u.literal("text"),text:u.string(),_meta:u.optional(u.object({}).passthrough())}).passthrough(),Fs=u.object({type:u.literal("image"),data:Ns,mimeType:u.string(),_meta:u.optional(u.object({}).passthrough())}).passthrough(),Ms=u.object({type:u.literal("audio"),data:Ns,mimeType:u.string(),_meta:u.optional(u.object({}).passthrough())}).passthrough(),ud=u.object({type:u.literal("resource"),resource:u.union([Kn,Yn]),_meta:u.optional(u.object({}).passthrough())}).passthrough(),dd=Xn.extend({type:u.literal("resource_link")}),ei=u.union([Ds,Fs,Ms,dd,ud]),fd=u.object({role:u.enum(["user","assistant"]),content:ei}).passthrough(),hd=gt.extend({description:u.optional(u.string()),messages:u.array(fd)}),pd=It.extend({method:u.literal("notifications/prompts/list_changed")}),md=u.object({title:u.optional(u.string()),readOnlyHint:u.optional(u.boolean()),destructiveHint:u.optional(u.boolean()),idempotentHint:u.optional(u.boolean()),openWorldHint:u.optional(u.boolean())}).passthrough(),vd=Ra.extend({description:u.optional(u.string()),inputSchema:u.object({type:u.literal("object"),properties:u.optional(u.object({}).passthrough()),required:u.optional(u.array(u.string()))}).passthrough(),outputSchema:u.optional(u.object({type:u.literal("object"),properties:u.optional(u.object({}).passthrough()),required:u.optional(u.array(u.string()))}).passthrough()),annotations:u.optional(md),_meta:u.optional(u.object({}).passthrough())}),_s=Qa.extend({method:u.literal("tools/list")}),gd=Ga.extend({tools:u.array(vd)}),ti=gt.extend({content:u.array(ei).default([]),structuredContent:u.object({}).passthrough().optional(),isError:u.optional(u.boolean())}),lp=ti.or(gt.extend({toolResult:u.unknown()})),bs=at.extend({method:u.literal("tools/call"),params:vt.extend({name:u.string(),arguments:u.optional(u.record(u.unknown()))})}),yd=It.extend({method:u.literal("notifications/tools/list_changed")}),ri=u.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),_d=at.extend({method:u.literal("logging/setLevel"),params:vt.extend({level:ri})}),bd=It.extend({method:u.literal("notifications/message"),params:Pa.extend({level:ri,logger:u.optional(u.string()),data:u.unknown()})}),Sd=u.object({name:u.string().optional()}).passthrough(),xd=u.object({hints:u.optional(u.array(Sd)),costPriority:u.optional(u.number().min(0).max(1)),speedPriority:u.optional(u.number().min(0).max(1)),intelligencePriority:u.optional(u.number().min(0).max(1))}).passthrough(),Ed=u.object({role:u.enum(["user","assistant"]),content:u.union([Ds,Fs,Ms])}).passthrough(),wd=at.extend({method:u.literal("sampling/createMessage"),params:vt.extend({messages:u.array(Ed),systemPrompt:u.optional(u.string()),includeContext:u.optional(u.enum(["none","thisServer","allServers"])),temperature:u.optional(u.number()),maxTokens:u.number().int(),stopSequences:u.optional(u.array(u.string())),metadata:u.optional(u.object({}).passthrough()),modelPreferences:u.optional(xd)})}),ai=gt.extend({model:u.string(),stopReason:u.optional(u.enum(["endTurn","stopSequence","maxTokens"]).or(u.string())),role:u.enum(["user","assistant"]),content:u.discriminatedUnion("type",[Ds,Fs,Ms])}),Pd=u.object({type:u.literal("boolean"),title:u.optional(u.string()),description:u.optional(u.string()),default:u.optional(u.boolean())}).passthrough(),Rd=u.object({type:u.literal("string"),title:u.optional(u.string()),description:u.optional(u.string()),minLength:u.optional(u.number()),maxLength:u.optional(u.number()),format:u.optional(u.enum(["email","uri","date","date-time"]))}).passthrough(),Td=u.object({type:u.enum(["number","integer"]),title:u.optional(u.string()),description:u.optional(u.string()),minimum:u.optional(u.number()),maximum:u.optional(u.number())}).passthrough(),kd=u.object({type:u.literal("string"),title:u.optional(u.string()),description:u.optional(u.string()),enum:u.array(u.string()),enumNames:u.optional(u.array(u.string()))}).passthrough(),Cd=u.union([Pd,Rd,Td,kd]),Od=at.extend({method:u.literal("elicitation/create"),params:vt.extend({message:u.string(),requestedSchema:u.object({type:u.literal("object"),properties:u.record(u.string(),Cd),required:u.optional(u.array(u.string()))}).passthrough()})}),si=gt.extend({action:u.enum(["accept","decline","cancel"]),content:u.optional(u.record(u.string(),u.unknown()))}),Id=u.object({type:u.literal("ref/resource"),uri:u.string()}).passthrough(),$d=u.object({type:u.literal("ref/prompt"),name:u.string()}).passthrough(),Ss=at.extend({method:u.literal("completion/complete"),params:vt.extend({ref:u.union([$d,Id]),argument:u.object({name:u.string(),value:u.string()}).passthrough(),context:u.optional(u.object({arguments:u.optional(u.record(u.string(),u.string()))}))})}),Ad=gt.extend({completion:u.object({values:u.array(u.string()).max(100),total:u.optional(u.number().int()),hasMore:u.optional(u.boolean())}).passthrough()}),jd=u.object({uri:u.string().startsWith("file://"),name:u.optional(u.string()),_meta:u.optional(u.object({}).passthrough())}).passthrough(),Nd=at.extend({method:u.literal("roots/list")}),ni=gt.extend({roots:u.array(jd)}),Dd=It.extend({method:u.literal("notifications/roots/list_changed")}),cp=u.union([As,Gn,Ss,_d,ys,gs,ps,ms,vs,sd,nd,bs,_s]),up=u.union([$s,js,Jn,Dd]),dp=u.union([Is,ai,si,ni]),fp=u.union([As,wd,Od,Nd]),hp=u.union([$s,js,bd,id,ad,yd,pd]),pp=u.union([Is,Ku,Ad,hd,cd,ed,td,rd,ti,gd]),ze=class extends Error{constructor(t,r,e){super(`MCP error ${t}: ${r}`),this.code=t,this.data=e,this.name="McpError"}},Fd=6e4,xs=class{constructor(t){this._options=t,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.setNotificationHandler($s,r=>{let e=this._requestHandlerAbortControllers.get(r.params.requestId);e?.abort(r.params.reason)}),this.setNotificationHandler(js,r=>{this._onprogress(r)}),this.setRequestHandler(As,r=>({}))}_setupTimeout(t,r,e,n,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:e,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let e=Date.now()-r.startTime;if(r.maxTotalTimeout&&e>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),new ze(qe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:e});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){var r,e,n;this._transport=t;let i=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{i?.(),this._onclose()};let a=(e=this.transport)===null||e===void 0?void 0:e.onerror;this._transport.onerror=c=>{a?.(c),this._onerror(c)};let o=(n=this._transport)===null||n===void 0?void 0:n.onmessage;this._transport.onmessage=(c,l)=>{o?.(c,l),mn(c)||Gu(c)?this._onresponse(c):Bu(c)?this._onrequest(c,l):Qu(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var t;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(t=this.onclose)===null||t===void 0||t.call(this);let e=new ze(qe.ConnectionClosed,"Connection closed");for(let n of r.values())n(e)}_onerror(t){var r;(r=this.onerror)===null||r===void 0||r.call(this,t)}_onnotification(t){var r;let e=(r=this._notificationHandlers.get(t.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;e!==void 0&&Promise.resolve().then(()=>e(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){var e,n;let i=(e=this._requestHandlers.get(t.method))!==null&&e!==void 0?e:this.fallbackRequestHandler,a=this._transport;if(i===void 0){a?.send({jsonrpc:"2.0",id:t.id,error:{code:qe.MethodNotFound,message:"Method not found"}}).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(t.id,o);let c={signal:o.signal,sessionId:a?.sessionId,_meta:(n=t.params)===null||n===void 0?void 0:n._meta,sendNotification:l=>this.notification(l,{relatedRequestId:t.id}),sendRequest:(l,f,y)=>this.request(l,f,{...y,relatedRequestId:t.id}),authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>i(t,c)).then(l=>{if(!o.signal.aborted)return a?.send({result:l,jsonrpc:"2.0",id:t.id})},l=>{var f;if(!o.signal.aborted)return a?.send({jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:qe.InternalError,message:(f=l.message)!==null&&f!==void 0?f:"Internal error"}})}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...e}=t.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let a=this._responseHandlers.get(n),o=this._timeoutInfo.get(n);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){a(c);return}i(e)}_onresponse(t){let r=Number(t.id),e=this._responseHandlers.get(r);if(e===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),mn(t))e(t);else{let n=new ze(t.error.code,t.error.message,t.error.data);e(n)}}get transport(){return this._transport}async close(){var t;await((t=this._transport)===null||t===void 0?void 0:t.close())}request(t,r,e){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}=e??{};return new Promise((o,c)=>{var l,f,y,R,m,b;if(!this._transport){c(new Error("Not connected"));return}((l=this._options)===null||l===void 0?void 0:l.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(t.method),(f=e?.signal)===null||f===void 0||f.throwIfAborted();let d=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:d};e?.onprogress&&(this._progressHandlers.set(d,e.onprogress),p.params={...t.params,_meta:{...((y=t.params)===null||y===void 0?void 0:y._meta)||{},progressToken:d}});let _=$=>{var O;this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),(O=this._transport)===null||O===void 0||O.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String($)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(E=>this._onerror(new Error(`Failed to send cancellation: ${E}`))),c($)};this._responseHandlers.set(d,$=>{var O;if(!(!((O=e?.signal)===null||O===void 0)&&O.aborted)){if($ instanceof Error)return c($);try{let E=r.parse($.result);o(E)}catch(E){c(E)}}}),(R=e?.signal)===null||R===void 0||R.addEventListener("abort",()=>{var $;_(($=e?.signal)===null||$===void 0?void 0:$.reason)});let g=(m=e?.timeout)!==null&&m!==void 0?m:Fd,x=()=>_(new ze(qe.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(d,g,e?.maxTotalTimeout,x,(b=e?.resetTimeoutOnProgress)!==null&&b!==void 0?b:!1),this._transport.send(p,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch($=>{this._cleanupTimeout(d),c($)})})}async notification(t,r){var e,n;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(t.method),((n=(e=this._options)===null||e===void 0?void 0:e.debouncedNotificationMethods)!==null&&n!==void 0?n:[]).includes(t.method)&&!t.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let l={...t,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(l,r).catch(f=>this._onerror(f))});return}let o={...t,jsonrpc:"2.0"};await this._transport.send(o,r)}setRequestHandler(t,r){let e=t.shape.method.value;this.assertRequestHandlerCapability(e),this._requestHandlers.set(e,(n,i)=>Promise.resolve(r(t.parse(n),i)))}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){this._notificationHandlers.set(t.shape.method.value,e=>Promise.resolve(r(t.parse(e))))}removeNotificationHandler(t){this._notificationHandlers.delete(t)}};function Md(s,t){return Object.entries(t).reduce((r,[e,n])=>(n&&typeof n=="object"?r[e]=r[e]?{...r[e],...n}:n:r[e]=n,r),{...s})}var Ld=Yi(jo(),1),Es=class extends xs{constructor(t,r){var e;super(r),this._serverInfo=t,this._capabilities=(e=r?.capabilities)!==null&&e!==void 0?e:{},this._instructions=r?.instructions,this.setRequestHandler(Gn,n=>this._oninitialize(n)),this.setNotificationHandler(Jn,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)})}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Md(this._capabilities,t)}assertCapabilityForMethod(t){var r,e,n;switch(t){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!(!((e=this._clientCapabilities)===null||e===void 0)&&e.elicitation))throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.roots))throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);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 ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);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 ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"ping":case"initialize":break}}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:Vu.includes(r)?r:qn,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"},Is)}async createMessage(t,r){return this.request({method:"sampling/createMessage",params:t},ai,r)}async elicitInput(t,r){let e=await this.request({method:"elicitation/create",params:t},si,r);if(e.action==="accept"&&e.content)try{let n=new Ld.default,i=n.compile(t.requestedSchema);if(!i(e.content))throw new ze(qe.InvalidParams,`Elicitation response content does not match requested schema: ${n.errorsText(i.errors)}`)}catch(n){throw n instanceof ze?n:new ze(qe.InternalError,`Error validating elicitation response: ${n}`)}return e}async listRoots(t,r){return this.request({method:"roots/list",params:t},ni,r)}async sendLoggingMessage(t){return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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"})}},qd=Symbol("Let zodToJsonSchema decide on which parser to use"),vn={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"},zd=s=>typeof s=="string"?{...vn,name:s}:{...vn,...s},Ud=s=>{let t=zd(s),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function ii(s,t,r,e){e?.errorMessages&&r&&(s.errorMessage={...s.errorMessage,[t]:r})}function Ce(s,t,r,e,n){s[t]=r,ii(s,t,e,n)}function Zd(){return{}}function Vd(s,t){let r={type:"array"};return s.type?._def&&s.type?._def?.typeName!==Z.ZodAny&&(r.items=Te(s.type._def,{...t,currentPath:[...t.currentPath,"items"]})),s.minLength&&Ce(r,"minItems",s.minLength.value,s.minLength.message,t),s.maxLength&&Ce(r,"maxItems",s.maxLength.value,s.maxLength.message,t),s.exactLength&&(Ce(r,"minItems",s.exactLength.value,s.exactLength.message,t),Ce(r,"maxItems",s.exactLength.value,s.exactLength.message,t)),r}function Hd(s,t){let r={type:"integer",format:"int64"};if(!s.checks)return r;for(let e of s.checks)switch(e.kind){case"min":t.target==="jsonSchema7"?e.inclusive?Ce(r,"minimum",e.value,e.message,t):Ce(r,"exclusiveMinimum",e.value,e.message,t):(e.inclusive||(r.exclusiveMinimum=!0),Ce(r,"minimum",e.value,e.message,t));break;case"max":t.target==="jsonSchema7"?e.inclusive?Ce(r,"maximum",e.value,e.message,t):Ce(r,"exclusiveMaximum",e.value,e.message,t):(e.inclusive||(r.exclusiveMaximum=!0),Ce(r,"maximum",e.value,e.message,t));break;case"multipleOf":Ce(r,"multipleOf",e.value,e.message,t);break}return r}function Bd(){return{type:"boolean"}}function oi(s,t){return Te(s.type._def,t)}var Qd=(s,t)=>Te(s.innerType._def,t);function li(s,t,r){let e=r??t.dateStrategy;if(Array.isArray(e))return{anyOf:e.map((n,i)=>li(s,t,n))};switch(e){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Gd(s,t)}}var Gd=(s,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let e of s.checks)switch(e.kind){case"min":Ce(r,"minimum",e.value,e.message,t);break;case"max":Ce(r,"maximum",e.value,e.message,t);break}return r};function Jd(s,t){return{...Te(s.innerType._def,t),default:s.defaultValue()}}function Wd(s,t){return t.effectStrategy==="input"?Te(s.schema._def,t):{}}function Kd(s){return{type:"string",enum:Array.from(s.values)}}var Yd=s=>"type"in s&&s.type==="string"?!1:"allOf"in s;function Xd(s,t){let r=[Te(s.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Te(s.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(i=>!!i),e=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach(i=>{if(Yd(i))n.push(...i.allOf),i.unevaluatedProperties===void 0&&(e=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:o,...c}=i;a=c}else e=void 0;n.push(a)}}),n.length?{allOf:n,...e}:void 0}function ef(s,t){let r=typeof s.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(s.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[s.value]}:{type:r==="bigint"?"integer":r,const:s.value}}var os=void 0,xt={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:()=>(os===void 0&&(os=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),os),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ci(s,t){let r={type:"string"};if(s.checks)for(let e of s.checks)switch(e.kind){case"min":Ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,e.value):e.value,e.message,t);break;case"max":Ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,e.value):e.value,e.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Et(r,"email",e.message,t);break;case"format:idn-email":Et(r,"idn-email",e.message,t);break;case"pattern:zod":et(r,xt.email,e.message,t);break}break;case"url":Et(r,"uri",e.message,t);break;case"uuid":Et(r,"uuid",e.message,t);break;case"regex":et(r,e.regex,e.message,t);break;case"cuid":et(r,xt.cuid,e.message,t);break;case"cuid2":et(r,xt.cuid2,e.message,t);break;case"startsWith":et(r,RegExp(`^${ls(e.value,t)}`),e.message,t);break;case"endsWith":et(r,RegExp(`${ls(e.value,t)}$`),e.message,t);break;case"datetime":Et(r,"date-time",e.message,t);break;case"date":Et(r,"date",e.message,t);break;case"time":Et(r,"time",e.message,t);break;case"duration":Et(r,"duration",e.message,t);break;case"length":Ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,e.value):e.value,e.message,t),Ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,e.value):e.value,e.message,t);break;case"includes":{et(r,RegExp(ls(e.value,t)),e.message,t);break}case"ip":{e.version!=="v6"&&Et(r,"ipv4",e.message,t),e.version!=="v4"&&Et(r,"ipv6",e.message,t);break}case"base64url":et(r,xt.base64url,e.message,t);break;case"jwt":et(r,xt.jwt,e.message,t);break;case"cidr":{e.version!=="v6"&&et(r,xt.ipv4Cidr,e.message,t),e.version!=="v4"&&et(r,xt.ipv6Cidr,e.message,t);break}case"emoji":et(r,xt.emoji(),e.message,t);break;case"ulid":{et(r,xt.ulid,e.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Et(r,"binary",e.message,t);break}case"contentEncoding:base64":{Ce(r,"contentEncoding","base64",e.message,t);break}case"pattern:zod":{et(r,xt.base64,e.message,t);break}}break}case"nanoid":et(r,xt.nanoid,e.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ls(s,t){return t.patternStrategy==="escape"?rf(s):s}var tf=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function rf(s){let t="";for(let r=0;rn.format)?(s.anyOf||(s.anyOf=[]),s.format&&(s.anyOf.push({format:s.format,...s.errorMessage&&e.errorMessages&&{errorMessage:{format:s.errorMessage.format}}}),delete s.format,s.errorMessage&&(delete s.errorMessage.format,Object.keys(s.errorMessage).length===0&&delete s.errorMessage)),s.anyOf.push({format:t,...r&&e.errorMessages&&{errorMessage:{format:r}}})):Ce(s,"format",t,r,e)}function et(s,t,r,e){s.pattern||s.allOf?.some(n=>n.pattern)?(s.allOf||(s.allOf=[]),s.pattern&&(s.allOf.push({pattern:s.pattern,...s.errorMessage&&e.errorMessages&&{errorMessage:{pattern:s.errorMessage.pattern}}}),delete s.pattern,s.errorMessage&&(delete s.errorMessage.pattern,Object.keys(s.errorMessage).length===0&&delete s.errorMessage)),s.allOf.push({pattern:gn(t,e),...r&&e.errorMessages&&{errorMessage:{pattern:r}}})):Ce(s,"pattern",gn(t,e),r,e)}function gn(s,t){if(!t.applyRegexFlags||!s.flags)return s.source;let r={i:s.flags.includes("i"),m:s.flags.includes("m"),s:s.flags.includes("s")},e=r.i?s.source.toLowerCase():s.source,n="",i=!1,a=!1,o=!1;for(let c=0;c({...e,[n]:Te(s.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Te(s.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(s.keyType?._def.typeName===Z.ZodString&&s.keyType._def.checks?.length){let{type:e,...n}=ci(s.keyType._def,t);return{...r,propertyNames:n}}else{if(s.keyType?._def.typeName===Z.ZodEnum)return{...r,propertyNames:{enum:s.keyType._def.values}};if(s.keyType?._def.typeName===Z.ZodBranded&&s.keyType._def.type._def.typeName===Z.ZodString&&s.keyType._def.type._def.checks?.length){let{type:e,...n}=oi(s.keyType._def,t);return{...r,propertyNames:n}}}return r}function af(s,t){if(t.mapStrategy==="record")return ui(s,t);let r=Te(s.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},e=Te(s.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,e],minItems:2,maxItems:2}}}function sf(s){let t=s.values,e=Object.keys(s.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(e.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:e}}function nf(){return{not:{}}}function of(s){return s.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ua={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function lf(s,t){if(t.target==="openApi3")return yn(s,t);let r=s.options instanceof Map?Array.from(s.options.values()):s.options;if(r.every(e=>e._def.typeName in Ua&&(!e._def.checks||!e._def.checks.length))){let e=r.reduce((n,i)=>{let a=Ua[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:e.length>1?e:e[0]}}else if(r.every(e=>e._def.typeName==="ZodLiteral"&&!e.description)){let e=r.reduce((n,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(e.length===r.length){let n=e.filter((i,a,o)=>o.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(e=>e._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((e,n)=>[...e,...n._def.values.filter(i=>!e.includes(i))],[])};return yn(s,t)}var yn=(s,t)=>{let r=(s.options instanceof Map?Array.from(s.options.values()):s.options).map((e,n)=>Te(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e=="object"&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function cf(s,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(s.innerType._def.typeName)&&(!s.innerType._def.checks||!s.innerType._def.checks.length))return t.target==="openApi3"?{type:Ua[s.innerType._def.typeName],nullable:!0}:{type:[Ua[s.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let e=Te(s.innerType._def,{...t,currentPath:[...t.currentPath]});return e&&"$ref"in e?{allOf:[e],nullable:!0}:e&&{...e,nullable:!0}}let r=Te(s.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function uf(s,t){let r={type:"number"};if(!s.checks)return r;for(let e of s.checks)switch(e.kind){case"int":r.type="integer",ii(r,"type",e.message,t);break;case"min":t.target==="jsonSchema7"?e.inclusive?Ce(r,"minimum",e.value,e.message,t):Ce(r,"exclusiveMinimum",e.value,e.message,t):(e.inclusive||(r.exclusiveMinimum=!0),Ce(r,"minimum",e.value,e.message,t));break;case"max":t.target==="jsonSchema7"?e.inclusive?Ce(r,"maximum",e.value,e.message,t):Ce(r,"exclusiveMaximum",e.value,e.message,t):(e.inclusive||(r.exclusiveMaximum=!0),Ce(r,"maximum",e.value,e.message,t));break;case"multipleOf":Ce(r,"multipleOf",e.value,e.message,t);break}return r}function df(s,t){let r=t.target==="openAi",e={type:"object",properties:{}},n=[],i=s.shape();for(let o in i){let c=i[o];if(c===void 0||c._def===void 0)continue;let l=hf(c);l&&r&&(c instanceof ut&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let f=Te(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});f!==void 0&&(e.properties[o]=f,l||n.push(o))}n.length&&(e.required=n);let a=ff(s,t);return a!==void 0&&(e.additionalProperties=a),e}function ff(s,t){if(s.catchall._def.typeName!=="ZodNever")return Te(s.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(s.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function hf(s){try{return s.isOptional()}catch{return!0}}var pf=(s,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Te(s.innerType._def,t);let r=Te(s.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},mf=(s,t)=>{if(t.pipeStrategy==="input")return Te(s.in._def,t);if(t.pipeStrategy==="output")return Te(s.out._def,t);let r=Te(s.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),e=Te(s.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,e].filter(n=>n!==void 0)}};function vf(s,t){return Te(s.type._def,t)}function gf(s,t){let e={type:"array",uniqueItems:!0,items:Te(s.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return s.minSize&&Ce(e,"minItems",s.minSize.value,s.minSize.message,t),s.maxSize&&Ce(e,"maxItems",s.maxSize.value,s.maxSize.message,t),e}function yf(s,t){return s.rest?{type:"array",minItems:s.items.length,items:s.items.map((r,e)=>Te(r._def,{...t,currentPath:[...t.currentPath,"items",`${e}`]})).reduce((r,e)=>e===void 0?r:[...r,e],[]),additionalItems:Te(s.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:s.items.length,maxItems:s.items.length,items:s.items.map((r,e)=>Te(r._def,{...t,currentPath:[...t.currentPath,"items",`${e}`]})).reduce((r,e)=>e===void 0?r:[...r,e],[])}}function _f(){return{not:{}}}function bf(){return{}}var Sf=(s,t)=>Te(s.innerType._def,t),xf=(s,t,r)=>{switch(t){case Z.ZodString:return ci(s,r);case Z.ZodNumber:return uf(s,r);case Z.ZodObject:return df(s,r);case Z.ZodBigInt:return Hd(s,r);case Z.ZodBoolean:return Bd();case Z.ZodDate:return li(s,r);case Z.ZodUndefined:return _f();case Z.ZodNull:return of(r);case Z.ZodArray:return Vd(s,r);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return lf(s,r);case Z.ZodIntersection:return Xd(s,r);case Z.ZodTuple:return yf(s,r);case Z.ZodRecord:return ui(s,r);case Z.ZodLiteral:return ef(s,r);case Z.ZodEnum:return Kd(s);case Z.ZodNativeEnum:return sf(s);case Z.ZodNullable:return cf(s,r);case Z.ZodOptional:return pf(s,r);case Z.ZodMap:return af(s,r);case Z.ZodSet:return gf(s,r);case Z.ZodLazy:return()=>s.getter()._def;case Z.ZodPromise:return vf(s,r);case Z.ZodNaN:case Z.ZodNever:return nf();case Z.ZodEffects:return Wd(s,r);case Z.ZodAny:return Zd();case Z.ZodUnknown:return bf();case Z.ZodDefault:return Jd(s,r);case Z.ZodBranded:return oi(s,r);case Z.ZodReadonly:return Sf(s,r);case Z.ZodCatch:return Qd(s,r);case Z.ZodPipeline:return mf(s,r);case Z.ZodFunction:case Z.ZodVoid:case Z.ZodSymbol:return;default:return(e=>{})(t)}};function Te(s,t,r=!1){let e=t.seen.get(s);if(t.override){let o=t.override?.(s,t,e,r);if(o!==qd)return o}if(e&&!r){let o=Ef(e,t);if(o!==void 0)return o}let n={def:s,path:t.currentPath,jsonSchema:void 0};t.seen.set(s,n);let i=xf(s,s.typeName,t),a=typeof i=="function"?Te(i(),t):i;if(a&&Pf(s,t,a),t.postProcess){let o=t.postProcess(a,s,t);return n.jsonSchema=a,o}return n.jsonSchema=a,a}var Ef=(s,t)=>{switch(t.$refStrategy){case"root":return{$ref:s.path.join("/")};case"relative":return{$ref:wf(t.currentPath,s.path)};case"none":case"seen":return s.path.lengtht.currentPath[e]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):t.$refStrategy==="seen"?{}:void 0}},wf=(s,t)=>{let r=0;for(;r(s.description&&(r.description=s.description,t.markdownDescription&&(r.markdownDescription=s.description)),r),_n=(s,t)=>{let r=Ud(t),e=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[l,f])=>({...c,[l]:Te(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??{}}),{}):void 0,n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=Te(s._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a);let o=n===void 0?e?{...i,[r.definitionPath]:e}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...e,[n]:i}};return r.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o},ws;(function(s){s.Completable="McpCompletable"})(ws||(ws={}));var Ea=class extends fe{_parse(t){let{ctx:r}=this._processInputParams(t),e=r.data;return this._def.type._parse({data:e,path:r.path,parent:r})}unwrap(){return this._def.type}};Ea.create=(s,t)=>new Ea({type:s,typeName:ws.Completable,complete:t.complete,...Rf(t)});function Rf(s){if(!s)return{};let{errorMap:t,invalid_type_error:r,required_error:e,description:n}=s;if(t&&(r||e))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:n}:{errorMap:(a,o)=>{var c,l;let{message:f}=s;return a.code==="invalid_enum_value"?{message:f??o.defaultError}:typeof o.data>"u"?{message:(c=f??e)!==null&&c!==void 0?c:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(l=f??r)!==null&&l!==void 0?l:o.defaultError}},description:n}}var Ps=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Es(t,r)}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(_s.shape.method.value),this.server.assertCanSetRequestHandler(bs.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(_s,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let e={name:t,title:r.title,description:r.description,inputSchema:r.inputSchema?_n(r.inputSchema,{strictUnions:!0}):Tf,annotations:r.annotations};return r.outputSchema&&(e.outputSchema=_n(r.outputSchema,{strictUnions:!0})),e})})),this.server.setRequestHandler(bs,async(t,r)=>{let e=this._registeredTools[t.params.name];if(!e)throw new ze(qe.InvalidParams,`Tool ${t.params.name} not found`);if(!e.enabled)throw new ze(qe.InvalidParams,`Tool ${t.params.name} disabled`);let n;if(e.inputSchema){let i=await e.inputSchema.safeParseAsync(t.params.arguments);if(!i.success)throw new ze(qe.InvalidParams,`Invalid arguments for tool ${t.params.name}: ${i.error.message}`);let a=i.data,o=e.callback;try{n=await Promise.resolve(o(a,r))}catch(c){n={content:[{type:"text",text:c instanceof Error?c.message:String(c)}],isError:!0}}}else{let i=e.callback;try{n=await Promise.resolve(i(r))}catch(a){n={content:[{type:"text",text:a instanceof Error?a.message:String(a)}],isError:!0}}}if(e.outputSchema&&!n.isError){if(!n.structuredContent)throw new ze(qe.InvalidParams,`Tool ${t.params.name} has an output schema but no structured content was provided`);let i=await e.outputSchema.safeParseAsync(n.structuredContent);if(!i.success)throw new ze(qe.InvalidParams,`Invalid structured content for tool ${t.params.name}: ${i.error.message}`)}return n}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Ss.shape.method.value),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ss,async t=>{switch(t.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return this.handleResourceCompletion(t,t.params.ref);default:throw new ze(qe.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let e=this._registeredPrompts[r.name];if(!e)throw new ze(qe.InvalidParams,`Prompt ${r.name} not found`);if(!e.enabled)throw new ze(qe.InvalidParams,`Prompt ${r.name} disabled`);if(!e.argsSchema)return Na;let n=e.argsSchema.shape[t.params.argument.name];if(!(n instanceof Ea))return Na;let a=await n._def.complete(t.params.argument.value,t.params.context);return Sn(a)}async handleResourceCompletion(t,r){let e=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!e){if(this._registeredResources[r.uri])return Na;throw new ze(qe.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let n=e.resourceTemplate.completeCallback(t.params.argument.name);if(!n)return Na;let i=await n(t.params.argument.value,t.params.context);return Sn(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ps.shape.method.value),this.server.assertCanSetRequestHandler(ms.shape.method.value),this.server.assertCanSetRequestHandler(vs.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ps,async(t,r)=>{let e=Object.entries(this._registeredResources).filter(([i,a])=>a.enabled).map(([i,a])=>({uri:i,name:a.name,...a.metadata})),n=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let a=await i.resourceTemplate.listCallback(r);for(let o of a.resources)n.push({...i.metadata,...o})}return{resources:[...e,...n]}}),this.server.setRequestHandler(ms,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,e])=>({name:r,uriTemplate:e.resourceTemplate.uriTemplate.toString(),...e.metadata}))})),this.server.setRequestHandler(vs,async(t,r)=>{let e=new URL(t.params.uri),n=this._registeredResources[e.toString()];if(n){if(!n.enabled)throw new ze(qe.InvalidParams,`Resource ${e} disabled`);return n.readCallback(e,r)}for(let i of Object.values(this._registeredResourceTemplates)){let a=i.resourceTemplate.uriTemplate.match(e.toString());if(a)return i.readCallback(e,a,r)}throw new ze(qe.InvalidParams,`Resource ${e} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(gs.shape.method.value),this.server.assertCanSetRequestHandler(ys.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(gs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?Cf(r.argsSchema):void 0}))})),this.server.setRequestHandler(ys,async(t,r)=>{let e=this._registeredPrompts[t.params.name];if(!e)throw new ze(qe.InvalidParams,`Prompt ${t.params.name} not found`);if(!e.enabled)throw new ze(qe.InvalidParams,`Prompt ${t.params.name} disabled`);if(e.argsSchema){let n=await e.argsSchema.safeParseAsync(t.params.arguments);if(!n.success)throw new ze(qe.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${n.error.message}`);let i=n.data,a=e.callback;return await Promise.resolve(a(i,r))}else{let n=e.callback;return await Promise.resolve(n(r))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(t,r,...e){let n;typeof e[0]=="object"&&(n=e.shift());let i=e[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let a=this._createRegisteredResource(t,void 0,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let a=this._createRegisteredResourceTemplate(t,void 0,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(t,r,e,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,e.title,r,e,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,e.title,r,e,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,e,n,i){let a={name:t,title:r,metadata:n,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:o=>{typeof o.uri<"u"&&o.uri!==e&&(delete this._registeredResources[e],o.uri&&(this._registeredResources[o.uri]=a)),typeof o.name<"u"&&(a.name=o.name),typeof o.title<"u"&&(a.title=o.title),typeof o.metadata<"u"&&(a.metadata=o.metadata),typeof o.callback<"u"&&(a.readCallback=o.callback),typeof o.enabled<"u"&&(a.enabled=o.enabled),this.sendResourceListChanged()}};return this._registeredResources[e]=a,a}_createRegisteredResourceTemplate(t,r,e,n,i){let a={resourceTemplate:e,title:r,metadata:n,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:o=>{typeof o.name<"u"&&o.name!==t&&(delete this._registeredResourceTemplates[t],o.name&&(this._registeredResourceTemplates[o.name]=a)),typeof o.title<"u"&&(a.title=o.title),typeof o.template<"u"&&(a.resourceTemplate=o.template),typeof o.metadata<"u"&&(a.metadata=o.metadata),typeof o.callback<"u"&&(a.readCallback=o.callback),typeof o.enabled<"u"&&(a.enabled=o.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[t]=a,a}_createRegisteredPrompt(t,r,e,n,i){let a={title:r,description:e,argsSchema:n===void 0?void 0:u.object(n),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:o=>{typeof o.name<"u"&&o.name!==t&&(delete this._registeredPrompts[t],o.name&&(this._registeredPrompts[o.name]=a)),typeof o.title<"u"&&(a.title=o.title),typeof o.description<"u"&&(a.description=o.description),typeof o.argsSchema<"u"&&(a.argsSchema=u.object(o.argsSchema)),typeof o.callback<"u"&&(a.callback=o.callback),typeof o.enabled<"u"&&(a.enabled=o.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=a,a}_createRegisteredTool(t,r,e,n,i,a,o){let c={title:r,description:e,inputSchema:n===void 0?void 0:u.object(n),outputSchema:i===void 0?void 0:u.object(i),annotations:a,callback:o,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==t&&(delete this._registeredTools[t],l.name&&(this._registeredTools[l.name]=c)),typeof l.title<"u"&&(c.title=l.title),typeof l.description<"u"&&(c.description=l.description),typeof l.paramsSchema<"u"&&(c.inputSchema=u.object(l.paramsSchema)),typeof l.callback<"u"&&(c.callback=l.callback),typeof l.annotations<"u"&&(c.annotations=l.annotations),typeof l.enabled<"u"&&(c.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let e,n,i,a;if(typeof r[0]=="string"&&(e=r.shift()),r.length>1){let c=r[0];bn(c)?(n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!bn(r[0])&&(a=r.shift())):typeof c=="object"&&c!==null&&(a=r.shift())}let o=r[0];return this._createRegisteredTool(t,void 0,e,n,i,a,o)}registerTool(t,r,e){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:n,description:i,inputSchema:a,outputSchema:o,annotations:c}=r;return this._createRegisteredTool(t,n,i,a,o,c,e)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let e;typeof r[0]=="string"&&(e=r.shift());let n;r.length>1&&(n=r.shift());let i=r[0],a=this._createRegisteredPrompt(t,void 0,e,n,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(t,r,e){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:n,description:i,argsSchema:a}=r,o=this._createRegisteredPrompt(t,n,i,a,e);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Tf={type:"object",properties:{}};function bn(s){return typeof s!="object"||s===null?!1:Object.keys(s).length===0||Object.values(s).some(kf)}function kf(s){return s!==null&&typeof s=="object"&&"parse"in s&&typeof s.parse=="function"&&"safeParse"in s&&typeof s.safeParse=="function"}function Cf(s){return Object.entries(s.shape).map(([t,r])=>({name:t,description:r.description,required:!r.isOptional()}))}function Sn(s){return{completion:{values:s.slice(0,100),total:s.length,hasMore:s.length>100}}}var Na={completion:{values:[],hasMore:!1}};function _r(s,t,r,e){return{name:s,description:t,inputSchema:r,handler:e}}function di(s){let t=new Ps({name:s.name,version:s.version??"1.0.0"},{capabilities:{tools:s.tools?{}:void 0}});return s.tools&&s.tools.forEach(r=>{t.tool(r.name,r.description,r.inputSchema,r.handler)}),{type:"sdk",name:s.name,instance:t}}var G={};Qi(G,{BRAND:()=>th,DIRTY:()=>br,EMPTY_PATH:()=>Af,INVALID:()=>re,NEVER:()=>Lh,OK:()=>Ye,ParseStatus:()=>Je,Schema:()=>ge,ZodAny:()=>Kt,ZodArray:()=>Ht,ZodBigInt:()=>xr,ZodBoolean:()=>Er,ZodBranded:()=>ka,ZodCatch:()=>jr,ZodDate:()=>wr,ZodDefault:()=>Ar,ZodDiscriminatedUnion:()=>Ka,ZodEffects:()=>bt,ZodEnum:()=>Ir,ZodError:()=>st,ZodFirstPartyTypeKind:()=>ne,ZodFunction:()=>Xa,ZodIntersection:()=>kr,ZodIssueCode:()=>q,ZodLazy:()=>Cr,ZodLiteral:()=>Or,ZodMap:()=>oa,ZodNaN:()=>ca,ZodNativeEnum:()=>$r,ZodNever:()=>Pt,ZodNull:()=>Rr,ZodNullable:()=>jt,ZodNumber:()=>Sr,ZodObject:()=>nt,ZodOptional:()=>yt,ZodParsedType:()=>J,ZodPipeline:()=>Ca,ZodPromise:()=>Yt,ZodReadonly:()=>Nr,ZodRecord:()=>Ya,ZodSchema:()=>ge,ZodSet:()=>la,ZodString:()=>Wt,ZodSymbol:()=>na,ZodTransformer:()=>bt,ZodTuple:()=>At,ZodType:()=>ge,ZodUndefined:()=>Pr,ZodUnion:()=>Tr,ZodUnknown:()=>Vt,ZodVoid:()=>ia,addIssueToContext:()=>B,any:()=>uh,array:()=>ph,bigint:()=>nh,boolean:()=>xi,coerce:()=>Mh,custom:()=>_i,date:()=>ih,datetimeRegex:()=>gi,defaultErrorMap:()=>Ut,discriminatedUnion:()=>yh,effect:()=>Oh,enum:()=>Th,function:()=>wh,getErrorMap:()=>ra,getParsedType:()=>$t,instanceof:()=>ah,intersection:()=>_h,isAborted:()=>Ja,isAsync:()=>aa,isDirty:()=>Wa,isValid:()=>Jt,late:()=>rh,lazy:()=>Ph,literal:()=>Rh,makeIssue:()=>Ta,map:()=>xh,nan:()=>sh,nativeEnum:()=>kh,never:()=>fh,null:()=>ch,nullable:()=>$h,number:()=>Si,object:()=>mh,objectUtil:()=>Ls,oboolean:()=>Fh,onumber:()=>Dh,optional:()=>Ih,ostring:()=>Nh,pipeline:()=>jh,preprocess:()=>Ah,promise:()=>Ch,quotelessJson:()=>Of,record:()=>Sh,set:()=>Eh,setErrorMap:()=>$f,strictObject:()=>vh,string:()=>bi,symbol:()=>oh,transformer:()=>Oh,tuple:()=>bh,undefined:()=>lh,union:()=>gh,unknown:()=>dh,util:()=>be,void:()=>hh});var be;(function(s){s.assertEqual=n=>{};function t(n){}s.assertIs=t;function r(n){throw new Error}s.assertNever=r,s.arrayToEnum=n=>{let i={};for(let a of n)i[a]=a;return i},s.getValidEnumValues=n=>{let i=s.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),a={};for(let o of i)a[o]=n[o];return s.objectValues(a)},s.objectValues=n=>s.objectKeys(n).map(function(i){return n[i]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&i.push(a);return i},s.find=(n,i)=>{for(let a of n)if(i(a))return a},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function e(n,i=" | "){return n.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}s.joinValues=e,s.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(be||(be={}));var Ls;(function(s){s.mergeShapes=(t,r)=>({...t,...r})})(Ls||(Ls={}));var J=be.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$t=s=>{switch(typeof s){case"undefined":return J.undefined;case"string":return J.string;case"number":return Number.isNaN(s)?J.nan:J.number;case"boolean":return J.boolean;case"function":return J.function;case"bigint":return J.bigint;case"symbol":return J.symbol;case"object":return Array.isArray(s)?J.array:s===null?J.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?J.promise:typeof Map<"u"&&s instanceof Map?J.map:typeof Set<"u"&&s instanceof Set?J.set:typeof Date<"u"&&s instanceof Date?J.date:J.object;default:return J.unknown}};var q=be.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"]),Of=s=>JSON.stringify(s,null,2).replace(/"([^"]+)":/g,"$1:"),st=class s extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(i){return i.message},e={_errors:[]},n=i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(n);else if(a.code==="invalid_return_type")n(a.returnTypeError);else if(a.code==="invalid_arguments")n(a.argumentsError);else if(a.path.length===0)e._errors.push(r(a));else{let o=e,c=0;for(;cr.message){let r={},e=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(t(n))}else e.push(t(n));return{formErrors:e,fieldErrors:r}}get formErrors(){return this.flatten()}};st.create=s=>new st(s);var If=(s,t)=>{let r;switch(s.code){case q.invalid_type:s.received===J.undefined?r="Required":r=`Expected ${s.expected}, received ${s.received}`;break;case q.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(s.expected,be.jsonStringifyReplacer)}`;break;case q.unrecognized_keys:r=`Unrecognized key(s) in object: ${be.joinValues(s.keys,", ")}`;break;case q.invalid_union:r="Invalid input";break;case q.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${be.joinValues(s.options)}`;break;case q.invalid_enum_value:r=`Invalid enum value. Expected ${be.joinValues(s.options)}, received '${s.received}'`;break;case q.invalid_arguments:r="Invalid function arguments";break;case q.invalid_return_type:r="Invalid function return type";break;case q.invalid_date:r="Invalid date";break;case q.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(r=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?r=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?r=`Invalid input: must end with "${s.validation.endsWith}"`:be.assertNever(s.validation):s.validation!=="regex"?r=`Invalid ${s.validation}`:r="Invalid";break;case q.too_small:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:r="Invalid input";break;case q.too_big:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?r=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:r="Invalid input";break;case q.custom:r="Invalid input";break;case q.invalid_intersection_types:r="Intersection results could not be merged";break;case q.not_multiple_of:r=`Number must be a multiple of ${s.multipleOf}`;break;case q.not_finite:r="Number must be finite";break;default:r=t.defaultError,be.assertNever(s)}return{message:r}},Ut=If;var fi=Ut;function $f(s){fi=s}function ra(){return fi}var Ta=s=>{let{data:t,path:r,errorMaps:e,issueData:n}=s,i=[...r,...n.path||[]],a={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let o="",c=e.filter(l=>!!l).slice().reverse();for(let l of c)o=l(a,{data:t,defaultError:o}).message;return{...n,path:i,message:o}},Af=[];function B(s,t){let r=ra(),e=Ta({issueData:t,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,r,r===Ut?void 0:Ut].filter(n=>!!n)});s.common.issues.push(e)}var Je=class s{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let e=[];for(let n of r){if(n.status==="aborted")return re;n.status==="dirty"&&t.dirty(),e.push(n.value)}return{status:t.value,value:e}}static async mergeObjectAsync(t,r){let e=[];for(let n of r){let i=await n.key,a=await n.value;e.push({key:i,value:a})}return s.mergeObjectSync(t,e)}static mergeObjectSync(t,r){let e={};for(let n of r){let{key:i,value:a}=n;if(i.status==="aborted"||a.status==="aborted")return re;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||n.alwaysSet)&&(e[i.value]=a.value)}return{status:t.value,value:e}}},re=Object.freeze({status:"aborted"}),br=s=>({status:"dirty",value:s}),Ye=s=>({status:"valid",value:s}),Ja=s=>s.status==="aborted",Wa=s=>s.status==="dirty",Jt=s=>s.status==="valid",aa=s=>typeof Promise<"u"&&s instanceof Promise;var ee;(function(s){s.errToObj=t=>typeof t=="string"?{message:t}:t||{},s.toString=t=>typeof t=="string"?t:t?.message})(ee||(ee={}));var _t=class{constructor(t,r,e,n){this._cachedPath=[],this.parent=t,this.data=r,this._path=e,this._key=n}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}},hi=(s,t)=>{if(Jt(t))return{success:!0,data:t.value};if(!s.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 st(s.common.issues);return this._error=r,this._error}}};function pe(s){if(!s)return{};let{errorMap:t,invalid_type_error:r,required_error:e,description:n}=s;if(t&&(r||e))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:n}:{errorMap:(a,o)=>{let{message:c}=s;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??e??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:n}}var ge=class{get description(){return this._def.description}_getType(t){return $t(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:$t(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Je,ctx:{common:t.parent.common,data:t.data,parsedType:$t(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(aa(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let e=this.safeParse(t,r);if(e.success)return e.data;throw e.error}safeParse(t,r){let e={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:$t(t)},n=this._parseSync({data:t,path:e.path,parent:e});return hi(e,n)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:$t(t)};if(!this["~standard"].async)try{let e=this._parseSync({data:t,path:[],parent:r});return Jt(e)?{value:e.value}:{issues:r.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(e=>Jt(e)?{value:e.value}:{issues:r.common.issues})}async parseAsync(t,r){let e=await this.safeParseAsync(t,r);if(e.success)return e.data;throw e.error}async safeParseAsync(t,r){let e={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:$t(t)},n=this._parse({data:t,path:e.path,parent:e}),i=await(aa(n)?n:Promise.resolve(n));return hi(e,i)}refine(t,r){let e=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,i)=>{let a=t(n),o=()=>i.addIssue({code:q.custom,...e(n)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(t,r){return this._refinement((e,n)=>t(e)?!0:(n.addIssue(typeof r=="function"?r(e,n):r),!1))}_refinement(t){return new bt({schema:this,typeName:ne.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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 yt.create(this,this._def)}nullable(){return jt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ht.create(this)}promise(){return Yt.create(this,this._def)}or(t){return Tr.create([this,t],this._def)}and(t){return kr.create(this,t,this._def)}transform(t){return new bt({...pe(this._def),schema:this,typeName:ne.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Ar({...pe(this._def),innerType:this,defaultValue:r,typeName:ne.ZodDefault})}brand(){return new ka({typeName:ne.ZodBranded,type:this,...pe(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new jr({...pe(this._def),innerType:this,catchValue:r,typeName:ne.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Ca.create(this,t)}readonly(){return Nr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},jf=/^c[^\s-]{8,}$/i,Nf=/^[0-9a-z]+$/,Df=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ff=/^[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,Mf=/^[a-z0-9_-]{21}$/i,Lf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,qf=/^[-+]?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)?)??$/,zf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Uf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qs,Zf=/^(?:(?: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])$/,Vf=/^(?:(?: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])$/,Hf=/^(([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]))$/,Bf=/^(([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])$/,Qf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mi="((\\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])))",Jf=new RegExp(`^${mi}$`);function vi(s){let t="[0-5]\\d";s.precision?t=`${t}\\.\\d{${s.precision}}`:s.precision==null&&(t=`${t}(\\.\\d+)?`);let r=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Wf(s){return new RegExp(`^${vi(s)}$`)}function gi(s){let t=`${mi}T${vi(s)}`,r=[];return r.push(s.local?"Z?":"Z"),s.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Kf(s,t){return!!((t==="v4"||!t)&&Zf.test(s)||(t==="v6"||!t)&&Hf.test(s))}function Yf(s,t){if(!Lf.test(s))return!1;try{let[r]=s.split(".");if(!r)return!1;let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(e));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||t&&n.alg!==t)}catch{return!1}}function Xf(s,t){return!!((t==="v4"||!t)&&Vf.test(s)||(t==="v6"||!t)&&Bf.test(s))}var Wt=class s extends ge{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==J.string){let i=this._getOrReturnCtx(t);return B(i,{code:q.invalid_type,expected:J.string,received:i.parsedType}),re}let e=new Je,n;for(let i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(n=this._getOrReturnCtx(t,n),B(n,{code:q.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),e.dirty());else if(i.kind==="length"){let a=t.data.length>i.value,o=t.data.lengtht.test(n),{validation:r,code:q.invalid_string,...ee.errToObj(e)})}_addCheck(t){return new s({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ee.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ee.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ee.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ee.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ee.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ee.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ee.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ee.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ee.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ee.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ee.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ee.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ee.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...ee.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...ee.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ee.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...ee.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...ee.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...ee.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...ee.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...ee.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...ee.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...ee.errToObj(r)})}nonempty(t){return this.min(1,ee.errToObj(t))}trim(){return new s({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew Wt({checks:[],typeName:ne.ZodString,coerce:s?.coerce??!1,...pe(s)});function eh(s,t){let r=(s.toString().split(".")[1]||"").length,e=(t.toString().split(".")[1]||"").length,n=r>e?r:e,i=Number.parseInt(s.toFixed(n).replace(".","")),a=Number.parseInt(t.toFixed(n).replace(".",""));return i%a/10**n}var Sr=class s extends ge{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==J.number){let i=this._getOrReturnCtx(t);return B(i,{code:q.invalid_type,expected:J.number,received:i.parsedType}),re}let e,n=new Je;for(let i of this._def.checks)i.kind==="int"?be.isInteger(t.data)||(e=this._getOrReturnCtx(t,e),B(e,{code:q.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(e=this._getOrReturnCtx(t,e),B(e,{code:q.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?eh(t.data,i.value)!==0&&(e=this._getOrReturnCtx(t,e),B(e,{code:q.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(e=this._getOrReturnCtx(t,e),B(e,{code:q.not_finite,message:i.message}),n.dirty()):be.assertNever(i);return{status:n.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,ee.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ee.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ee.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ee.toString(r))}setLimit(t,r,e,n){return new s({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:e,message:ee.toString(n)}]})}_addCheck(t){return new s({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ee.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ee.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ee.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ee.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ee.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ee.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:ee.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ee.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ee.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.valuet.kind==="int"||t.kind==="multipleOf"&&be.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let e of this._def.checks){if(e.kind==="finite"||e.kind==="int"||e.kind==="multipleOf")return!0;e.kind==="min"?(r===null||e.value>r)&&(r=e.value):e.kind==="max"&&(t===null||e.valuenew Sr({checks:[],typeName:ne.ZodNumber,coerce:s?.coerce||!1,...pe(s)});var xr=class s extends ge{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==J.bigint)return this._getInvalidInput(t);let e,n=new Je;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(e=this._getOrReturnCtx(t,e),B(e,{code:q.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(e=this._getOrReturnCtx(t,e),B(e,{code:q.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):be.assertNever(i);return{status:n.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return B(r,{code:q.invalid_type,expected:J.bigint,received:r.parsedType}),re}gte(t,r){return this.setLimit("min",t,!0,ee.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ee.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ee.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ee.toString(r))}setLimit(t,r,e,n){return new s({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:e,message:ee.toString(n)}]})}_addCheck(t){return new s({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ee.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ee.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ee.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ee.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ee.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew xr({checks:[],typeName:ne.ZodBigInt,coerce:s?.coerce??!1,...pe(s)});var Er=class extends ge{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==J.boolean){let e=this._getOrReturnCtx(t);return B(e,{code:q.invalid_type,expected:J.boolean,received:e.parsedType}),re}return Ye(t.data)}};Er.create=s=>new Er({typeName:ne.ZodBoolean,coerce:s?.coerce||!1,...pe(s)});var wr=class s extends ge{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==J.date){let i=this._getOrReturnCtx(t);return B(i,{code:q.invalid_type,expected:J.date,received:i.parsedType}),re}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return B(i,{code:q.invalid_date}),re}let e=new Je,n;for(let i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(n=this._getOrReturnCtx(t,n),B(n,{code:q.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),e.dirty()):be.assertNever(i);return{status:e.value,value:new Date(t.data.getTime())}}_addCheck(t){return new s({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:ee.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:ee.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew wr({checks:[],coerce:s?.coerce||!1,typeName:ne.ZodDate,...pe(s)});var na=class extends ge{_parse(t){if(this._getType(t)!==J.symbol){let e=this._getOrReturnCtx(t);return B(e,{code:q.invalid_type,expected:J.symbol,received:e.parsedType}),re}return Ye(t.data)}};na.create=s=>new na({typeName:ne.ZodSymbol,...pe(s)});var Pr=class extends ge{_parse(t){if(this._getType(t)!==J.undefined){let e=this._getOrReturnCtx(t);return B(e,{code:q.invalid_type,expected:J.undefined,received:e.parsedType}),re}return Ye(t.data)}};Pr.create=s=>new Pr({typeName:ne.ZodUndefined,...pe(s)});var Rr=class extends ge{_parse(t){if(this._getType(t)!==J.null){let e=this._getOrReturnCtx(t);return B(e,{code:q.invalid_type,expected:J.null,received:e.parsedType}),re}return Ye(t.data)}};Rr.create=s=>new Rr({typeName:ne.ZodNull,...pe(s)});var Kt=class extends ge{constructor(){super(...arguments),this._any=!0}_parse(t){return Ye(t.data)}};Kt.create=s=>new Kt({typeName:ne.ZodAny,...pe(s)});var Vt=class extends ge{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ye(t.data)}};Vt.create=s=>new Vt({typeName:ne.ZodUnknown,...pe(s)});var Pt=class extends ge{_parse(t){let r=this._getOrReturnCtx(t);return B(r,{code:q.invalid_type,expected:J.never,received:r.parsedType}),re}};Pt.create=s=>new Pt({typeName:ne.ZodNever,...pe(s)});var ia=class extends ge{_parse(t){if(this._getType(t)!==J.undefined){let e=this._getOrReturnCtx(t);return B(e,{code:q.invalid_type,expected:J.void,received:e.parsedType}),re}return Ye(t.data)}};ia.create=s=>new ia({typeName:ne.ZodVoid,...pe(s)});var Ht=class s extends ge{_parse(t){let{ctx:r,status:e}=this._processInputParams(t),n=this._def;if(r.parsedType!==J.array)return B(r,{code:q.invalid_type,expected:J.array,received:r.parsedType}),re;if(n.exactLength!==null){let a=r.data.length>n.exactLength.value,o=r.data.lengthn.maxLength.value&&(B(r,{code:q.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),e.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>n.type._parseAsync(new _t(r,a,r.path,o)))).then(a=>Je.mergeArray(e,a));let i=[...r.data].map((a,o)=>n.type._parseSync(new _t(r,a,r.path,o)));return Je.mergeArray(e,i)}get element(){return this._def.type}min(t,r){return new s({...this._def,minLength:{value:t,message:ee.toString(r)}})}max(t,r){return new s({...this._def,maxLength:{value:t,message:ee.toString(r)}})}length(t,r){return new s({...this._def,exactLength:{value:t,message:ee.toString(r)}})}nonempty(t){return this.min(1,t)}};Ht.create=(s,t)=>new Ht({type:s,minLength:null,maxLength:null,exactLength:null,typeName:ne.ZodArray,...pe(t)});function sa(s){if(s instanceof nt){let t={};for(let r in s.shape){let e=s.shape[r];t[r]=yt.create(sa(e))}return new nt({...s._def,shape:()=>t})}else return s instanceof Ht?new Ht({...s._def,type:sa(s.element)}):s instanceof yt?yt.create(sa(s.unwrap())):s instanceof jt?jt.create(sa(s.unwrap())):s instanceof At?At.create(s.items.map(t=>sa(t))):s}var nt=class s extends ge{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=be.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==J.object){let l=this._getOrReturnCtx(t);return B(l,{code:q.invalid_type,expected:J.object,received:l.parsedType}),re}let{status:e,ctx:n}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Pt&&this._def.unknownKeys==="strip"))for(let l in n.data)a.includes(l)||o.push(l);let c=[];for(let l of a){let f=i[l],y=n.data[l];c.push({key:{status:"valid",value:l},value:f._parse(new _t(n,y,n.path,l)),alwaysSet:l in n.data})}if(this._def.catchall instanceof Pt){let l=this._def.unknownKeys;if(l==="passthrough")for(let f of o)c.push({key:{status:"valid",value:f},value:{status:"valid",value:n.data[f]}});else if(l==="strict")o.length>0&&(B(n,{code:q.unrecognized_keys,keys:o}),e.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let f of o){let y=n.data[f];c.push({key:{status:"valid",value:f},value:l._parse(new _t(n,y,n.path,f)),alwaysSet:f in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let l=[];for(let f of c){let y=await f.key,R=await f.value;l.push({key:y,value:R,alwaysSet:f.alwaysSet})}return l}).then(l=>Je.mergeObjectSync(e,l)):Je.mergeObjectSync(e,c)}get shape(){return this._def.shape()}strict(t){return ee.errToObj,new s({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,e)=>{let n=this._def.errorMap?.(r,e).message??e.defaultError;return r.code==="unrecognized_keys"?{message:ee.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new s({...this._def,unknownKeys:"strip"})}passthrough(){return new s({...this._def,unknownKeys:"passthrough"})}extend(t){return new s({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new s({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ne.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new s({...this._def,catchall:t})}pick(t){let r={};for(let e of be.objectKeys(t))t[e]&&this.shape[e]&&(r[e]=this.shape[e]);return new s({...this._def,shape:()=>r})}omit(t){let r={};for(let e of be.objectKeys(this.shape))t[e]||(r[e]=this.shape[e]);return new s({...this._def,shape:()=>r})}deepPartial(){return sa(this)}partial(t){let r={};for(let e of be.objectKeys(this.shape)){let n=this.shape[e];t&&!t[e]?r[e]=n:r[e]=n.optional()}return new s({...this._def,shape:()=>r})}required(t){let r={};for(let e of be.objectKeys(this.shape))if(t&&!t[e])r[e]=this.shape[e];else{let i=this.shape[e];for(;i instanceof yt;)i=i._def.innerType;r[e]=i}return new s({...this._def,shape:()=>r})}keyof(){return yi(be.objectKeys(this.shape))}};nt.create=(s,t)=>new nt({shape:()=>s,unknownKeys:"strip",catchall:Pt.create(),typeName:ne.ZodObject,...pe(t)});nt.strictCreate=(s,t)=>new nt({shape:()=>s,unknownKeys:"strict",catchall:Pt.create(),typeName:ne.ZodObject,...pe(t)});nt.lazycreate=(s,t)=>new nt({shape:s,unknownKeys:"strip",catchall:Pt.create(),typeName:ne.ZodObject,...pe(t)});var Tr=class extends ge{_parse(t){let{ctx:r}=this._processInputParams(t),e=this._def.options;function n(i){for(let o of i)if(o.result.status==="valid")return o.result;for(let o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(o=>new st(o.ctx.common.issues));return B(r,{code:q.invalid_union,unionErrors:a}),re}if(r.common.async)return Promise.all(e.map(async i=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(n);{let i,a=[];for(let c of e){let l={...r,common:{...r.common,issues:[]},parent:null},f=c._parseSync({data:r.data,path:r.path,parent:l});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let o=a.map(c=>new st(c));return B(r,{code:q.invalid_union,unionErrors:o}),re}}get options(){return this._def.options}};Tr.create=(s,t)=>new Tr({options:s,typeName:ne.ZodUnion,...pe(t)});var Zt=s=>s instanceof Cr?Zt(s.schema):s instanceof bt?Zt(s.innerType()):s instanceof Or?[s.value]:s instanceof Ir?s.options:s instanceof $r?be.objectValues(s.enum):s instanceof Ar?Zt(s._def.innerType):s instanceof Pr?[void 0]:s instanceof Rr?[null]:s instanceof yt?[void 0,...Zt(s.unwrap())]:s instanceof jt?[null,...Zt(s.unwrap())]:s instanceof ka||s instanceof Nr?Zt(s.unwrap()):s instanceof jr?Zt(s._def.innerType):[],Ka=class s extends ge{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==J.object)return B(r,{code:q.invalid_type,expected:J.object,received:r.parsedType}),re;let e=this.discriminator,n=r.data[e],i=this.optionsMap.get(n);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(B(r,{code:q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[e]}),re)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,e){let n=new Map;for(let i of r){let a=Zt(i.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of a){if(n.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);n.set(o,i)}}return new s({typeName:ne.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...pe(e)})}};function zs(s,t){let r=$t(s),e=$t(t);if(s===t)return{valid:!0,data:s};if(r===J.object&&e===J.object){let n=be.objectKeys(t),i=be.objectKeys(s).filter(o=>n.indexOf(o)!==-1),a={...s,...t};for(let o of i){let c=zs(s[o],t[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(r===J.array&&e===J.array){if(s.length!==t.length)return{valid:!1};let n=[];for(let i=0;i{if(Ja(i)||Ja(a))return re;let o=zs(i.value,a.value);return o.valid?((Wa(i)||Wa(a))&&r.dirty(),{status:r.value,value:o.data}):(B(e,{code:q.invalid_intersection_types}),re)};return e.common.async?Promise.all([this._def.left._parseAsync({data:e.data,path:e.path,parent:e}),this._def.right._parseAsync({data:e.data,path:e.path,parent:e})]).then(([i,a])=>n(i,a)):n(this._def.left._parseSync({data:e.data,path:e.path,parent:e}),this._def.right._parseSync({data:e.data,path:e.path,parent:e}))}};kr.create=(s,t,r)=>new kr({left:s,right:t,typeName:ne.ZodIntersection,...pe(r)});var At=class s extends ge{_parse(t){let{status:r,ctx:e}=this._processInputParams(t);if(e.parsedType!==J.array)return B(e,{code:q.invalid_type,expected:J.array,received:e.parsedType}),re;if(e.data.lengththis._def.items.length&&(B(e,{code:q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...e.data].map((a,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new _t(e,a,e.path,o)):null}).filter(a=>!!a);return e.common.async?Promise.all(i).then(a=>Je.mergeArray(r,a)):Je.mergeArray(r,i)}get items(){return this._def.items}rest(t){return new s({...this._def,rest:t})}};At.create=(s,t)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new At({items:s,typeName:ne.ZodTuple,rest:null,...pe(t)})};var Ya=class s extends ge{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:e}=this._processInputParams(t);if(e.parsedType!==J.object)return B(e,{code:q.invalid_type,expected:J.object,received:e.parsedType}),re;let n=[],i=this._def.keyType,a=this._def.valueType;for(let o in e.data)n.push({key:i._parse(new _t(e,o,e.path,o)),value:a._parse(new _t(e,e.data[o],e.path,o)),alwaysSet:o in e.data});return e.common.async?Je.mergeObjectAsync(r,n):Je.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,e){return r instanceof ge?new s({keyType:t,valueType:r,typeName:ne.ZodRecord,...pe(e)}):new s({keyType:Wt.create(),valueType:t,typeName:ne.ZodRecord,...pe(r)})}},oa=class extends ge{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:e}=this._processInputParams(t);if(e.parsedType!==J.map)return B(e,{code:q.invalid_type,expected:J.map,received:e.parsedType}),re;let n=this._def.keyType,i=this._def.valueType,a=[...e.data.entries()].map(([o,c],l)=>({key:n._parse(new _t(e,o,e.path,[l,"key"])),value:i._parse(new _t(e,c,e.path,[l,"value"]))}));if(e.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of a){let l=await c.key,f=await c.value;if(l.status==="aborted"||f.status==="aborted")return re;(l.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(l.value,f.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of a){let l=c.key,f=c.value;if(l.status==="aborted"||f.status==="aborted")return re;(l.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(l.value,f.value)}return{status:r.value,value:o}}}};oa.create=(s,t,r)=>new oa({valueType:t,keyType:s,typeName:ne.ZodMap,...pe(r)});var la=class s extends ge{_parse(t){let{status:r,ctx:e}=this._processInputParams(t);if(e.parsedType!==J.set)return B(e,{code:q.invalid_type,expected:J.set,received:e.parsedType}),re;let n=this._def;n.minSize!==null&&e.data.sizen.maxSize.value&&(B(e,{code:q.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let i=this._def.valueType;function a(c){let l=new Set;for(let f of c){if(f.status==="aborted")return re;f.status==="dirty"&&r.dirty(),l.add(f.value)}return{status:r.value,value:l}}let o=[...e.data.values()].map((c,l)=>i._parse(new _t(e,c,e.path,l)));return e.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(t,r){return new s({...this._def,minSize:{value:t,message:ee.toString(r)}})}max(t,r){return new s({...this._def,maxSize:{value:t,message:ee.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};la.create=(s,t)=>new la({valueType:s,minSize:null,maxSize:null,typeName:ne.ZodSet,...pe(t)});var Xa=class s extends ge{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==J.function)return B(r,{code:q.invalid_type,expected:J.function,received:r.parsedType}),re;function e(o,c){return Ta({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ra(),Ut].filter(l=>!!l),issueData:{code:q.invalid_arguments,argumentsError:c}})}function n(o,c){return Ta({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ra(),Ut].filter(l=>!!l),issueData:{code:q.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Yt){let o=this;return Ye(async function(...c){let l=new st([]),f=await o._def.args.parseAsync(c,i).catch(m=>{throw l.addIssue(e(c,m)),l}),y=await Reflect.apply(a,this,f);return await o._def.returns._def.type.parseAsync(y,i).catch(m=>{throw l.addIssue(n(y,m)),l})})}else{let o=this;return Ye(function(...c){let l=o._def.args.safeParse(c,i);if(!l.success)throw new st([e(c,l.error)]);let f=Reflect.apply(a,this,l.data),y=o._def.returns.safeParse(f,i);if(!y.success)throw new st([n(f,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new s({...this._def,args:At.create(t).rest(Vt.create())})}returns(t){return new s({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,e){return new s({args:t||At.create([]).rest(Vt.create()),returns:r||Vt.create(),typeName:ne.ZodFunction,...pe(e)})}},Cr=class extends ge{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Cr.create=(s,t)=>new Cr({getter:s,typeName:ne.ZodLazy,...pe(t)});var Or=class extends ge{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return B(r,{received:r.data,code:q.invalid_literal,expected:this._def.value}),re}return{status:"valid",value:t.data}}get value(){return this._def.value}};Or.create=(s,t)=>new Or({value:s,typeName:ne.ZodLiteral,...pe(t)});function yi(s,t){return new Ir({values:s,typeName:ne.ZodEnum,...pe(t)})}var Ir=class s extends ge{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),e=this._def.values;return B(r,{expected:be.joinValues(e),received:r.parsedType,code:q.invalid_type}),re}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),e=this._def.values;return B(r,{received:r.data,code:q.invalid_enum_value,options:e}),re}return Ye(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return s.create(t,{...this._def,...r})}exclude(t,r=this._def){return s.create(this.options.filter(e=>!t.includes(e)),{...this._def,...r})}};Ir.create=yi;var $r=class extends ge{_parse(t){let r=be.getValidEnumValues(this._def.values),e=this._getOrReturnCtx(t);if(e.parsedType!==J.string&&e.parsedType!==J.number){let n=be.objectValues(r);return B(e,{expected:be.joinValues(n),received:e.parsedType,code:q.invalid_type}),re}if(this._cache||(this._cache=new Set(be.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let n=be.objectValues(r);return B(e,{received:e.data,code:q.invalid_enum_value,options:n}),re}return Ye(t.data)}get enum(){return this._def.values}};$r.create=(s,t)=>new $r({values:s,typeName:ne.ZodNativeEnum,...pe(t)});var Yt=class extends ge{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==J.promise&&r.common.async===!1)return B(r,{code:q.invalid_type,expected:J.promise,received:r.parsedType}),re;let e=r.parsedType===J.promise?r.data:Promise.resolve(r.data);return Ye(e.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Yt.create=(s,t)=>new Yt({type:s,typeName:ne.ZodPromise,...pe(t)});var bt=class extends ge{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ne.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:e}=this._processInputParams(t),n=this._def.effect||null,i={addIssue:a=>{B(e,a),a.fatal?r.abort():r.dirty()},get path(){return e.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let a=n.transform(e.data,i);if(e.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return re;let c=await this._def.schema._parseAsync({data:o,path:e.path,parent:e});return c.status==="aborted"?re:c.status==="dirty"?br(c.value):r.value==="dirty"?br(c.value):c});{if(r.value==="aborted")return re;let o=this._def.schema._parseSync({data:a,path:e.path,parent:e});return o.status==="aborted"?re:o.status==="dirty"?br(o.value):r.value==="dirty"?br(o.value):o}}if(n.type==="refinement"){let a=o=>{let c=n.refinement(o,i);if(e.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(e.common.async===!1){let o=this._def.schema._parseSync({data:e.data,path:e.path,parent:e});return o.status==="aborted"?re:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:e.data,path:e.path,parent:e}).then(o=>o.status==="aborted"?re:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(n.type==="transform")if(e.common.async===!1){let a=this._def.schema._parseSync({data:e.data,path:e.path,parent:e});if(!Jt(a))return re;let o=n.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:e.data,path:e.path,parent:e}).then(a=>Jt(a)?Promise.resolve(n.transform(a.value,i)).then(o=>({status:r.value,value:o})):re);be.assertNever(n)}};bt.create=(s,t,r)=>new bt({schema:s,typeName:ne.ZodEffects,effect:t,...pe(r)});bt.createWithPreprocess=(s,t,r)=>new bt({schema:t,effect:{type:"preprocess",transform:s},typeName:ne.ZodEffects,...pe(r)});var yt=class extends ge{_parse(t){return this._getType(t)===J.undefined?Ye(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};yt.create=(s,t)=>new yt({innerType:s,typeName:ne.ZodOptional,...pe(t)});var jt=class extends ge{_parse(t){return this._getType(t)===J.null?Ye(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};jt.create=(s,t)=>new jt({innerType:s,typeName:ne.ZodNullable,...pe(t)});var Ar=class extends ge{_parse(t){let{ctx:r}=this._processInputParams(t),e=r.data;return r.parsedType===J.undefined&&(e=this._def.defaultValue()),this._def.innerType._parse({data:e,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ar.create=(s,t)=>new Ar({innerType:s,typeName:ne.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...pe(t)});var jr=class extends ge{_parse(t){let{ctx:r}=this._processInputParams(t),e={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:e.data,path:e.path,parent:{...e}});return aa(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new st(e.common.issues)},input:e.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new st(e.common.issues)},input:e.data})}}removeCatch(){return this._def.innerType}};jr.create=(s,t)=>new jr({innerType:s,typeName:ne.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...pe(t)});var ca=class extends ge{_parse(t){if(this._getType(t)!==J.nan){let e=this._getOrReturnCtx(t);return B(e,{code:q.invalid_type,expected:J.nan,received:e.parsedType}),re}return{status:"valid",value:t.data}}};ca.create=s=>new ca({typeName:ne.ZodNaN,...pe(s)});var th=Symbol("zod_brand"),ka=class extends ge{_parse(t){let{ctx:r}=this._processInputParams(t),e=r.data;return this._def.type._parse({data:e,path:r.path,parent:r})}unwrap(){return this._def.type}},Ca=class s extends ge{_parse(t){let{status:r,ctx:e}=this._processInputParams(t);if(e.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:e.data,path:e.path,parent:e});return i.status==="aborted"?re:i.status==="dirty"?(r.dirty(),br(i.value)):this._def.out._parseAsync({data:i.value,path:e.path,parent:e})})();{let n=this._def.in._parseSync({data:e.data,path:e.path,parent:e});return n.status==="aborted"?re:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:e.path,parent:e})}}static create(t,r){return new s({in:t,out:r,typeName:ne.ZodPipeline})}},Nr=class extends ge{_parse(t){let r=this._def.innerType._parse(t),e=n=>(Jt(n)&&(n.value=Object.freeze(n.value)),n);return aa(r)?r.then(n=>e(n)):e(r)}unwrap(){return this._def.innerType}};Nr.create=(s,t)=>new Nr({innerType:s,typeName:ne.ZodReadonly,...pe(t)});function pi(s,t){let r=typeof s=="function"?s(t):typeof s=="string"?{message:s}:s;return typeof r=="string"?{message:r}:r}function _i(s,t={},r){return s?Kt.create().superRefine((e,n)=>{let i=s(e);if(i instanceof Promise)return i.then(a=>{if(!a){let o=pi(t,e),c=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:c})}});if(!i){let a=pi(t,e),o=a.fatal??r??!0;n.addIssue({code:"custom",...a,fatal:o})}}):Kt.create()}var rh={object:nt.lazycreate},ne;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(ne||(ne={}));var ah=(s,t={message:`Input not instance of ${s.name}`})=>_i(r=>r instanceof s,t),bi=Wt.create,Si=Sr.create,sh=ca.create,nh=xr.create,xi=Er.create,ih=wr.create,oh=na.create,lh=Pr.create,ch=Rr.create,uh=Kt.create,dh=Vt.create,fh=Pt.create,hh=ia.create,ph=Ht.create,mh=nt.create,vh=nt.strictCreate,gh=Tr.create,yh=Ka.create,_h=kr.create,bh=At.create,Sh=Ya.create,xh=oa.create,Eh=la.create,wh=Xa.create,Ph=Cr.create,Rh=Or.create,Th=Ir.create,kh=$r.create,Ch=Yt.create,Oh=bt.create,Ih=yt.create,$h=jt.create,Ah=bt.createWithPreprocess,jh=Ca.create,Nh=()=>bi().optional(),Dh=()=>Si().optional(),Fh=()=>xi().optional(),Mh={string:s=>Wt.create({...s,coerce:!0}),number:s=>Sr.create({...s,coerce:!0}),boolean:s=>Er.create({...s,coerce:!0}),bigint:s=>xr.create({...s,coerce:!0}),date:s=>wr.create({...s,coerce:!0})};var Lh=re;import zh from"better-sqlite3";import{join as Rt,dirname as Vp,basename as Hp}from"path";import{homedir as Ei}from"os";import{existsSync as Jp,mkdirSync as qh}from"fs";var Xt=process.env.CLAUDE_MEM_DATA_DIR||Rt(Ei(),".claude-mem"),Us=process.env.CLAUDE_CONFIG_DIR||Rt(Ei(),".claude"),Wp=Rt(Xt,"archives"),Kp=Rt(Xt,"logs"),Yp=Rt(Xt,"trash"),Xp=Rt(Xt,"backups"),em=Rt(Xt,"settings.json"),wi=Rt(Xt,"claude-mem.db"),tm=Rt(Us,"settings.json"),rm=Rt(Us,"commands"),am=Rt(Us,"CLAUDE.md");function Pi(s){qh(s,{recursive:!0})}var es=class{db;constructor(t){t||(Pi(Xt),t=wi),this.db=new zh(t),this.db.pragma("journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){try{if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(e=>e.name==="observations_fts"||e.name==="session_summaries_fts"))return;console.error("[SessionSearch] Creating FTS5 tables..."),this.db.exec(` + CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5( + title, + subtitle, + narrative, + text, + facts, + concepts, + content='observations', + content_rowid='id' + ); + `),this.db.exec(` + INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts) + SELECT id, title, subtitle, narrative, text, facts, concepts + FROM observations; + `),this.db.exec(` + CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN + INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts) + VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts); + END; + + CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN + INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts) + VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts); + END; + + CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN + INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts) + VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts); + INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts) + VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts); + END; + `),this.db.exec(` + CREATE VIRTUAL TABLE IF NOT EXISTS session_summaries_fts USING fts5( + request, + investigated, + learned, + completed, + next_steps, + notes, + content='session_summaries', + content_rowid='id' + ); + `),this.db.exec(` + INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes) + SELECT id, request, investigated, learned, completed, next_steps, notes + FROM session_summaries; + `),this.db.exec(` + CREATE TRIGGER IF NOT EXISTS session_summaries_ai AFTER INSERT ON session_summaries BEGIN + INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes) + VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes); + END; + + CREATE TRIGGER IF NOT EXISTS session_summaries_ad AFTER DELETE ON session_summaries BEGIN + INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes) + VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes); + END; + + CREATE TRIGGER IF NOT EXISTS session_summaries_au AFTER UPDATE ON session_summaries BEGIN + INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes) + VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes); + INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes) + VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes); + END; + `),console.error("[SessionSearch] FTS5 tables created successfully")}catch(t){console.error("[SessionSearch] FTS migration error:",t.message)}}escapeFTS5(t){return t}buildFilterClause(t,r,e="o"){let n=[];if(t.project&&(n.push(`${e}.project = ?`),r.push(t.project)),t.type)if(Array.isArray(t.type)){let i=t.type.map(()=>"?").join(",");n.push(`${e}.type IN (${i})`),r.push(...t.type)}else n.push(`${e}.type = ?`),r.push(t.type);if(t.dateRange){let{start:i,end:a}=t.dateRange;if(i){let o=typeof i=="number"?i:new Date(i).getTime();n.push(`${e}.created_at_epoch >= ?`),r.push(o)}if(a){let o=typeof a=="number"?a:new Date(a).getTime();n.push(`${e}.created_at_epoch <= ?`),r.push(o)}}if(t.concepts){let i=Array.isArray(t.concepts)?t.concepts:[t.concepts],a=i.map(()=>`EXISTS (SELECT 1 FROM json_each(${e}.concepts) WHERE value = ?)`);a.length>0&&(n.push(`(${a.join(" OR ")})`),r.push(...i))}if(t.files){let i=Array.isArray(t.files)?t.files:[t.files],a=i.map(()=>`( + EXISTS (SELECT 1 FROM json_each(${e}.files_read) WHERE value LIKE ?) + OR EXISTS (SELECT 1 FROM json_each(${e}.files_modified) WHERE value LIKE ?) + )`);a.length>0&&(n.push(`(${a.join(" OR ")})`),i.forEach(o=>{r.push(`%${o}%`,`%${o}%`)}))}return n.length>0?n.join(" AND "):""}buildOrderClause(t="relevance",r=!0,e="observations_fts"){switch(t){case"relevance":return r?`ORDER BY ${e}.rank ASC`:"ORDER BY o.created_at_epoch DESC";case"date_desc":return"ORDER BY o.created_at_epoch DESC";case"date_asc":return"ORDER BY o.created_at_epoch ASC";default:return"ORDER BY o.created_at_epoch DESC"}}searchObservations(t,r={}){let e=[],{limit:n=50,offset:i=0,orderBy:a="relevance",...o}=r,c=this.escapeFTS5(t);e.push(c);let l=this.buildFilterClause(o,e,"o"),f=l?`AND ${l}`:"",y=this.buildOrderClause(a,!0),R=` + SELECT + o.*, + observations_fts.rank as rank + FROM observations o + JOIN observations_fts ON o.id = observations_fts.rowid + WHERE observations_fts MATCH ? + ${f} + ${y} + LIMIT ? OFFSET ? + `;e.push(n,i);let m=this.db.prepare(R).all(...e);if(m.length>0){let b=Math.min(...m.map(_=>_.rank||0)),p=Math.max(...m.map(_=>_.rank||0))-b||1;m.forEach(_=>{_.rank!==void 0&&(_.score=1-(_.rank-b)/p)})}return m}searchSessions(t,r={}){let e=[],{limit:n=50,offset:i=0,orderBy:a="relevance",...o}=r,c=this.escapeFTS5(t);e.push(c);let l={...o};delete l.type;let f=this.buildFilterClause(l,e,"s"),b=` + SELECT + s.*, + session_summaries_fts.rank as rank + FROM session_summaries s + JOIN session_summaries_fts ON s.id = session_summaries_fts.rowid + WHERE session_summaries_fts MATCH ? + ${(f?`AND ${f}`:"").replace(/files_read/g,"files_read").replace(/files_modified/g,"files_edited")} + ${a==="relevance"?"ORDER BY session_summaries_fts.rank ASC":a==="date_asc"?"ORDER BY s.created_at_epoch ASC":"ORDER BY s.created_at_epoch DESC"} + LIMIT ? OFFSET ? + `;e.push(n,i);let d=this.db.prepare(b).all(...e);if(d.length>0){let p=Math.min(...d.map(x=>x.rank||0)),g=Math.max(...d.map(x=>x.rank||0))-p||1;d.forEach(x=>{x.rank!==void 0&&(x.score=1-(x.rank-p)/g)})}return d}findByConcept(t,r={}){let e=[],n={...r,concepts:t},a=` + SELECT o.* + FROM observations o + WHERE ${this.buildFilterClause(n,e,"o")} + ORDER BY o.created_at_epoch DESC + `;return this.db.prepare(a).all(...e)}findByFile(t,r={}){let e=[],n={...r,files:t},a=` + SELECT o.* + FROM observations o + WHERE ${this.buildFilterClause(n,e,"o")} + ORDER BY o.created_at_epoch DESC + `,o=this.db.prepare(a).all(...e),c=[],l={...r};delete l.type;let f=[];if(l.project&&(f.push("s.project = ?"),c.push(l.project)),l.dateRange){let{start:m,end:b}=l.dateRange;if(m){let d=typeof m=="number"?m:new Date(m).getTime();f.push("s.created_at_epoch >= ?"),c.push(d)}if(b){let d=typeof b=="number"?b:new Date(b).getTime();f.push("s.created_at_epoch <= ?"),c.push(d)}}f.push(`( + EXISTS (SELECT 1 FROM json_each(s.files_read) WHERE value LIKE ?) + OR EXISTS (SELECT 1 FROM json_each(s.files_edited) WHERE value LIKE ?) + )`),c.push(`%${t}%`,`%${t}%`);let y=` + SELECT s.* + FROM session_summaries s + WHERE ${f.join(" AND ")} + ORDER BY s.created_at_epoch DESC + `,R=this.db.prepare(y).all(...c);return{observations:o,sessions:R}}findByType(t,r={}){let e=[],n={...r,type:t},a=` + SELECT o.* + FROM observations o + WHERE ${this.buildFilterClause(n,e,"o")} + ORDER BY o.created_at_epoch DESC + `;return this.db.prepare(a).all(...e)}advancedSearch(t){let{textQuery:r,searchSessions:e=!0,...n}=t,i=[],a=[];if(r)i=this.searchObservations(r,n),e&&(a=this.searchSessions(r,n));else{let o=[],c=this.buildFilterClause(n,o,"o");if(c){let l=` + SELECT o.* + FROM observations o + WHERE ${c} + ${this.buildOrderClause(n.orderBy,!1)} + LIMIT ? OFFSET ? + `;o.push(n.limit||50,n.offset||0),i=this.db.prepare(l).all(...o)}if(e){let l=[],f={...n};delete f.type;let y=this.buildFilterClause(f,l,"s");if(y){let R=` + SELECT s.* + FROM session_summaries s + WHERE ${y} + ORDER BY s.created_at_epoch DESC + LIMIT ? OFFSET ? + `;l.push(n.limit||50,n.offset||0),a=this.db.prepare(R).all(...l)}}}return{observations:i,sessions:a}}close(){this.db.close()}};var Dr;try{Dr=new es}catch(s){console.error("[search-server] Failed to initialize search:",s.message),process.exit(1)}function Oa(s,t){let r=`claude-mem://observation/${s.id}`,e=s.title||`Observation #${s.id}`,n=[];s.subtitle&&n.push(`**${s.subtitle}**`),s.narrative&&n.push(s.narrative),s.text&&n.push(s.text);let i=[];if(i.push(`Type: ${s.type}`),s.facts)try{let o=JSON.parse(s.facts);o.length>0&&i.push(`Facts: ${o.join("; ")}`)}catch{}if(s.concepts)try{let o=JSON.parse(s.concepts);o.length>0&&i.push(`Concepts: ${o.join(", ")}`)}catch{}if(s.files_read||s.files_modified){let o=[];if(s.files_read)try{o.push(...JSON.parse(s.files_read))}catch{}if(s.files_modified)try{o.push(...JSON.parse(s.files_modified))}catch{}o.length>0&&i.push(`Files: ${[...new Set(o)].join(", ")}`)}i.length>0&&n.push(` +--- +${i.join(" | ")}`);let a=n.join(` + +`);return{type:"search_result",source:r,title:e,content:[{type:"text",text:a||"No content available"}],citations:{enabled:!0}}}function Zs(s,t){let r=`claude-mem://session/${s.sdk_session_id}`,e=s.request||`Session ${s.sdk_session_id.substring(0,8)}`,n=[];s.completed&&n.push(`**Completed:** ${s.completed}`),s.learned&&n.push(`**Learned:** ${s.learned}`),s.investigated&&n.push(`**Investigated:** ${s.investigated}`),s.next_steps&&n.push(`**Next Steps:** ${s.next_steps}`),s.notes&&n.push(`**Notes:** ${s.notes}`);let i=[];if(s.files_read||s.files_edited){let c=[];if(s.files_read)try{c.push(...JSON.parse(s.files_read))}catch{}if(s.files_edited)try{c.push(...JSON.parse(s.files_edited))}catch{}c.length>0&&i.push(`Files: ${[...new Set(c)].join(", ")}`)}let a=new Date(s.created_at_epoch).toLocaleDateString();i.push(`Date: ${a}`),i.length>0&&n.push(` +--- +${i.join(" | ")}`);let o=n.join(` + +`);return{type:"search_result",source:r,title:e,content:[{type:"text",text:o||"No content available"}],citations:{enabled:!0}}}var Ri=G.object({project:G.string().optional().describe("Filter by project name"),type:G.union([G.enum(["decision","bugfix","feature","refactor","discovery","change"]),G.array(G.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).optional().describe("Filter by observation type"),concepts:G.union([G.string(),G.array(G.string())]).optional().describe("Filter by concept tags"),files:G.union([G.string(),G.array(G.string())]).optional().describe("Filter by file paths (partial match)"),dateRange:G.object({start:G.union([G.string(),G.number()]).optional().describe("Start date (ISO string or epoch)"),end:G.union([G.string(),G.number()]).optional().describe("End date (ISO string or epoch)")}).optional().describe("Filter by date range"),limit:G.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:G.number().min(0).default(0).describe("Number of results to skip"),orderBy:G.enum(["relevance","date_desc","date_asc"]).default("relevance").describe("Sort order")}),fm=di({name:"claude-mem-search",version:"1.0.0",tools:[_r("search_observations","Search observations using full-text search across titles, narratives, facts, and concepts",{query:G.string().describe("Search query for FTS5 full-text search"),...Ri.shape},async s=>{try{let{query:t,...r}=s,e=Dr.searchObservations(t,r);return e.length===0?{content:[{type:"text",text:`No observations found matching "${t}"`}]}:{content:e.map((n,i)=>Oa(n,i))}}catch(t){return{content:[{type:"text",text:`Search failed: ${t.message}`}]}}}),_r("search_sessions","Search session summaries using full-text search across requests, completions, learnings, and notes",{query:G.string().describe("Search query for FTS5 full-text search"),project:G.string().optional().describe("Filter by project name"),dateRange:G.object({start:G.union([G.string(),G.number()]).optional(),end:G.union([G.string(),G.number()]).optional()}).optional().describe("Filter by date range"),limit:G.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:G.number().min(0).default(0).describe("Number of results to skip"),orderBy:G.enum(["relevance","date_desc","date_asc"]).default("relevance").describe("Sort order")},async s=>{try{let{query:t,...r}=s,e=Dr.searchSessions(t,r);return e.length===0?{content:[{type:"text",text:`No sessions found matching "${t}"`}]}:{content:e.map((n,i)=>Zs(n,i))}}catch(t){return{content:[{type:"text",text:`Search failed: ${t.message}`}]}}}),_r("find_by_concept","Find observations tagged with a specific concept",{concept:G.string().describe("Concept tag to search for"),project:G.string().optional().describe("Filter by project name"),dateRange:G.object({start:G.union([G.string(),G.number()]).optional(),end:G.union([G.string(),G.number()]).optional()}).optional().describe("Filter by date range")},async s=>{try{let{concept:t,...r}=s,e=Dr.findByConcept(t,r);return e.length===0?{content:[{type:"text",text:`No observations found with concept "${t}"`}]}:{content:e.map((n,i)=>Oa(n,i))}}catch(t){return{content:[{type:"text",text:`Search failed: ${t.message}`}]}}}),_r("find_by_file","Find observations and sessions that reference a specific file path",{filePath:G.string().describe("File path to search for (supports partial matching)"),project:G.string().optional().describe("Filter by project name"),dateRange:G.object({start:G.union([G.string(),G.number()]).optional(),end:G.union([G.string(),G.number()]).optional()}).optional().describe("Filter by date range")},async s=>{try{let{filePath:t,...r}=s,e=Dr.findByFile(t,r);if(e.observations.length+e.sessions.length===0)return{content:[{type:"text",text:`No results found for file "${t}"`}]};let i=[];return e.observations.forEach((a,o)=>{i.push(Oa(a,o))}),e.sessions.forEach((a,o)=>{i.push(Zs(a,o+e.observations.length))}),{content:i}}catch(t){return{content:[{type:"text",text:`Search failed: ${t.message}`}]}}}),_r("find_by_type","Find observations of a specific type (decision, bugfix, feature, refactor, discovery, change)",{type:G.union([G.enum(["decision","bugfix","feature","refactor","discovery","change"]),G.array(G.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).describe("Observation type(s) to filter by"),project:G.string().optional().describe("Filter by project name"),dateRange:G.object({start:G.union([G.string(),G.number()]).optional(),end:G.union([G.string(),G.number()]).optional()}).optional().describe("Filter by date range")},async s=>{try{let{type:t,...r}=s,e=Dr.findByType(t,r);return e.length===0?{content:[{type:"text",text:`No observations found with type "${Array.isArray(t)?t.join(", "):t}"`}]}:{content:e.map((n,i)=>Oa(n,i))}}catch(t){return{content:[{type:"text",text:`Search failed: ${t.message}`}]}}}),_r("advanced_search","Advanced search combining full-text search with structured filters across both observations and sessions",{textQuery:G.string().optional().describe("Optional text query for FTS5 search"),searchSessions:G.boolean().default(!0).describe("Include session summaries in results"),...Ri.shape},async s=>{try{let t=Dr.advancedSearch(s);if(t.observations.length+t.sessions.length===0)return{content:[{type:"text",text:"No results found matching the search criteria"}]};let e=[];return t.observations.forEach((n,i)=>{e.push(Oa(n,i))}),t.sessions.forEach((n,i)=>{e.push(Zs(n,i+t.observations.length))}),{content:e}}catch(t){return{content:[{type:"text",text:`Search failed: ${t.message}`}]}}})]});console.error("[search-server] Starting claude-mem search server..."); diff --git a/plugin/scripts/worker.js b/plugin/scripts/worker.js deleted file mode 100755 index 8305c614..00000000 --- a/plugin/scripts/worker.js +++ /dev/null @@ -1,194 +0,0 @@ -#!/usr/bin/env bun -// @bun -import VJ from"net";import{unlinkSync as kW,existsSync as h9}from"fs";import{join as _8}from"path";import{fileURLToPath as d6}from"url";import{setMaxListeners as u6}from"events";import{spawn as n6}from"child_process";import{createInterface as i6}from"readline";import*as W0 from"fs";import{stat as o6,open as kJ}from"fs/promises";import{join as mX}from"path";import{homedir as lX}from"os";import{dirname as n9,join as a8}from"path";import{cwd as g8}from"process";import{randomUUID as dX}from"crypto";var{create:Y6,getPrototypeOf:J6,defineProperty:c9,getOwnPropertyNames:z6}=Object,G6=Object.prototype.hasOwnProperty,B6=(Q,Y,J)=>{J=Q!=null?Y6(J6(Q)):{};let W=Y||!Q||!Q.__esModule?c9(J,"default",{value:Q,enumerable:!0}):J;for(let z of z6(Q))if(!G6.call(W,z))c9(W,z,{get:()=>Q[z],enumerable:!0});return W},Y0=(Q,Y)=>()=>(Y||Q((Y={exports:{}}).exports,Y),Y.exports),F6=(Q,Y)=>{for(var J in Y)c9(Q,J,{get:Y[J],enumerable:!0,configurable:!0,set:(W)=>Y[J]=()=>W})},H6=Y0((Q,Y)=>{(function(J,W){typeof Q==="object"&&typeof Y!=="undefined"?W(Q):typeof define==="function"&&define.amd?define(["exports"],W):W(J.URI=J.URI||{})})(Q,function(J){function W(){for(var M=arguments.length,q=Array(M),A=0;A1){q[0]=q[0].slice(0,-1);var E=q.length-1;for(var v=1;v= 0x80 (not a basic code point)","invalid-input":"Invalid input"},k=U-N,R=Math.floor,T=String.fromCharCode;function f(M){throw new RangeError(b[M])}function $(M,q){var A=[],E=M.length;while(E--)A[E]=q(M[E]);return A}function p(M,q){var A=M.split("@"),E="";if(A.length>1)E=A[0]+"@",M=A[1];M=M.replace(x,".");var v=M.split("."),n=$(v,q).join(".");return E+n}function d(M){var q=[],A=0,E=M.length;while(A=55296&&v<=56319&&A>1,q+=R(q/A);for(;q>k*V>>1;v+=U)q=R(q/k);return R(v+(k+1)*q/(q+L))},z0=function M(q){var A=[],E=q.length,v=0,n=S,H0=y,M0=q.lastIndexOf(I);if(M0<0)M0=0;for(var A0=0;A0=128)f("not-basic");A.push(q.charCodeAt(A0))}for(var b0=M0>0?M0+1:0;b0=E)f("invalid-input");var I0=s(q.charCodeAt(b0++));if(I0>=U||I0>R((Z-v)/_0))f("overflow");v+=I0*_0;var j0=S0<=H0?N:S0>=H0+V?V:S0-H0;if(I0R(Z/P0))f("overflow");_0*=P0}var V0=A.length+1;if(H0=a(v-K0,V0,K0==0),R(v/V0)>Z-n)f("overflow");n+=R(v/V0),v%=V0,A.splice(v++,0,n)}return String.fromCodePoint.apply(String,A)},g0=function M(q){var A=[];q=d(q);var E=q.length,v=S,n=0,H0=y,M0=!0,A0=!1,b0=void 0;try{for(var K0=q[Symbol.iterator](),_0;!(M0=(_0=K0.next()).done);M0=!0){var S0=_0.value;if(S0<128)A.push(T(S0))}}catch(D1){A0=!0,b0=D1}finally{try{if(!M0&&K0.return)K0.return()}finally{if(A0)throw b0}}var I0=A.length,j0=I0;if(I0)A.push(I);while(j0=v&&d0R((Z-n)/o0))f("overflow");n+=(P0-v)*o0,v=P0;var J1=!0,R1=!1,H1=void 0;try{for(var z9=q[Symbol.iterator](),D9;!(J1=(D9=z9.next()).done);J1=!0){var I9=D9.value;if(I9Z)f("overflow");if(I9==v){var b1=n;for(var S1=U;;S1+=U){var U1=S1<=H0?N:S1>=H0+V?V:S1-H0;if(b1>6|192).toString(16).toUpperCase()+"%"+(q&63|128).toString(16).toUpperCase();else A="%"+(q>>12|224).toString(16).toUpperCase()+"%"+(q>>6&63|128).toString(16).toUpperCase()+"%"+(q&63|128).toString(16).toUpperCase();return A}function h(M){var q="",A=0,E=M.length;while(A=194&&v<224){if(E-A>=6){var n=parseInt(M.substr(A+4,2),16);q+=String.fromCharCode((v&31)<<6|n&63)}else q+=M.substr(A,6);A+=6}else if(v>=224){if(E-A>=9){var H0=parseInt(M.substr(A+4,2),16),M0=parseInt(M.substr(A+7,2),16);q+=String.fromCharCode((v&15)<<12|(H0&63)<<6|M0&63)}else q+=M.substr(A,9);A+=9}else q+=M.substr(A,3),A+=3}return q}function o(M,q){function A(E){var v=h(E);return!v.match(q.UNRESERVED)?E:v}if(M.scheme)M.scheme=String(M.scheme).replace(q.PCT_ENCODED,A).toLowerCase().replace(q.NOT_SCHEME,"");if(M.userinfo!==void 0)M.userinfo=String(M.userinfo).replace(q.PCT_ENCODED,A).replace(q.NOT_USERINFO,C).replace(q.PCT_ENCODED,X);if(M.host!==void 0)M.host=String(M.host).replace(q.PCT_ENCODED,A).toLowerCase().replace(q.NOT_HOST,C).replace(q.PCT_ENCODED,X);if(M.path!==void 0)M.path=String(M.path).replace(q.PCT_ENCODED,A).replace(M.scheme?q.NOT_PATH:q.NOT_PATH_NOSCHEME,C).replace(q.PCT_ENCODED,X);if(M.query!==void 0)M.query=String(M.query).replace(q.PCT_ENCODED,A).replace(q.NOT_QUERY,C).replace(q.PCT_ENCODED,X);if(M.fragment!==void 0)M.fragment=String(M.fragment).replace(q.PCT_ENCODED,A).replace(q.NOT_FRAGMENT,C).replace(q.PCT_ENCODED,X);return M}function G0(M){return M.replace(/^0*(.*)/,"$1")||"0"}function m(M,q){var A=M.match(q.IPV4ADDRESS)||[],E=_(A,2),v=E[1];if(v)return v.split(".").map(G0).join(".");else return M}function u(M,q){var A=M.match(q.IPV6ADDRESS)||[],E=_(A,3),v=E[1],n=E[2];if(v){var H0=v.toLowerCase().split("::").reverse(),M0=_(H0,2),A0=M0[0],b0=M0[1],K0=b0?b0.split(":").map(G0):[],_0=A0.split(":").map(G0),S0=q.IPV4ADDRESS.test(_0[_0.length-1]),I0=S0?7:8,j0=_0.length-I0,P0=Array(I0);for(var V0=0;V01){var O0=P0.slice(0,p0.index),d0=P0.slice(p0.index+p0.length);i0=O0.join(":")+"::"+d0.join(":")}else i0=P0.join(":");if(n)i0+="%"+n;return i0}else return M}var U0=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,q0="".match(/(){0}/)[1]===void 0;function Q0(M){var q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A={},E=q.iri!==!1?w:O;if(q.reference==="suffix")M=(q.scheme?q.scheme+":":"")+"//"+M;var v=M.match(U0);if(v){if(q0){if(A.scheme=v[1],A.userinfo=v[3],A.host=v[4],A.port=parseInt(v[5],10),A.path=v[6]||"",A.query=v[7],A.fragment=v[8],isNaN(A.port))A.port=v[5]}else if(A.scheme=v[1]||void 0,A.userinfo=M.indexOf("@")!==-1?v[3]:void 0,A.host=M.indexOf("//")!==-1?v[4]:void 0,A.port=parseInt(v[5],10),A.path=v[6]||"",A.query=M.indexOf("?")!==-1?v[7]:void 0,A.fragment=M.indexOf("#")!==-1?v[8]:void 0,isNaN(A.port))A.port=M.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?v[4]:void 0;if(A.host)A.host=u(m(A.host,E),E);if(A.scheme===void 0&&A.userinfo===void 0&&A.host===void 0&&A.port===void 0&&!A.path&&A.query===void 0)A.reference="same-document";else if(A.scheme===void 0)A.reference="relative";else if(A.fragment===void 0)A.reference="absolute";else A.reference="uri";if(q.reference&&q.reference!=="suffix"&&q.reference!==A.reference)A.error=A.error||"URI is not a "+q.reference+" reference.";var n=C0[(q.scheme||A.scheme||"").toLowerCase()];if(!q.unicodeSupport&&(!n||!n.unicodeSupport)){if(A.host&&(q.domainHost||n&&n.domainHost))try{A.host=Z0.toASCII(A.host.replace(E.PCT_ENCODED,h).toLowerCase())}catch(H0){A.error=A.error||"Host's domain name can not be converted to ASCII via punycode: "+H0}o(A,O)}else o(A,E);if(n&&n.parse)n.parse(A,q)}else A.error=A.error||"URI can not be parsed.";return A}function w0(M,q){var A=q.iri!==!1?w:O,E=[];if(M.userinfo!==void 0)E.push(M.userinfo),E.push("@");if(M.host!==void 0)E.push(u(m(String(M.host),A),A).replace(A.IPV6ADDRESS,function(v,n,H0){return"["+n+(H0?"%25"+H0:"")+"]"}));if(typeof M.port==="number"||typeof M.port==="string")E.push(":"),E.push(String(M.port));return E.length?E.join(""):void 0}var R0=/^\.\.?\//,L0=/^\/\.(\/|$)/,x0=/^\/\.\.(\/|$)/,E0=/^\/?(?:.|\n)*?(?=\/|$)/;function h0(M){var q=[];while(M.length)if(M.match(R0))M=M.replace(R0,"");else if(M.match(L0))M=M.replace(L0,"/");else if(M.match(x0))M=M.replace(x0,"/"),q.pop();else if(M==="."||M==="..")M="";else{var A=M.match(E0);if(A){var E=A[0];M=M.slice(E.length),q.push(E)}else throw new Error("Unexpected dot segment condition")}return q.join("")}function D0(M){var q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A=q.iri?w:O,E=[],v=C0[(q.scheme||M.scheme||"").toLowerCase()];if(v&&v.serialize)v.serialize(M,q);if(M.host){if(A.IPV6ADDRESS.test(M.host));else if(q.domainHost||v&&v.domainHost)try{M.host=!q.iri?Z0.toASCII(M.host.replace(A.PCT_ENCODED,h).toLowerCase()):Z0.toUnicode(M.host)}catch(M0){M.error=M.error||"Host's domain name can not be converted to "+(!q.iri?"ASCII":"Unicode")+" via punycode: "+M0}}if(o(M,A),q.reference!=="suffix"&&M.scheme)E.push(M.scheme),E.push(":");var n=w0(M,q);if(n!==void 0){if(q.reference!=="suffix")E.push("//");if(E.push(n),M.path&&M.path.charAt(0)!=="/")E.push("/")}if(M.path!==void 0){var H0=M.path;if(!q.absolutePath&&(!v||!v.absolutePath))H0=h0(H0);if(n===void 0)H0=H0.replace(/^\/\//,"/%2F");E.push(H0)}if(M.query!==void 0)E.push("?"),E.push(M.query);if(M.fragment!==void 0)E.push("#"),E.push(M.fragment);return E.join("")}function v0(M,q){var A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},E=arguments[3],v={};if(!E)M=Q0(D0(M,A),A),q=Q0(D0(q,A),A);if(A=A||{},!A.tolerant&&q.scheme)v.scheme=q.scheme,v.userinfo=q.userinfo,v.host=q.host,v.port=q.port,v.path=h0(q.path||""),v.query=q.query;else{if(q.userinfo!==void 0||q.host!==void 0||q.port!==void 0)v.userinfo=q.userinfo,v.host=q.host,v.port=q.port,v.path=h0(q.path||""),v.query=q.query;else{if(!q.path)if(v.path=M.path,q.query!==void 0)v.query=q.query;else v.query=M.query;else{if(q.path.charAt(0)==="/")v.path=h0(q.path);else{if((M.userinfo!==void 0||M.host!==void 0||M.port!==void 0)&&!M.path)v.path="/"+q.path;else if(!M.path)v.path=q.path;else v.path=M.path.slice(0,M.path.lastIndexOf("/")+1)+q.path;v.path=h0(v.path)}v.query=q.query}v.userinfo=M.userinfo,v.host=M.host,v.port=M.port}v.scheme=M.scheme}return v.fragment=q.fragment,v}function n0(M,q,A){var E=K({scheme:"null"},A);return D0(v0(Q0(M,E),Q0(q,E),E,!0),E)}function l0(M,q){if(typeof M==="string")M=D0(Q0(M,q),q);else if(F(M)==="object")M=Q0(D0(M,q),q);return M}function R9(M,q,A){if(typeof M==="string")M=D0(Q0(M,A),A);else if(F(M)==="object")M=D0(M,A);if(typeof q==="string")q=D0(Q0(q,A),A);else if(F(q)==="object")q=D0(q,A);return M===q}function $9(M,q){return M&&M.toString().replace(!q||!q.iri?O.ESCAPE:w.ESCAPE,C)}function t0(M,q){return M&&M.toString().replace(!q||!q.iri?O.PCT_ENCODED:w.PCT_ENCODED,h)}var Y9={scheme:"http",domainHost:!0,parse:function M(q,A){if(!q.host)q.error=q.error||"HTTP URIs must have a host.";return q},serialize:function M(q,A){var E=String(q.scheme).toLowerCase()==="https";if(q.port===(E?443:80)||q.port==="")q.port=void 0;if(!q.path)q.path="/";return q}},U8={scheme:"https",domainHost:Y9.domainHost,parse:Y9.parse,serialize:Y9.serialize};function q8(M){return typeof M.secure==="boolean"?M.secure:String(M.scheme).toLowerCase()==="wss"}var J9={scheme:"ws",domainHost:!0,parse:function M(q,A){var E=q;return E.secure=q8(E),E.resourceName=(E.path||"/")+(E.query?"?"+E.query:""),E.path=void 0,E.query=void 0,E},serialize:function M(q,A){if(q.port===(q8(q)?443:80)||q.port==="")q.port=void 0;if(typeof q.secure==="boolean")q.scheme=q.secure?"wss":"ws",q.secure=void 0;if(q.resourceName){var E=q.resourceName.split("?"),v=_(E,2),n=v[0],H0=v[1];q.path=n&&n!=="/"?n:void 0,q.query=H0,q.resourceName=void 0}return q.fragment=void 0,q}},K8={scheme:"wss",domainHost:J9.domainHost,parse:J9.parse,serialize:J9.serialize},hW={},$W=!0,N8="[A-Za-z0-9\\-\\.\\_\\~"+($W?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Y1="[0-9A-Fa-f]",mW=z(z("%[EFef]"+Y1+"%"+Y1+Y1+"%"+Y1+Y1)+"|"+z("%[89A-Fa-f]"+Y1+"%"+Y1+Y1)+"|"+z("%"+Y1+Y1)),lW="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",pW="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",dW=W(pW,"[\\\"\\\\]"),uW="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",cW=new RegExp(N8,"g"),E1=new RegExp(mW,"g"),nW=new RegExp(W("[^]",lW,"[\\.]","[\\\"]",dW),"g"),M8=new RegExp(W("[^]",N8,uW),"g"),iW=M8;function m9(M){var q=h(M);return!q.match(cW)?M:q}var L8={scheme:"mailto",parse:function M(q,A){var E=q,v=E.to=E.path?E.path.split(","):[];if(E.path=void 0,E.query){var n=!1,H0={},M0=E.query.split("&");for(var A0=0,b0=M0.length;A0{Y.exports=function J(W,z){if(W===z)return!0;if(W&&z&&typeof W=="object"&&typeof z=="object"){if(W.constructor!==z.constructor)return!1;var F,X,B;if(Array.isArray(W)){if(F=W.length,F!=z.length)return!1;for(X=F;X--!==0;)if(!J(W[X],z[X]))return!1;return!0}if(W.constructor===RegExp)return W.source===z.source&&W.flags===z.flags;if(W.valueOf!==Object.prototype.valueOf)return W.valueOf()===z.valueOf();if(W.toString!==Object.prototype.toString)return W.toString()===z.toString();if(B=Object.keys(W),F=B.length,F!==Object.keys(z).length)return!1;for(X=F;X--!==0;)if(!Object.prototype.hasOwnProperty.call(z,B[X]))return!1;for(X=F;X--!==0;){var K=B[X];if(!J(W[K],z[K]))return!1}return!0}return W!==W&&z!==z}}),U6=Y0((Q,Y)=>{Y.exports=function J(W){var z=0,F=W.length,X=0,B;while(X=55296&&B<=56319&&X{Y.exports={copy:J,checkDataType:W,checkDataTypes:z,coerceToTypes:X,toHash:B,getProperty:O,escapeQuotes:w,equal:e9(),ucs2length:U6(),varOccurences:_,varReplace:j,schemaHasRules:Z,schemaHasRulesExcept:U,schemaUnknownRules:N,toQuotedString:V,getPathExpr:L,getPath:D,getData:I,unescapeFragment:g,unescapeJsonPointer:k,escapeFragment:x,escapeJsonPointer:b};function J(R,T){T=T||{};for(var f in R)T[f]=R[f];return T}function W(R,T,f,$){var p=$?" !== ":" === ",d=$?" || ":" && ",X0=$?"!":"",s=$?"":"!";switch(R){case"null":return T+p+"null";case"array":return X0+"Array.isArray("+T+")";case"object":return"("+X0+T+d+"typeof "+T+p+'"object"'+d+s+"Array.isArray("+T+"))";case"integer":return"(typeof "+T+p+'"number"'+d+s+"("+T+" % 1)"+d+T+p+T+(f?d+X0+"isFinite("+T+")":"")+")";case"number":return"(typeof "+T+p+'"'+R+'"'+(f?d+X0+"isFinite("+T+")":"")+")";default:return"typeof "+T+p+'"'+R+'"'}}function z(R,T,f){switch(R.length){case 1:return W(R[0],T,f,!0);default:var $="",p=B(R);if(p.array&&p.object)$=p.null?"(":"(!"+T+" || ",$+="typeof "+T+' !== "object")',delete p.null,delete p.array,delete p.object;if(p.number)delete p.integer;for(var d in p)$+=($?" && ":"")+W(d,T,f,!0);return $}}var F=B(["string","number","integer","boolean","null"]);function X(R,T){if(Array.isArray(T)){var f=[];for(var $=0;$=T)throw new Error("Cannot access property/index "+$+" levels up, current level is "+T);return f[T-$]}if($>T)throw new Error("Cannot access data "+$+" levels up, current level is "+T);if(d="data"+(T-$||""),!p)return d}var s=d,J0=p.split("/");for(var a=0;a{var J=t1();Y.exports=W;function W(z){J.copy(z,this)}}),q6=Y0((Q,Y)=>{var J=Y.exports=function(F,X,B){if(typeof X=="function")B=X,X={};B=X.cb||B;var K=typeof B=="function"?B:B.pre||function(){},H=B.post||function(){};W(X,K,H,F,"",F)};J.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},J.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},J.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},J.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 W(F,X,B,K,H,O,w,_,j,Z){if(K&&typeof K=="object"&&!Array.isArray(K)){X(K,H,O,w,_,j,Z);for(var U in K){var N=K[U];if(Array.isArray(N)){if(U in J.arrayKeywords)for(var V=0;V{var J=H6(),W=e9(),z=t1(),F=h8(),X=q6();Y.exports=B,B.normalizeId=D,B.fullPath=N,B.url=y,B.ids=S,B.inlineRef=j,B.schema=K;function B(I,P,g){var x=this._refs[g];if(typeof x=="string")if(this._refs[x])x=this._refs[x];else return B.call(this,I,P,x);if(x=x||this._schemas[g],x instanceof F)return j(x.schema,this._opts.inlineRefs)?x.schema:x.validate||this._compile(x);var b=K.call(this,P,g),k,R,T;if(b)k=b.schema,P=b.root,T=b.baseId;if(k instanceof F)R=k.validate||I.call(this,k.schema,P,void 0,T);else if(k!==void 0)R=j(k,this._opts.inlineRefs)?k:I.call(this,k,P,void 0,T);return R}function K(I,P){var g=J.parse(P),x=V(g),b=N(this._getId(I.schema));if(Object.keys(I.schema).length===0||x!==b){var k=D(x),R=this._refs[k];if(typeof R=="string")return H.call(this,I,R,g);else if(R instanceof F){if(!R.validate)this._compile(R);I=R}else if(R=this._schemas[k],R instanceof F){if(!R.validate)this._compile(R);if(k==D(P))return{schema:R,root:I,baseId:b};I=R}else return;if(!I.schema)return;b=N(this._getId(I.schema))}return w.call(this,g,b,I.schema,I)}function H(I,P,g){var x=K.call(this,I,P);if(x){var{schema:b,baseId:k}=x;I=x.root;var R=this._getId(b);if(R)k=y(k,R);return w.call(this,g,k,b,I)}}var O=z.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function w(I,P,g,x){if(I.fragment=I.fragment||"",I.fragment.slice(0,1)!="/")return;var b=I.fragment.split("/");for(var k=1;k{var J=W8();Y.exports={Validation:F(W),MissingRef:F(z)};function W(X){this.message="validation failed",this.errors=X,this.ajv=this.validation=!0}z.message=function(X,B){return"can't resolve reference "+B+" from id "+X};function z(X,B,K){this.message=K||z.message(X,B),this.missingRef=J.url(X,B),this.missingSchema=J.normalizeId(J.fullPath(this.missingRef))}function F(X){return X.prototype=Object.create(Error.prototype),X.prototype.constructor=X,X}}),$8=Y0((Q,Y)=>{Y.exports=function(J,W){if(!W)W={};if(typeof W==="function")W={cmp:W};var z=typeof W.cycles==="boolean"?W.cycles:!1,F=W.cmp&&function(B){return function(K){return function(H,O){var w={key:H,value:K[H]},_={key:O,value:K[O]};return B(w,_)}}}(W.cmp),X=[];return function B(K){if(K&&K.toJSON&&typeof K.toJSON==="function")K=K.toJSON();if(K===void 0)return;if(typeof K=="number")return isFinite(K)?""+K:"null";if(typeof K!=="object")return JSON.stringify(K);var H,O;if(Array.isArray(K)){O="[";for(H=0;H{Y.exports=function J(W,z,F){var X="",B=W.schema.$async===!0,K=W.util.schemaHasRulesExcept(W.schema,W.RULES.all,"$ref"),H=W.self._getId(W.schema);if(W.opts.strictKeywords){var O=W.util.schemaUnknownRules(W.schema,W.RULES.keywords);if(O){var w="unknown keyword: "+O;if(W.opts.strictKeywords==="log")W.logger.warn(w);else throw new Error(w)}}if(W.isTop){if(X+=" var validate = ",B)W.async=!0,X+="async ";if(X+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",H&&(W.opts.sourceCode||W.opts.processCode))X+=" "+("/*# sourceURL="+H+" */")+" "}if(typeof W.schema=="boolean"||!(K||W.schema.$ref)){var z="false schema",_=W.level,j=W.dataLevel,Z=W.schema[z],U=W.schemaPath+W.util.getProperty(z),N=W.errSchemaPath+"/"+z,P=!W.opts.allErrors,b,V="data"+(j||""),I="valid"+_;if(W.schema===!1){if(W.isTop)P=!0;else X+=" var "+I+" = false; ";var L=L||[];if(L.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: '"+(b||"false schema")+"' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(N)+" , params: {} ",W.opts.messages!==!1)X+=" , message: 'boolean schema is false' ";if(W.opts.verbose)X+=" , schema: false , parentSchema: validate.schema"+W.schemaPath+" , data: "+V+" ";X+=" } "}else X+=" {} ";var D=X;if(X=L.pop(),!W.compositeRule&&P)if(W.async)X+=" throw new ValidationError(["+D+"]); ";else X+=" validate.errors = ["+D+"]; return false; ";else X+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else if(W.isTop)if(B)X+=" return data; ";else X+=" validate.errors = null; return true; ";else X+=" var "+I+" = true; ";if(W.isTop)X+=" }; return validate; ";return X}if(W.isTop){var y=W.isTop,_=W.level=0,j=W.dataLevel=0,V="data";if(W.rootId=W.resolve.fullPath(W.self._getId(W.root.schema)),W.baseId=W.baseId||W.rootId,delete W.isTop,W.dataPathArr=[""],W.schema.default!==void 0&&W.opts.useDefaults&&W.opts.strictDefaults){var S="default is ignored in the schema root";if(W.opts.strictDefaults==="log")W.logger.warn(S);else throw new Error(S)}X+=" var vErrors = null; ",X+=" var errors = 0; ",X+=" if (rootData === undefined) rootData = data; "}else{var{level:_,dataLevel:j}=W,V="data"+(j||"");if(H)W.baseId=W.resolve.url(W.baseId,H);if(B&&!W.async)throw new Error("async schema in sync schema");X+=" var errs_"+_+" = errors;"}var I="valid"+_,P=!W.opts.allErrors,g="",x="",b,k=W.schema.type,R=Array.isArray(k);if(k&&W.opts.nullable&&W.schema.nullable===!0){if(R){if(k.indexOf("null")==-1)k=k.concat("null")}else if(k!="null")k=[k,"null"],R=!0}if(R&&k.length==1)k=k[0],R=!1;if(W.schema.$ref&&K){if(W.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+W.errSchemaPath+'" (see option extendRefs)');else if(W.opts.extendRefs!==!0)K=!1,W.logger.warn('$ref: keywords ignored in schema at path "'+W.errSchemaPath+'"')}if(W.schema.$comment&&W.opts.$comment)X+=" "+W.RULES.all.$comment.code(W,"$comment");if(k){if(W.opts.coerceTypes)var T=W.util.coerceToTypes(W.opts.coerceTypes,k);var f=W.RULES.types[k];if(T||R||f===!0||f&&!E0(f)){var U=W.schemaPath+".type",N=W.errSchemaPath+"/type",U=W.schemaPath+".type",N=W.errSchemaPath+"/type",$=R?"checkDataTypes":"checkDataType";if(X+=" if ("+W.util[$](k,V,W.opts.strictNumbers,!0)+") { ",T){var p="dataType"+_,d="coerced"+_;if(X+=" var "+p+" = typeof "+V+"; var "+d+" = undefined; ",W.opts.coerceTypes=="array")X+=" if ("+p+" == 'object' && Array.isArray("+V+") && "+V+".length == 1) { "+V+" = "+V+"[0]; "+p+" = typeof "+V+"; if ("+W.util.checkDataType(W.schema.type,V,W.opts.strictNumbers)+") "+d+" = "+V+"; } ";X+=" if ("+d+" !== undefined) ; ";var X0=T;if(X0){var s,J0=-1,a=X0.length-1;while(J0{var J=W8(),W=t1(),z=Q8(),F=$8(),X=m8(),B=W.ucs2length,K=e9(),H=z.Validation;Y.exports=O;function O(D,y,S,I){var P=this,g=this._opts,x=[void 0],b={},k=[],R={},T=[],f={},$=[];y=y||{schema:D,refVal:x,refs:b};var p=w.call(this,D,y,I),d=this._compilations[p.index];if(p.compiling)return d.callValidate=z0;var X0=this._formats,s=this.RULES;try{var J0=g0(D,y,S,I);d.validate=J0;var a=d.callValidate;if(a){if(a.schema=J0.schema,a.errors=null,a.refs=J0.refs,a.refVal=J0.refVal,a.root=J0.root,a.$async=J0.$async,g.sourceCode)a.source=J0.source}return J0}finally{_.call(this,D,y,I)}function z0(){var m=d.validate,u=m.apply(this,arguments);return z0.errors=m.errors,u}function g0(m,u,U0,q0){var Q0=!u||u&&u.schema==m;if(u.schema!=y.schema)return O.call(P,m,u,U0,q0);var w0=m.$async===!0,R0=X({isTop:!0,schema:m,isRoot:Q0,baseId:q0,root:u,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:z.MissingRef,RULES:s,validate:X,util:W,resolve:J,resolveRef:y0,usePattern:h,useDefault:o,useCustomRule:G0,opts:g,formats:X0,logger:P.logger,self:P});if(R0=L(x,N)+L(k,Z)+L(T,U)+L($,V)+R0,g.processCode)R0=g.processCode(R0,m);var L0;try{var x0=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",R0);L0=x0(P,s,X0,y,x,T,$,K,B,H),x[0]=L0}catch(E0){throw P.logger.error("Error compiling schema, function code:",R0),E0}if(L0.schema=m,L0.errors=null,L0.refs=b,L0.refVal=x,L0.root=Q0?L0:u,w0)L0.$async=!0;if(g.sourceCode===!0)L0.source={code:R0,patterns:k,defaults:T};return L0}function y0(m,u,U0){u=J.url(m,u);var q0=b[u],Q0,w0;if(q0!==void 0)return Q0=x[q0],w0="refVal["+q0+"]",C(Q0,w0);if(!U0&&y.refs){var R0=y.refs[u];if(R0!==void 0)return Q0=y.refVal[R0],w0=k0(u,Q0),C(Q0,w0)}w0=k0(u);var L0=J.call(P,g0,y,u);if(L0===void 0){var x0=S&&S[u];if(x0)L0=J.inlineRef(x0,g.inlineRefs)?x0:O.call(P,x0,y,S,m)}if(L0===void 0)Z0(u);else return C0(u,L0),C(L0,w0)}function k0(m,u){var U0=x.length;return x[U0]=u,b[m]=U0,"refVal"+U0}function Z0(m){delete b[m]}function C0(m,u){var U0=b[m];x[U0]=u}function C(m,u){return typeof m=="object"||typeof m=="boolean"?{code:u,schema:m,inline:!0}:{code:u,$async:m&&!!m.$async}}function h(m){var u=R[m];if(u===void 0)u=R[m]=k.length,k[u]=m;return"pattern"+u}function o(m){switch(typeof m){case"boolean":case"number":return""+m;case"string":return W.toQuotedString(m);case"object":if(m===null)return"null";var u=F(m),U0=f[u];if(U0===void 0)U0=f[u]=T.length,T[U0]=m;return"default"+U0}}function G0(m,u,U0,q0){if(P._opts.validateSchema!==!1){var Q0=m.definition.dependencies;if(Q0&&!Q0.every(function(n0){return Object.prototype.hasOwnProperty.call(U0,n0)}))throw new Error("parent schema must have all required keywords: "+Q0.join(","));var w0=m.definition.validateSchema;if(w0){var R0=w0(u);if(!R0){var L0="keyword schema is invalid: "+P.errorsText(w0.errors);if(P._opts.validateSchema=="log")P.logger.error(L0);else throw new Error(L0)}}}var x0=m.definition.compile,E0=m.definition.inline,h0=m.definition.macro,D0;if(x0)D0=x0.call(P,u,U0,q0);else if(h0){if(D0=h0.call(P,u,U0,q0),g.validateSchema!==!1)P.validateSchema(D0,!0)}else if(E0)D0=E0.call(P,q0,m.keyword,u,U0);else if(D0=m.definition.validate,!D0)return;if(D0===void 0)throw new Error('custom keyword "'+m.keyword+'"failed to compile');var v0=$.length;return $[v0]=D0,{code:"customRule"+v0,validate:D0}}}function w(D,y,S){var I=j.call(this,D,y,S);if(I>=0)return{index:I,compiling:!0};return I=this._compilations.length,this._compilations[I]={schema:D,root:y,baseId:S},{index:I,compiling:!1}}function _(D,y,S){var I=j.call(this,D,y,S);if(I>=0)this._compilations.splice(I,1)}function j(D,y,S){for(var I=0;I{var J=Y.exports=function W(){this._cache={}};J.prototype.put=function W(z,F){this._cache[z]=F},J.prototype.get=function W(z){return this._cache[z]},J.prototype.del=function W(z){delete this._cache[z]},J.prototype.clear=function W(){this._cache={}}}),M6=Y0((Q,Y)=>{var J=t1(),W=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,z=[0,31,28,31,30,31,30,31,31,30,31,30,31],F=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,X=/^(?=.{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,B=/^(?:[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,K=/^(?:[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,H=/^(?:(?:[^\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,O=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,w=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,_=/^(?:\/(?:[^~/]|~0|~1)*)*$/,j=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Z=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;Y.exports=U;function U(x){return x=x=="full"?"full":"fast",J.copy(U[x])}U.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":H,url:O,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,hostname:X,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:g,uuid:w,"json-pointer":_,"json-pointer-uri-fragment":j,"relative-json-pointer":Z},U.full={date:V,time:L,"date-time":y,uri:I,"uri-reference":K,"uri-template":H,url:O,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:X,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:g,uuid:w,"json-pointer":_,"json-pointer-uri-fragment":j,"relative-json-pointer":Z};function N(x){return x%4===0&&(x%100!==0||x%400===0)}function V(x){var b=x.match(W);if(!b)return!1;var k=+b[1],R=+b[2],T=+b[3];return R>=1&&R<=12&&T>=1&&T<=(R==2&&N(k)?29:z[R])}function L(x,b){var k=x.match(F);if(!k)return!1;var R=k[1],T=k[2],f=k[3],$=k[5];return(R<=23&&T<=59&&f<=59||R==23&&T==59&&f==60)&&(!b||$)}var D=/t|\s/i;function y(x){var b=x.split(D);return b.length==2&&V(b[0])&&L(b[1],!0)}var S=/\/|:/;function I(x){return S.test(x)&&B.test(x)}var P=/[^\\]\\Z/;function g(x){if(P.test(x))return!1;try{return new RegExp(x),!0}catch(b){return!1}}}),L6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.errSchemaPath+"/"+z,w=!W.opts.allErrors,_="data"+(K||""),j="valid"+B,Z,U;if(H=="#"||H=="#/")if(W.isRoot)Z=W.async,U="validate";else Z=W.root.schema.$async===!0,U="root.refVal[0]";else{var N=W.resolveRef(W.baseId,H,W.isRoot);if(N===void 0){var V=W.MissingRefError.message(W.baseId,H);if(W.opts.missingRefs=="fail"){W.logger.error(V);var L=L||[];if(L.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(O)+" , params: { ref: '"+W.util.escapeQuotes(H)+"' } ",W.opts.messages!==!1)X+=" , message: 'can\\'t resolve reference "+W.util.escapeQuotes(H)+"' ";if(W.opts.verbose)X+=" , schema: "+W.util.toQuotedString(H)+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+_+" ";X+=" } "}else X+=" {} ";var D=X;if(X=L.pop(),!W.compositeRule&&w)if(W.async)X+=" throw new ValidationError(["+D+"]); ";else X+=" validate.errors = ["+D+"]; return false; ";else X+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(w)X+=" if (false) { "}else if(W.opts.missingRefs=="ignore"){if(W.logger.warn(V),w)X+=" if (true) { "}else throw new W.MissingRefError(W.baseId,H,V)}else if(N.inline){var y=W.util.copy(W);y.level++;var S="valid"+y.level;y.schema=N.schema,y.schemaPath="",y.errSchemaPath=H;var I=W.validate(y).replace(/validate\.schema/g,N.code);if(X+=" "+I+" ",w)X+=" if ("+S+") { "}else Z=N.$async===!0||W.async&&N.$async!==!1,U=N.code}if(U){var L=L||[];if(L.push(X),X="",W.opts.passContext)X+=" "+U+".call(this, ";else X+=" "+U+"( ";if(X+=" "+_+", (dataPath || '')",W.errorPath!='""')X+=" + "+W.errorPath;var P=K?"data"+(K-1||""):"parentData",g=K?W.dataPathArr[K]:"parentDataProperty";X+=" , "+P+" , "+g+", rootData) ";var x=X;if(X=L.pop(),Z){if(!W.async)throw new Error("async schema referenced by sync schema");if(w)X+=" var "+j+"; ";if(X+=" try { await "+x+"; ",w)X+=" "+j+" = true; ";if(X+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",w)X+=" "+j+" = false; ";if(X+=" } ",w)X+=" if ("+j+") { "}else if(X+=" if (!"+x+") { if (vErrors === null) vErrors = "+U+".errors; else vErrors = vErrors.concat("+U+".errors); errors = vErrors.length; } ",w)X+=" else { "}return X}}),j6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.schema[z],K=W.schemaPath+W.util.getProperty(z),H=W.errSchemaPath+"/"+z,O=!W.opts.allErrors,w=W.util.copy(W),_="";w.level++;var j="valid"+w.level,Z=w.baseId,U=!0,N=B;if(N){var V,L=-1,D=N.length-1;while(L0||V===!1:W.util.schemaHasRules(V,W.RULES.all)){if(U=!1,w.schema=V,w.schemaPath=K+"["+L+"]",w.errSchemaPath=H+"/"+L,X+=" "+W.validate(w)+" ",w.baseId=Z,O)X+=" if ("+j+") { ",_+="}"}}if(O)if(U)X+=" if (true) { ";else X+=" "+_.slice(0,-1)+" ";return X}}),A6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="valid"+B,U="errs__"+B,N=W.util.copy(W),V="";N.level++;var L="valid"+N.level,D=H.every(function(b){return W.opts.strictKeywords?typeof b=="object"&&Object.keys(b).length>0||b===!1:W.util.schemaHasRules(b,W.RULES.all)});if(D){var y=N.baseId;X+=" var "+U+" = errors; var "+Z+" = false; ";var S=W.compositeRule;W.compositeRule=N.compositeRule=!0;var I=H;if(I){var P,g=-1,x=I.length-1;while(g{Y.exports=function J(W,z,F){var X=" ",B=W.schema[z],K=W.errSchemaPath+"/"+z,H=!W.opts.allErrors,O=W.util.toQuotedString(B);if(W.opts.$comment===!0)X+=" console.log("+O+");";else if(typeof W.opts.$comment=="function")X+=" self._opts.$comment("+O+", "+W.util.toQuotedString(K)+", validate.root.schema);";return X}}),O6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="valid"+B,U=W.opts.$data&&H&&H.$data,N;if(U)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",N="schema"+B;else N=H;if(!U)X+=" var schema"+B+" = validate.schema"+O+";";X+="var "+Z+" = equal("+j+", schema"+B+"); if (!"+Z+") { ";var V=V||[];if(V.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'const' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { allowedValue: schema"+B+" } ",W.opts.messages!==!1)X+=" , message: 'should be equal to constant' ";if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";var L=X;if(X=V.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+L+"]); ";else X+=" validate.errors = ["+L+"]; return false; ";else X+=" var err = "+L+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+=" }",_)X+=" else { ";return X}}),Z6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="valid"+B,U="errs__"+B,N=W.util.copy(W),V="";N.level++;var L="valid"+N.level,D="i"+B,y=N.dataLevel=W.dataLevel+1,S="data"+y,I=W.baseId,P=W.opts.strictKeywords?typeof H=="object"&&Object.keys(H).length>0||H===!1:W.util.schemaHasRules(H,W.RULES.all);if(X+="var "+U+" = errors;var "+Z+";",P){var g=W.compositeRule;W.compositeRule=N.compositeRule=!0,N.schema=H,N.schemaPath=O,N.errSchemaPath=w,X+=" var "+L+" = false; for (var "+D+" = 0; "+D+" < "+j+".length; "+D+"++) { ",N.errorPath=W.util.getPathExpr(W.errorPath,D,W.opts.jsonPointers,!0);var x=j+"["+D+"]";N.dataPathArr[y]=D;var b=W.validate(N);if(N.baseId=I,W.util.varOccurences(b,S)<2)X+=" "+W.util.varReplace(b,S,x)+" ";else X+=" var "+S+" = "+x+"; "+b+" ";X+=" if ("+L+") break; } ",W.compositeRule=N.compositeRule=g,X+=" "+V+" if (!"+L+") {"}else X+=" if ("+j+".length == 0) {";var k=k||[];if(k.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: {} ",W.opts.messages!==!1)X+=" , message: 'should contain a valid item' ";if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";var R=X;if(X=k.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+R+"]); ";else X+=" validate.errors = ["+R+"]; return false; ";else X+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+=" } else { ",P)X+=" errors = "+U+"; if (vErrors !== null) { if ("+U+") vErrors.length = "+U+"; else vErrors = null; } ";if(W.opts.allErrors)X+=" } ";return X}}),w6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="errs__"+B,U=W.util.copy(W),N="";U.level++;var V="valid"+U.level,L={},D={},y=W.opts.ownProperties;for(g in H){if(g=="__proto__")continue;var S=H[g],I=Array.isArray(S)?D:L;I[g]=S}X+="var "+Z+" = errors;";var P=W.errorPath;X+="var missing"+B+";";for(var g in D)if(I=D[g],I.length){if(X+=" if ( "+j+W.util.getProperty(g)+" !== undefined ",y)X+=" && Object.prototype.hasOwnProperty.call("+j+", '"+W.util.escapeQuotes(g)+"') ";if(_){X+=" && ( ";var x=I;if(x){var b,k=-1,R=x.length-1;while(k0||S===!1:W.util.schemaHasRules(S,W.RULES.all)){if(X+=" "+V+" = true; if ( "+j+W.util.getProperty(g)+" !== undefined ",y)X+=" && Object.prototype.hasOwnProperty.call("+j+", '"+W.util.escapeQuotes(g)+"') ";if(X+=") { ",U.schema=S,U.schemaPath=O+W.util.getProperty(g),U.errSchemaPath=w+"/"+W.util.escapeFragment(g),X+=" "+W.validate(U)+" ",U.baseId=z0,X+=" } ",_)X+=" if ("+V+") { ",N+="}"}}if(_)X+=" "+N+" if ("+Z+" == errors) {";return X}}),R6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="valid"+B,U=W.opts.$data&&H&&H.$data,N;if(U)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",N="schema"+B;else N=H;var V="i"+B,L="schema"+B;if(!U)X+=" var "+L+" = validate.schema"+O+";";if(X+="var "+Z+";",U)X+=" if (schema"+B+" === undefined) "+Z+" = true; else if (!Array.isArray(schema"+B+")) "+Z+" = false; else {";if(X+=""+Z+" = false;for (var "+V+"=0; "+V+"<"+L+".length; "+V+"++) if (equal("+j+", "+L+"["+V+"])) { "+Z+" = true; break; }",U)X+=" } ";X+=" if (!"+Z+") { ";var D=D||[];if(D.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { allowedValues: schema"+B+" } ",W.opts.messages!==!1)X+=" , message: 'should be equal to one of the allowed values' ";if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";var y=X;if(X=D.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+y+"]); ";else X+=" validate.errors = ["+y+"]; return false; ";else X+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+=" }",_)X+=" else { ";return X}}),D6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||"");if(W.opts.format===!1){if(_)X+=" if (true) { ";return X}var Z=W.opts.$data&&H&&H.$data,U;if(Z)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",U="schema"+B;else U=H;var N=W.opts.unknownFormats,V=Array.isArray(N);if(Z){var L="format"+B,D="isObject"+B,y="formatType"+B;if(X+=" var "+L+" = formats["+U+"]; var "+D+" = typeof "+L+" == 'object' && !("+L+" instanceof RegExp) && "+L+".validate; var "+y+" = "+D+" && "+L+".type || 'string'; if ("+D+") { ",W.async)X+=" var async"+B+" = "+L+".async; ";if(X+=" "+L+" = "+L+".validate; } if ( ",Z)X+=" ("+U+" !== undefined && typeof "+U+" != 'string') || ";if(X+=" (",N!="ignore"){if(X+=" ("+U+" && !"+L+" ",V)X+=" && self._opts.unknownFormats.indexOf("+U+") == -1 ";X+=") || "}if(X+=" ("+L+" && "+y+" == '"+F+"' && !(typeof "+L+" == 'function' ? ",W.async)X+=" (async"+B+" ? await "+L+"("+j+") : "+L+"("+j+")) ";else X+=" "+L+"("+j+") ";X+=" : "+L+".test("+j+"))))) {"}else{var L=W.formats[H];if(!L)if(N=="ignore"){if(W.logger.warn('unknown format "'+H+'" ignored in schema at path "'+W.errSchemaPath+'"'),_)X+=" if (true) { ";return X}else if(V&&N.indexOf(H)>=0){if(_)X+=" if (true) { ";return X}else throw new Error('unknown format "'+H+'" is used in schema at path "'+W.errSchemaPath+'"');var D=typeof L=="object"&&!(L instanceof RegExp)&&L.validate,y=D&&L.type||"string";if(D){var S=L.async===!0;L=L.validate}if(y!=F){if(_)X+=" if (true) { ";return X}if(S){if(!W.async)throw new Error("async format in sync schema");var I="formats"+W.util.getProperty(H)+".validate";X+=" if (!(await "+I+"("+j+"))) { "}else{X+=" if (! ";var I="formats"+W.util.getProperty(H);if(D)I+=".validate";if(typeof L=="function")X+=" "+I+"("+j+") ";else X+=" "+I+".test("+j+") ";X+=") { "}}var P=P||[];if(P.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'format' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { format: ",Z)X+=""+U;else X+=""+W.util.toQuotedString(H);if(X+=" } ",W.opts.messages!==!1){if(X+=` , message: 'should match format "`,Z)X+="' + "+U+" + '";else X+=""+W.util.escapeQuotes(H);X+=`"' `}if(W.opts.verbose){if(X+=" , schema: ",Z)X+="validate.schema"+O;else X+=""+W.util.toQuotedString(H);X+=" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" "}X+=" } "}else X+=" {} ";var g=X;if(X=P.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+g+"]); ";else X+=" validate.errors = ["+g+"]; return false; ";else X+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+=" } ",_)X+=" else { ";return X}}),I6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="valid"+B,U="errs__"+B,N=W.util.copy(W);N.level++;var V="valid"+N.level,L=W.schema.then,D=W.schema.else,y=L!==void 0&&(W.opts.strictKeywords?typeof L=="object"&&Object.keys(L).length>0||L===!1:W.util.schemaHasRules(L,W.RULES.all)),S=D!==void 0&&(W.opts.strictKeywords?typeof D=="object"&&Object.keys(D).length>0||D===!1:W.util.schemaHasRules(D,W.RULES.all)),I=N.baseId;if(y||S){var P;N.createErrors=!1,N.schema=H,N.schemaPath=O,N.errSchemaPath=w,X+=" var "+U+" = errors; var "+Z+" = true; ";var g=W.compositeRule;if(W.compositeRule=N.compositeRule=!0,X+=" "+W.validate(N)+" ",N.baseId=I,N.createErrors=!0,X+=" errors = "+U+"; if (vErrors !== null) { if ("+U+") vErrors.length = "+U+"; else vErrors = null; } ",W.compositeRule=N.compositeRule=g,y){if(X+=" if ("+V+") { ",N.schema=W.schema.then,N.schemaPath=W.schemaPath+".then",N.errSchemaPath=W.errSchemaPath+"/then",X+=" "+W.validate(N)+" ",N.baseId=I,X+=" "+Z+" = "+V+"; ",y&&S)P="ifClause"+B,X+=" var "+P+" = 'then'; ";else P="'then'";if(X+=" } ",S)X+=" else { "}else X+=" if (!"+V+") { ";if(S){if(N.schema=W.schema.else,N.schemaPath=W.schemaPath+".else",N.errSchemaPath=W.errSchemaPath+"/else",X+=" "+W.validate(N)+" ",N.baseId=I,X+=" "+Z+" = "+V+"; ",y&&S)P="ifClause"+B,X+=" var "+P+" = 'else'; ";else P="'else'";X+=" } "}if(X+=" if (!"+Z+") { var err = ",W.createErrors!==!1){if(X+=" { keyword: 'if' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { failingKeyword: "+P+" } ",W.opts.messages!==!1)X+=` , message: 'should match "' + `+P+` + '" schema' `;if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";if(X+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(vErrors); ";else X+=" validate.errors = vErrors; return false; ";if(X+=" } ",_)X+=" else { "}else if(_)X+=" if (true) { ";return X}}),C6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="valid"+B,U="errs__"+B,N=W.util.copy(W),V="";N.level++;var L="valid"+N.level,D="i"+B,y=N.dataLevel=W.dataLevel+1,S="data"+y,I=W.baseId;if(X+="var "+U+" = errors;var "+Z+";",Array.isArray(H)){var P=W.schema.additionalItems;if(P===!1){X+=" "+Z+" = "+j+".length <= "+H.length+"; ";var g=w;w=W.errSchemaPath+"/additionalItems",X+=" if (!"+Z+") { ";var x=x||[];if(x.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { limit: "+H.length+" } ",W.opts.messages!==!1)X+=" , message: 'should NOT have more than "+H.length+" items' ";if(W.opts.verbose)X+=" , schema: false , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";var b=X;if(X=x.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+b+"]); ";else X+=" validate.errors = ["+b+"]; return false; ";else X+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+=" } ",w=g,_)V+="}",X+=" else { "}var k=H;if(k){var R,T=-1,f=k.length-1;while(T0||R===!1:W.util.schemaHasRules(R,W.RULES.all)){X+=" "+L+" = true; if ("+j+".length > "+T+") { ";var $=j+"["+T+"]";N.schema=R,N.schemaPath=O+"["+T+"]",N.errSchemaPath=w+"/"+T,N.errorPath=W.util.getPathExpr(W.errorPath,T,W.opts.jsonPointers,!0),N.dataPathArr[y]=T;var p=W.validate(N);if(N.baseId=I,W.util.varOccurences(p,S)<2)X+=" "+W.util.varReplace(p,S,$)+" ";else X+=" var "+S+" = "+$+"; "+p+" ";if(X+=" } ",_)X+=" if ("+L+") { ",V+="}"}}if(typeof P=="object"&&(W.opts.strictKeywords?typeof P=="object"&&Object.keys(P).length>0||P===!1:W.util.schemaHasRules(P,W.RULES.all))){N.schema=P,N.schemaPath=W.schemaPath+".additionalItems",N.errSchemaPath=W.errSchemaPath+"/additionalItems",X+=" "+L+" = true; if ("+j+".length > "+H.length+") { for (var "+D+" = "+H.length+"; "+D+" < "+j+".length; "+D+"++) { ",N.errorPath=W.util.getPathExpr(W.errorPath,D,W.opts.jsonPointers,!0);var $=j+"["+D+"]";N.dataPathArr[y]=D;var p=W.validate(N);if(N.baseId=I,W.util.varOccurences(p,S)<2)X+=" "+W.util.varReplace(p,S,$)+" ";else X+=" var "+S+" = "+$+"; "+p+" ";if(_)X+=" if (!"+L+") break; ";if(X+=" } } ",_)X+=" if ("+L+") { ",V+="}"}}else if(W.opts.strictKeywords?typeof H=="object"&&Object.keys(H).length>0||H===!1:W.util.schemaHasRules(H,W.RULES.all)){N.schema=H,N.schemaPath=O,N.errSchemaPath=w,X+=" for (var "+D+" = 0; "+D+" < "+j+".length; "+D+"++) { ",N.errorPath=W.util.getPathExpr(W.errorPath,D,W.opts.jsonPointers,!0);var $=j+"["+D+"]";N.dataPathArr[y]=D;var p=W.validate(N);if(N.baseId=I,W.util.varOccurences(p,S)<2)X+=" "+W.util.varReplace(p,S,$)+" ";else X+=" var "+S+" = "+$+"; "+p+" ";if(_)X+=" if (!"+L+") break; ";X+=" }"}if(_)X+=" "+V+" if ("+U+" == errors) {";return X}}),R8=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,I,j="data"+(K||""),Z=W.opts.$data&&H&&H.$data,U;if(Z)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",U="schema"+B;else U=H;var N=z=="maximum",V=N?"exclusiveMaximum":"exclusiveMinimum",L=W.schema[V],D=W.opts.$data&&L&&L.$data,y=N?"<":">",S=N?">":"<",I=void 0;if(!(Z||typeof H=="number"||H===void 0))throw new Error(z+" must be number");if(!(D||L===void 0||typeof L=="number"||typeof L=="boolean"))throw new Error(V+" must be number or boolean");if(D){var P=W.util.getData(L.$data,K,W.dataPathArr),g="exclusive"+B,x="exclType"+B,b="exclIsNumber"+B,k="op"+B,R="' + "+k+" + '";X+=" var schemaExcl"+B+" = "+P+"; ",P="schemaExcl"+B,X+=" var "+g+"; var "+x+" = typeof "+P+"; if ("+x+" != 'boolean' && "+x+" != 'undefined' && "+x+" != 'number') { ";var I=V,T=T||[];if(T.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: '"+(I||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: {} ",W.opts.messages!==!1)X+=" , message: '"+V+" should be boolean' ";if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";var f=X;if(X=T.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+f+"]); ";else X+=" validate.errors = ["+f+"]; return false; ";else X+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+=" } else if ( ",Z)X+=" ("+U+" !== undefined && typeof "+U+" != 'number') || ";if(X+=" "+x+" == 'number' ? ( ("+g+" = "+U+" === undefined || "+P+" "+y+"= "+U+") ? "+j+" "+S+"= "+P+" : "+j+" "+S+" "+U+" ) : ( ("+g+" = "+P+" === true) ? "+j+" "+S+"= "+U+" : "+j+" "+S+" "+U+" ) || "+j+" !== "+j+") { var op"+B+" = "+g+" ? '"+y+"' : '"+y+"='; ",H===void 0)I=V,w=W.errSchemaPath+"/"+V,U=P,Z=D}else{var b=typeof L=="number",R=y;if(b&&Z){var k="'"+R+"'";if(X+=" if ( ",Z)X+=" ("+U+" !== undefined && typeof "+U+" != 'number') || ";X+=" ( "+U+" === undefined || "+L+" "+y+"= "+U+" ? "+j+" "+S+"= "+L+" : "+j+" "+S+" "+U+" ) || "+j+" !== "+j+") { "}else{if(b&&H===void 0)g=!0,I=V,w=W.errSchemaPath+"/"+V,U=L,S+="=";else{if(b)U=Math[N?"min":"max"](L,H);if(L===(b?U:!0))g=!0,I=V,w=W.errSchemaPath+"/"+V,S+="=";else g=!1,R+="="}var k="'"+R+"'";if(X+=" if ( ",Z)X+=" ("+U+" !== undefined && typeof "+U+" != 'number') || ";X+=" "+j+" "+S+" "+U+" || "+j+" !== "+j+") { "}}I=I||z;var T=T||[];if(T.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: '"+(I||"_limit")+"' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { comparison: "+k+", limit: "+U+", exclusive: "+g+" } ",W.opts.messages!==!1)if(X+=" , message: 'should be "+R+" ",Z)X+="' + "+U;else X+=""+U+"'";if(W.opts.verbose){if(X+=" , schema: ",Z)X+="validate.schema"+O;else X+=""+H;X+=" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" "}X+=" } "}else X+=" {} ";var f=X;if(X=T.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+f+"]); ";else X+=" validate.errors = ["+f+"]; return false; ";else X+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+=" } ",_)X+=" else { ";return X}}),D8=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,V,j="data"+(K||""),Z=W.opts.$data&&H&&H.$data,U;if(Z)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",U="schema"+B;else U=H;if(!(Z||typeof H=="number"))throw new Error(z+" must be number");var N=z=="maxItems"?">":"<";if(X+="if ( ",Z)X+=" ("+U+" !== undefined && typeof "+U+" != 'number') || ";X+=" "+j+".length "+N+" "+U+") { ";var V=z,L=L||[];if(L.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: '"+(V||"_limitItems")+"' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { limit: "+U+" } ",W.opts.messages!==!1){if(X+=" , message: 'should NOT have ",z=="maxItems")X+="more";else X+="fewer";if(X+=" than ",Z)X+="' + "+U+" + '";else X+=""+H;X+=" items' "}if(W.opts.verbose){if(X+=" , schema: ",Z)X+="validate.schema"+O;else X+=""+H;X+=" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" "}X+=" } "}else X+=" {} ";var D=X;if(X=L.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+D+"]); ";else X+=" validate.errors = ["+D+"]; return false; ";else X+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+="} ",_)X+=" else { ";return X}}),I8=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,V,j="data"+(K||""),Z=W.opts.$data&&H&&H.$data,U;if(Z)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",U="schema"+B;else U=H;if(!(Z||typeof H=="number"))throw new Error(z+" must be number");var N=z=="maxLength"?">":"<";if(X+="if ( ",Z)X+=" ("+U+" !== undefined && typeof "+U+" != 'number') || ";if(W.opts.unicode===!1)X+=" "+j+".length ";else X+=" ucs2length("+j+") ";X+=" "+N+" "+U+") { ";var V=z,L=L||[];if(L.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: '"+(V||"_limitLength")+"' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { limit: "+U+" } ",W.opts.messages!==!1){if(X+=" , message: 'should NOT be ",z=="maxLength")X+="longer";else X+="shorter";if(X+=" than ",Z)X+="' + "+U+" + '";else X+=""+H;X+=" characters' "}if(W.opts.verbose){if(X+=" , schema: ",Z)X+="validate.schema"+O;else X+=""+H;X+=" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" "}X+=" } "}else X+=" {} ";var D=X;if(X=L.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+D+"]); ";else X+=" validate.errors = ["+D+"]; return false; ";else X+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+="} ",_)X+=" else { ";return X}}),C8=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,V,j="data"+(K||""),Z=W.opts.$data&&H&&H.$data,U;if(Z)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",U="schema"+B;else U=H;if(!(Z||typeof H=="number"))throw new Error(z+" must be number");var N=z=="maxProperties"?">":"<";if(X+="if ( ",Z)X+=" ("+U+" !== undefined && typeof "+U+" != 'number') || ";X+=" Object.keys("+j+").length "+N+" "+U+") { ";var V=z,L=L||[];if(L.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: '"+(V||"_limitProperties")+"' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { limit: "+U+" } ",W.opts.messages!==!1){if(X+=" , message: 'should NOT have ",z=="maxProperties")X+="more";else X+="fewer";if(X+=" than ",Z)X+="' + "+U+" + '";else X+=""+H;X+=" properties' "}if(W.opts.verbose){if(X+=" , schema: ",Z)X+="validate.schema"+O;else X+=""+H;X+=" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" "}X+=" } "}else X+=" {} ";var D=X;if(X=L.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+D+"]); ";else X+=" validate.errors = ["+D+"]; return false; ";else X+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+="} ",_)X+=" else { ";return X}}),_6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z=W.opts.$data&&H&&H.$data,U;if(Z)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",U="schema"+B;else U=H;if(!(Z||typeof H=="number"))throw new Error(z+" must be number");if(X+="var division"+B+";if (",Z)X+=" "+U+" !== undefined && ( typeof "+U+" != 'number' || ";if(X+=" (division"+B+" = "+j+" / "+U+", ",W.opts.multipleOfPrecision)X+=" Math.abs(Math.round(division"+B+") - division"+B+") > 1e-"+W.opts.multipleOfPrecision+" ";else X+=" division"+B+" !== parseInt(division"+B+") ";if(X+=" ) ",Z)X+=" ) ";X+=" ) { ";var N=N||[];if(N.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { multipleOf: "+U+" } ",W.opts.messages!==!1)if(X+=" , message: 'should be multiple of ",Z)X+="' + "+U;else X+=""+U+"'";if(W.opts.verbose){if(X+=" , schema: ",Z)X+="validate.schema"+O;else X+=""+H;X+=" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" "}X+=" } "}else X+=" {} ";var V=X;if(X=N.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+V+"]); ";else X+=" validate.errors = ["+V+"]; return false; ";else X+=" var err = "+V+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+="} ",_)X+=" else { ";return X}}),P6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="errs__"+B,U=W.util.copy(W);U.level++;var N="valid"+U.level;if(W.opts.strictKeywords?typeof H=="object"&&Object.keys(H).length>0||H===!1:W.util.schemaHasRules(H,W.RULES.all)){U.schema=H,U.schemaPath=O,U.errSchemaPath=w,X+=" var "+Z+" = errors; ";var V=W.compositeRule;W.compositeRule=U.compositeRule=!0,U.createErrors=!1;var L;if(U.opts.allErrors)L=U.opts.allErrors,U.opts.allErrors=!1;if(X+=" "+W.validate(U)+" ",U.createErrors=!0,L)U.opts.allErrors=L;W.compositeRule=U.compositeRule=V,X+=" if ("+N+") { ";var D=D||[];if(D.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'not' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: {} ",W.opts.messages!==!1)X+=" , message: 'should NOT be valid' ";if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";var y=X;if(X=D.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+y+"]); ";else X+=" validate.errors = ["+y+"]; return false; ";else X+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+=" } else { errors = "+Z+"; if (vErrors !== null) { if ("+Z+") vErrors.length = "+Z+"; else vErrors = null; } ",W.opts.allErrors)X+=" } "}else{if(X+=" var err = ",W.createErrors!==!1){if(X+=" { keyword: 'not' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: {} ",W.opts.messages!==!1)X+=" , message: 'should NOT be valid' ";if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";if(X+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",_)X+=" if (false) { "}return X}}),T6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="valid"+B,U="errs__"+B,N=W.util.copy(W),V="";N.level++;var L="valid"+N.level,D=N.baseId,y="prevValid"+B,S="passingSchemas"+B;X+="var "+U+" = errors , "+y+" = false , "+Z+" = false , "+S+" = null; ";var I=W.compositeRule;W.compositeRule=N.compositeRule=!0;var P=H;if(P){var g,x=-1,b=P.length-1;while(x0||g===!1:W.util.schemaHasRules(g,W.RULES.all))N.schema=g,N.schemaPath=O+"["+x+"]",N.errSchemaPath=w+"/"+x,X+=" "+W.validate(N)+" ",N.baseId=D;else X+=" var "+L+" = true; ";if(x)X+=" if ("+L+" && "+y+") { "+Z+" = false; "+S+" = ["+S+", "+x+"]; } else { ",V+="}";X+=" if ("+L+") { "+Z+" = "+y+" = true; "+S+" = "+x+"; }"}}if(W.compositeRule=N.compositeRule=I,X+=""+V+"if (!"+Z+") { var err = ",W.createErrors!==!1){if(X+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { passingSchemas: "+S+" } ",W.opts.messages!==!1)X+=" , message: 'should match exactly one schema in oneOf' ";if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";if(X+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(vErrors); ";else X+=" validate.errors = vErrors; return false; ";if(X+="} else { errors = "+U+"; if (vErrors !== null) { if ("+U+") vErrors.length = "+U+"; else vErrors = null; }",W.opts.allErrors)X+=" } ";return X}}),E6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z=W.opts.$data&&H&&H.$data,U;if(Z)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",U="schema"+B;else U=H;var N=Z?"(new RegExp("+U+"))":W.usePattern(H);if(X+="if ( ",Z)X+=" ("+U+" !== undefined && typeof "+U+" != 'string') || ";X+=" !"+N+".test("+j+") ) { ";var V=V||[];if(V.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { pattern: ",Z)X+=""+U;else X+=""+W.util.toQuotedString(H);if(X+=" } ",W.opts.messages!==!1){if(X+=` , message: 'should match pattern "`,Z)X+="' + "+U+" + '";else X+=""+W.util.escapeQuotes(H);X+=`"' `}if(W.opts.verbose){if(X+=" , schema: ",Z)X+="validate.schema"+O;else X+=""+W.util.toQuotedString(H);X+=" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" "}X+=" } "}else X+=" {} ";var L=X;if(X=V.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+L+"]); ";else X+=" validate.errors = ["+L+"]; return false; ";else X+=" var err = "+L+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+="} ",_)X+=" else { ";return X}}),b6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="errs__"+B,U=W.util.copy(W),N="";U.level++;var V="valid"+U.level,L="key"+B,D="idx"+B,y=U.dataLevel=W.dataLevel+1,S="data"+y,I="dataProperties"+B,P=Object.keys(H||{}).filter(J0),g=W.schema.patternProperties||{},x=Object.keys(g).filter(J0),b=W.schema.additionalProperties,k=P.length||x.length,R=b===!1,T=typeof b=="object"&&Object.keys(b).length,f=W.opts.removeAdditional,$=R||T||f,p=W.opts.ownProperties,d=W.baseId,X0=W.schema.required;if(X0&&!(W.opts.$data&&X0.$data)&&X0.length8)X+=" || validate.schema"+O+".hasOwnProperty("+L+") ";else{var a=P;if(a){var z0,g0=-1,y0=a.length-1;while(g00||E0===!1:W.util.schemaHasRules(E0,W.RULES.all)){var h0=W.util.getProperty(z0),q0=j+h0,D0=w0&&E0.default!==void 0;U.schema=E0,U.schemaPath=O+h0,U.errSchemaPath=w+"/"+W.util.escapeFragment(z0),U.errorPath=W.util.getPath(W.errorPath,z0,W.opts.jsonPointers),U.dataPathArr[y]=W.util.toQuotedString(z0);var Q0=W.validate(U);if(U.baseId=d,W.util.varOccurences(Q0,S)<2){Q0=W.util.varReplace(Q0,S,q0);var v0=q0}else{var v0=S;X+=" var "+S+" = "+q0+"; "}if(D0)X+=" "+Q0+" ";else{if(s&&s[z0]){if(X+=" if ( "+v0+" === undefined ",p)X+=" || ! Object.prototype.hasOwnProperty.call("+j+", '"+W.util.escapeQuotes(z0)+"') ";X+=") { "+V+" = false; ";var h=W.errorPath,G0=w,n0=W.util.escapeQuotes(z0);if(W.opts._errorDataPathProperty)W.errorPath=W.util.getPath(h,z0,W.opts.jsonPointers);w=W.errSchemaPath+"/required";var m=m||[];if(m.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'required' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { missingProperty: '"+n0+"' } ",W.opts.messages!==!1){if(X+=" , message: '",W.opts._errorDataPathProperty)X+="is a required property";else X+="should have required property \\'"+n0+"\\'";X+="' "}if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";var u=X;if(X=m.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+u+"]); ";else X+=" validate.errors = ["+u+"]; return false; ";else X+=" var err = "+u+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";w=G0,W.errorPath=h,X+=" } else { "}else if(_){if(X+=" if ( "+v0+" === undefined ",p)X+=" || ! Object.prototype.hasOwnProperty.call("+j+", '"+W.util.escapeQuotes(z0)+"') ";X+=") { "+V+" = true; } else { "}else{if(X+=" if ("+v0+" !== undefined ",p)X+=" && Object.prototype.hasOwnProperty.call("+j+", '"+W.util.escapeQuotes(z0)+"') ";X+=" ) { "}X+=" "+Q0+" } "}}if(_)X+=" if ("+V+") { ",N+="}"}}}if(x.length){var l0=x;if(l0){var Z0,R9=-1,$9=l0.length-1;while(R9<$9){Z0=l0[R9+=1];var E0=g[Z0];if(W.opts.strictKeywords?typeof E0=="object"&&Object.keys(E0).length>0||E0===!1:W.util.schemaHasRules(E0,W.RULES.all)){if(U.schema=E0,U.schemaPath=W.schemaPath+".patternProperties"+W.util.getProperty(Z0),U.errSchemaPath=W.errSchemaPath+"/patternProperties/"+W.util.escapeFragment(Z0),p)X+=" "+I+" = "+I+" || Object.keys("+j+"); for (var "+D+"=0; "+D+"<"+I+".length; "+D+"++) { var "+L+" = "+I+"["+D+"]; ";else X+=" for (var "+L+" in "+j+") { ";X+=" if ("+W.usePattern(Z0)+".test("+L+")) { ",U.errorPath=W.util.getPathExpr(W.errorPath,L,W.opts.jsonPointers);var q0=j+"["+L+"]";U.dataPathArr[y]=L;var Q0=W.validate(U);if(U.baseId=d,W.util.varOccurences(Q0,S)<2)X+=" "+W.util.varReplace(Q0,S,q0)+" ";else X+=" var "+S+" = "+q0+"; "+Q0+" ";if(_)X+=" if (!"+V+") break; ";if(X+=" } ",_)X+=" else "+V+" = true; ";if(X+=" } ",_)X+=" if ("+V+") { ",N+="}"}}}}if(_)X+=" "+N+" if ("+Z+" == errors) {";return X}}),S6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="errs__"+B,U=W.util.copy(W),N="";U.level++;var V="valid"+U.level;if(X+="var "+Z+" = errors;",W.opts.strictKeywords?typeof H=="object"&&Object.keys(H).length>0||H===!1:W.util.schemaHasRules(H,W.RULES.all)){U.schema=H,U.schemaPath=O,U.errSchemaPath=w;var L="key"+B,D="idx"+B,y="i"+B,S="' + "+L+" + '",I=U.dataLevel=W.dataLevel+1,P="data"+I,g="dataProperties"+B,x=W.opts.ownProperties,b=W.baseId;if(x)X+=" var "+g+" = undefined; ";if(x)X+=" "+g+" = "+g+" || Object.keys("+j+"); for (var "+D+"=0; "+D+"<"+g+".length; "+D+"++) { var "+L+" = "+g+"["+D+"]; ";else X+=" for (var "+L+" in "+j+") { ";X+=" var startErrs"+B+" = errors; ";var k=L,R=W.compositeRule;W.compositeRule=U.compositeRule=!0;var T=W.validate(U);if(U.baseId=b,W.util.varOccurences(T,P)<2)X+=" "+W.util.varReplace(T,P,k)+" ";else X+=" var "+P+" = "+k+"; "+T+" ";if(W.compositeRule=U.compositeRule=R,X+=" if (!"+V+") { for (var "+y+"=startErrs"+B+"; "+y+"{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="valid"+B,U=W.opts.$data&&H&&H.$data,N;if(U)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",N="schema"+B;else N=H;var V="schema"+B;if(!U)if(H.length0||P===!1:W.util.schemaHasRules(P,W.RULES.all))))L[L.length]=y}}}else var L=H;if(U||L.length){var g=W.errorPath,x=U||L.length>=W.opts.loopRequired,b=W.opts.ownProperties;if(_)if(X+=" var missing"+B+"; ",x){if(!U)X+=" var "+V+" = validate.schema"+O+"; ";var k="i"+B,R="schema"+B+"["+k+"]",T="' + "+R+" + '";if(W.opts._errorDataPathProperty)W.errorPath=W.util.getPathExpr(g,R,W.opts.jsonPointers);if(X+=" var "+Z+" = true; ",U)X+=" if (schema"+B+" === undefined) "+Z+" = true; else if (!Array.isArray(schema"+B+")) "+Z+" = false; else {";if(X+=" for (var "+k+" = 0; "+k+" < "+V+".length; "+k+"++) { "+Z+" = "+j+"["+V+"["+k+"]] !== undefined ",b)X+=" && Object.prototype.hasOwnProperty.call("+j+", "+V+"["+k+"]) ";if(X+="; if (!"+Z+") break; } ",U)X+=" } ";X+=" if (!"+Z+") { ";var f=f||[];if(f.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'required' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { missingProperty: '"+T+"' } ",W.opts.messages!==!1){if(X+=" , message: '",W.opts._errorDataPathProperty)X+="is a required property";else X+="should have required property \\'"+T+"\\'";X+="' "}if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" ";X+=" } "}else X+=" {} ";var $=X;if(X=f.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+$+"]); ";else X+=" validate.errors = ["+$+"]; return false; ";else X+=" var err = "+$+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";X+=" } else { "}else{X+=" if ( ";var p=L;if(p){var d,k=-1,X0=p.length-1;while(k{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j="data"+(K||""),Z="valid"+B,U=W.opts.$data&&H&&H.$data,N;if(U)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",N="schema"+B;else N=H;if((H||U)&&W.opts.uniqueItems!==!1){if(U)X+=" var "+Z+"; if ("+N+" === false || "+N+" === undefined) "+Z+" = true; else if (typeof "+N+" != 'boolean') "+Z+" = false; else { ";X+=" var i = "+j+".length , "+Z+" = true , j; if (i > 1) { ";var V=W.schema.items&&W.schema.items.type,L=Array.isArray(V);if(!V||V=="object"||V=="array"||L&&(V.indexOf("object")>=0||V.indexOf("array")>=0))X+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+j+"[i], "+j+"[j])) { "+Z+" = false; break outer; } } } ";else{X+=" var itemIndices = {}, item; for (;i--;) { var item = "+j+"[i]; ";var D="checkDataType"+(L?"s":"");if(X+=" if ("+W.util[D](V,"item",W.opts.strictNumbers,!0)+") continue; ",L)X+=` if (typeof item == 'string') item = '"' + item; `;X+=" if (typeof itemIndices[item] == 'number') { "+Z+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}if(X+=" } ",U)X+=" } ";X+=" if (!"+Z+") { ";var y=y||[];if(y.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { i: i, j: j } ",W.opts.messages!==!1)X+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' ";if(W.opts.verbose){if(X+=" , schema: ",U)X+="validate.schema"+O;else X+=""+H;X+=" , parentSchema: validate.schema"+W.schemaPath+" , data: "+j+" "}X+=" } "}else X+=" {} ";var S=X;if(X=y.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+S+"]); ";else X+=" validate.errors = ["+S+"]; return false; ";else X+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(X+=" } ",_)X+=" else { "}else if(_)X+=" if (true) { ";return X}}),k6=Y0((Q,Y)=>{Y.exports={$ref:L6(),allOf:j6(),anyOf:A6(),$comment:V6(),const:O6(),contains:Z6(),dependencies:w6(),enum:R6(),format:D6(),if:I6(),items:C6(),maximum:R8(),minimum:R8(),maxItems:D8(),minItems:D8(),maxLength:I8(),minLength:I8(),maxProperties:C8(),minProperties:C8(),multipleOf:_6(),not:P6(),oneOf:T6(),pattern:E6(),properties:b6(),propertyNames:S6(),required:v6(),uniqueItems:g6(),validate:m8()}}),x6=Y0((Q,Y)=>{var J=k6(),W=t1().toHash;Y.exports=function z(){var F=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],X=["type","$comment"],B=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],K=["number","integer","string","array","object","boolean","null"];return F.all=W(X),F.types=W(K),F.forEach(function(H){if(H.rules=H.rules.map(function(O){var w;if(typeof O=="object"){var _=Object.keys(O)[0];w=O[_],O=_,w.forEach(function(Z){X.push(Z),F.all[Z]=!0})}X.push(O);var j=F.all[O]={keyword:O,code:J[O],implements:w};return j}),F.all.$comment={keyword:"$comment",code:J.$comment},H.type)F.types[H.type]=H}),F.keywords=W(X.concat(B)),F.custom={},F}}),y6=Y0((Q,Y)=>{var J=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];Y.exports=function(W,z){for(var F=0;F{var J=Q8().MissingRef;Y.exports=W;function W(z,F,X){var B=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");if(typeof F=="function")X=F,F=void 0;var K=H(z).then(function(){var w=B._addSchema(z,void 0,F);return w.validate||O(w)});if(X)K.then(function(w){X(null,w)},X);return K;function H(w){var _=w.$schema;return _&&!B.getSchema(_)?W.call(B,{$ref:_},!0):Promise.resolve()}function O(w){try{return B._compile(w)}catch(j){if(j instanceof J)return _(j);throw j}function _(j){var Z=j.missingSchema;if(V(Z))throw new Error("Schema "+Z+" is loaded but "+j.missingRef+" cannot be resolved");var U=B._loadingSchemas[Z];if(!U)U=B._loadingSchemas[Z]=B._opts.loadSchema(Z),U.then(N,N);return U.then(function(L){if(!V(Z))return H(L).then(function(){if(!V(Z))B.addSchema(L,Z,void 0,F)})}).then(function(){return O(w)});function N(){delete B._loadingSchemas[Z]}function V(L){return B._refs[L]||B._schemas[L]}}}}}),h6=Y0((Q,Y)=>{Y.exports=function J(W,z,F){var X=" ",B=W.level,K=W.dataLevel,H=W.schema[z],O=W.schemaPath+W.util.getProperty(z),w=W.errSchemaPath+"/"+z,_=!W.opts.allErrors,j,Z="data"+(K||""),U="valid"+B,N="errs__"+B,V=W.opts.$data&&H&&H.$data,L;if(V)X+=" var schema"+B+" = "+W.util.getData(H.$data,K,W.dataPathArr)+"; ",L="schema"+B;else L=H;var D=this,y="definition"+B,S=D.definition,I="",P,g,x,b,k;if(V&&S.$data){k="keywordValidate"+B;var R=S.validateSchema;X+=" var "+y+" = RULES.custom['"+z+"'].definition; var "+k+" = "+y+".validate;"}else{if(b=W.useCustomRule(D,H,W.schema,W),!b)return;L="validate.schema"+O,k=b.code,P=S.compile,g=S.inline,x=S.macro}var T=k+".errors",f="i"+B,$="ruleErr"+B,p=S.async;if(p&&!W.async)throw new Error("async keyword in sync schema");if(!(g||x))X+=""+T+" = null;";if(X+="var "+N+" = errors;var "+U+";",V&&S.$data){if(I+="}",X+=" if ("+L+" === undefined) { "+U+" = true; } else { ",R)I+="}",X+=" "+U+" = "+y+".validateSchema("+L+"); if ("+U+") { "}if(g)if(S.statements)X+=" "+b.validate+" ";else X+=" "+U+" = "+b.validate+"; ";else if(x){var d=W.util.copy(W),I="";d.level++;var X0="valid"+d.level;d.schema=b.validate,d.schemaPath="";var s=W.compositeRule;W.compositeRule=d.compositeRule=!0;var J0=W.validate(d).replace(/validate\.schema/g,k);W.compositeRule=d.compositeRule=s,X+=" "+J0}else{var a=a||[];if(a.push(X),X="",X+=" "+k+".call( ",W.opts.passContext)X+="this";else X+="self";if(P||S.schema===!1)X+=" , "+Z+" ";else X+=" , "+L+" , "+Z+" , validate.schema"+W.schemaPath+" ";if(X+=" , (dataPath || '')",W.errorPath!='""')X+=" + "+W.errorPath;var z0=K?"data"+(K-1||""):"parentData",g0=K?W.dataPathArr[K]:"parentDataProperty";X+=" , "+z0+" , "+g0+" , rootData ) ";var y0=X;if(X=a.pop(),S.errors===!1){if(X+=" "+U+" = ",p)X+="await ";X+=""+y0+"; "}else if(p)T="customErrors"+B,X+=" var "+T+" = null; try { "+U+" = await "+y0+"; } catch (e) { "+U+" = false; if (e instanceof ValidationError) "+T+" = e.errors; else throw e; } ";else X+=" "+T+" = null; "+U+" = "+y0+"; "}if(S.modifying)X+=" if ("+z0+") "+Z+" = "+z0+"["+g0+"];";if(X+=""+I,S.valid){if(_)X+=" if (true) { "}else{if(X+=" if ( ",S.valid===void 0)if(X+=" !",x)X+=""+X0;else X+=""+U;else X+=" "+!S.valid+" ";X+=") { ",j=D.keyword;var a=a||[];a.push(X),X="";var a=a||[];if(a.push(X),X="",W.createErrors!==!1){if(X+=" { keyword: '"+(j||"custom")+"' , dataPath: (dataPath || '') + "+W.errorPath+" , schemaPath: "+W.util.toQuotedString(w)+" , params: { keyword: '"+D.keyword+"' } ",W.opts.messages!==!1)X+=` , message: 'should pass "`+D.keyword+`" keyword validation' `;if(W.opts.verbose)X+=" , schema: validate.schema"+O+" , parentSchema: validate.schema"+W.schemaPath+" , data: "+Z+" ";X+=" } "}else X+=" {} ";var k0=X;if(X=a.pop(),!W.compositeRule&&_)if(W.async)X+=" throw new ValidationError(["+k0+"]); ";else X+=" validate.errors = ["+k0+"]; return false; ";else X+=" var err = "+k0+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var Z0=X;if(X=a.pop(),g)if(S.errors){if(S.errors!="full"){if(X+=" for (var "+f+"="+N+"; "+f+"{Y.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}}),$6=Y0((Q,Y)=>{var J=l8();Y.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:J.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:J.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}}),m6=Y0((Q,Y)=>{var J=/^[a-z_$][a-z0-9_$-]*$/i,W=h6(),z=$6();Y.exports={add:F,get:X,remove:B,validate:K};function F(H,O){var w=this.RULES;if(w.keywords[H])throw new Error("Keyword "+H+" is already defined");if(!J.test(H))throw new Error("Keyword "+H+" is not a valid identifier");if(O){this.validateKeyword(O,!0);var _=O.type;if(Array.isArray(_))for(var j=0;j<_.length;j++)U(H,_[j],O);else U(H,_,O);var Z=O.metaSchema;if(Z){if(O.$data&&this._opts.$data)Z={anyOf:[Z,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]};O.validateSchema=this.compile(Z,!0)}}w.keywords[H]=w.all[H]=!0;function U(N,V,L){var D;for(var y=0;y{Y.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),p6=Y0((Q,Y)=>{var J=K6(),W=W8(),z=N6(),F=h8(),X=$8(),B=M6(),K=x6(),H=y6(),O=t1();Y.exports=N,N.prototype.validate=V,N.prototype.compile=L,N.prototype.addSchema=D,N.prototype.addMetaSchema=y,N.prototype.validateSchema=S,N.prototype.getSchema=P,N.prototype.removeSchema=b,N.prototype.addFormat=s,N.prototype.errorsText=X0,N.prototype._addSchema=R,N.prototype._compile=T,N.prototype.compileAsync=f6();var w=m6();N.prototype.addKeyword=w.add,N.prototype.getKeyword=w.get,N.prototype.removeKeyword=w.remove,N.prototype.validateKeyword=w.validate;var _=Q8();N.ValidationError=_.Validation,N.MissingRefError=_.MissingRef,N.$dataMetaSchema=H;var j="http://json-schema.org/draft-07/schema",Z=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],U=["/properties"];function N(C){if(!(this instanceof N))return new N(C);if(C=this._opts=O.copy(C)||{},Z0(this),this._schemas={},this._refs={},this._fragments={},this._formats=B(C.format),this._cache=C.cache||new z,this._loadingSchemas={},this._compilations=[],this.RULES=K(),this._getId=f(C),C.loopRequired=C.loopRequired||1/0,C.errorDataPath=="property")C._errorDataPathProperty=!0;if(C.serialize===void 0)C.serialize=X;if(this._metaOpts=k0(this),C.formats)z0(this);if(C.keywords)g0(this);if(J0(this),typeof C.meta=="object")this.addMetaSchema(C.meta);if(C.nullable)this.addKeyword("nullable",{metaSchema:{type:"boolean"}});a(this)}function V(C,h){var o;if(typeof C=="string"){if(o=this.getSchema(C),!o)throw new Error('no schema with key or ref "'+C+'"')}else{var G0=this._addSchema(C);o=G0.validate||this._compile(G0)}var m=o(h);if(o.$async!==!0)this.errors=o.errors;return m}function L(C,h){var o=this._addSchema(C,void 0,h);return o.validate||this._compile(o)}function D(C,h,o,G0){if(Array.isArray(C)){for(var m=0;m0)b.push("--allowedTools",y.join(","));if(S.length>0)b.push("--disallowedTools",S.join(","));if(I&&Object.keys(I).length>0)b.push("--mcp-config",JSON.stringify({mcpServers:I}));if(Y&&Object.keys(Y).length>0)b.push("--agents",JSON.stringify(Y));if(D)b.push("--setting-sources",D.join(","));if(P)b.push("--strict-mcp-config");if(U)b.push("--permission-mode",U);if(Z){if(j&&Z===j)throw new Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");b.push("--fallback-model",Z)}if(x)b.push("--include-partial-messages");for(let d of Q)b.push("--add-dir",d);if(this.options.forkSession)b.push("--fork-session");if(this.options.resumeSessionAt)b.push("--resume-session-at",this.options.resumeSessionAt);for(let[d,X0]of Object.entries(F))if(X0===null)b.push(`--${d}`);else b.push(`--${d}`,X0);if(!B.CLAUDE_CODE_ENTRYPOINT)B.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!L1().existsSync(X)){let d=P8(X)?`Claude Code native binary not found at ${X}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${X}. Is options.pathToClaudeCodeExecutable set?`;throw new ReferenceError(d)}let R=P8(X),T=R?X:W,f=R?b:[...z,X,...b];this.logForDebugging(R?`Spawning Claude Code native binary: ${X} ${b.join(" ")}`:`Spawning Claude Code process: ${W} ${[...z,X,...b].join(" ")}`);let $=B.DEBUG||K?"pipe":"ignore";if(this.child=n6(T,f,{cwd:J,stdio:["pipe","pipe",$],signal:this.abortController.signal,env:B}),this.childStdin=this.child.stdin,this.childStdout=this.child.stdout,B.DEBUG||K)this.child.stderr.on("data",(d)=>{this.logForDebugging(d.toString())});let p=()=>{if(this.child&&!this.child.killed)this.child.kill("SIGTERM")};this.processExitHandler=p,this.abortHandler=p,process.on("exit",this.processExitHandler),this.abortController.signal.addEventListener("abort",this.abortHandler),this.child.on("error",(d)=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new f1("Claude Code process aborted by user");else this.exitError=new Error(`Failed to spawn Claude Code process: ${d.message}`),this.logForDebugging(this.exitError.message)}),this.child.on("close",(d,X0)=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new f1("Claude Code process aborted by user");else{let s=this.getProcessExitError(d,X0);if(s)this.exitError=s,this.logForDebugging(s.message)}}),this.ready=!0}catch(Q){throw this.ready=!1,Q}}getProcessExitError(Q,Y){if(Q!==0&&Q!==null)return new Error(`Claude Code process exited with code ${Q}`);else if(Y)return new Error(`Claude Code process terminated by signal ${Y}`);return}logForDebugging(Q){if(process.env.DEBUG)process.stderr.write(`${Q} -`);if(this.options.stderr)this.options.stderr(Q)}write(Q){if(this.abortController.signal.aborted)throw new f1("Operation aborted");if(!this.ready||!this.childStdin)throw new Error("ProcessTransport is not ready for writing");if(this.child?.killed||this.child?.exitCode!==null)throw new Error("Cannot write to terminated process");if(this.exitError)throw new Error(`Cannot write to process that exited with error: ${this.exitError.message}`);if(process.env.DEBUG_SDK)process.stderr.write(`[ProcessTransport] Writing to stdin: ${Q.substring(0,100)} -`);try{if(!this.childStdin.write(Q)&&process.env.DEBUG_SDK)console.warn("[ProcessTransport] Write buffer full, data queued")}catch(Y){throw this.ready=!1,new Error(`Failed to write to process stdin: ${Y.message}`)}}close(){if(this.childStdin)this.childStdin.end(),this.childStdin=void 0;if(this.processExitHandler)process.off("exit",this.processExitHandler),this.processExitHandler=void 0;if(this.abortHandler)this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0;for(let{handler:Q}of this.exitListeners)this.child?.off("exit",Q);if(this.exitListeners=[],this.child&&!this.child.killed)this.child.kill("SIGTERM"),setTimeout(()=>{if(this.child&&!this.child.killed)this.child.kill("SIGKILL")},5000);this.ready=!1}isReady(){return this.ready}async*readMessages(){if(!this.childStdout)throw new Error("ProcessTransport output stream not available");let Q=i6({input:this.childStdout});try{for await(let Y of Q)if(Y.trim())yield JSON.parse(Y);await this.waitForExit()}catch(Y){throw Y}finally{Q.close()}}endInput(){if(this.childStdin)this.childStdin.end()}getInputStream(){return this.childStdin}onExit(Q){if(!this.child)return()=>{};let Y=(J,W)=>{let z=this.getProcessExitError(J,W);Q(z)};return this.child.on("exit",Y),this.exitListeners.push({callback:Q,handler:Y}),()=>{if(this.child)this.child.off("exit",Y);let J=this.exitListeners.findIndex((W)=>W.handler===Y);if(J!==-1)this.exitListeners.splice(J,1)}}async waitForExit(){if(!this.child){if(this.exitError)throw this.exitError;return}if(this.child.exitCode!==null||this.child.killed){if(this.exitError)throw this.exitError;return}return new Promise((Q,Y)=>{let J=(z,F)=>{if(this.abortController.signal.aborted){Y(new f1("Operation aborted"));return}let X=this.getProcessExitError(z,F);if(X)Y(X);else Q()};this.child.once("exit",J);let W=(z)=>{this.child.off("exit",J),Y(z)};this.child.once("error",W),this.child.once("exit",()=>{this.child.off("error",W)})})}}function P8(Q){return![".js",".mjs",".tsx",".ts",".jsx"].some((J)=>Q.endsWith(J))}class c8{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(Q){this.returned=Q}[Symbol.asyncIterator](){if(this.started)throw new Error("Stream can only be iterated once");return this.started=!0,this}next(){if(this.queue.length>0)return Promise.resolve({done:!1,value:this.queue.shift()});if(this.isDone)return Promise.resolve({done:!0,value:void 0});if(this.hasError)return Promise.reject(this.hasError);return new Promise((Q,Y)=>{this.readResolve=Q,this.readReject=Y})}enqueue(Q){if(this.readResolve){let Y=this.readResolve;this.readResolve=void 0,this.readReject=void 0,Y({done:!1,value:Q})}else this.queue.push(Q)}done(){if(this.isDone=!0,this.readResolve){let Q=this.readResolve;this.readResolve=void 0,this.readReject=void 0,Q({done:!0,value:void 0})}}error(Q){if(this.hasError=Q,this.readReject){let Y=this.readReject;this.readResolve=void 0,this.readReject=void 0,Y(Q)}}return(){if(this.isDone=!0,this.returned)this.returned();return Promise.resolve({done:!0,value:void 0})}}class n8{sendMcpMessage;isClosed=!1;constructor(Q){this.sendMcpMessage=Q}onclose;onerror;onmessage;async start(){}async send(Q){if(this.isClosed)throw new Error("Transport is closed");this.sendMcpMessage(Q)}async close(){if(this.isClosed)return;this.isClosed=!0,this.onclose?.()}}var a6=typeof global=="object"&&global&&global.Object===Object&&global,t6=a6,e6=typeof self=="object"&&self&&self.Object===Object&&self,WQ=t6||e6||Function("return this")(),X8=WQ,QQ=X8.Symbol,P9=QQ,i8=Object.prototype,XQ=i8.hasOwnProperty,YQ=i8.toString,U9=P9?P9.toStringTag:void 0;function JQ(Q){var Y=XQ.call(Q,U9),J=Q[U9];try{Q[U9]=void 0;var W=!0}catch(F){}var z=YQ.call(Q);if(W)if(Y)Q[U9]=J;else delete Q[U9];return z}var zQ=JQ,GQ=Object.prototype,BQ=GQ.toString;function FQ(Q){return BQ.call(Q)}var HQ=FQ,UQ="[object Null]",qQ="[object Undefined]",T8=P9?P9.toStringTag:void 0;function KQ(Q){if(Q==null)return Q===void 0?qQ:UQ;return T8&&T8 in Object(Q)?zQ(Q):HQ(Q)}var NQ=KQ;function MQ(Q){var Y=typeof Q;return Q!=null&&(Y=="object"||Y=="function")}var o8=MQ,LQ="[object AsyncFunction]",jQ="[object Function]",AQ="[object GeneratorFunction]",VQ="[object Proxy]";function OQ(Q){if(!o8(Q))return!1;var Y=NQ(Q);return Y==jQ||Y==AQ||Y==LQ||Y==VQ}var ZQ=OQ,wQ=X8["__core-js_shared__"],d9=wQ,E8=function(){var Q=/[^.]+$/.exec(d9&&d9.keys&&d9.keys.IE_PROTO||"");return Q?"Symbol(src)_1."+Q:""}();function RQ(Q){return!!E8&&E8 in Q}var DQ=RQ,IQ=Function.prototype,CQ=IQ.toString;function _Q(Q){if(Q!=null){try{return CQ.call(Q)}catch(Y){}try{return Q+""}catch(Y){}}return""}var PQ=_Q,TQ=/[\\^$.*+?()[\]{}|]/g,EQ=/^\[object .+?Constructor\]$/,bQ=Function.prototype,SQ=Object.prototype,vQ=bQ.toString,gQ=SQ.hasOwnProperty,kQ=RegExp("^"+vQ.call(gQ).replace(TQ,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function xQ(Q){if(!o8(Q)||DQ(Q))return!1;var Y=ZQ(Q)?kQ:EQ;return Y.test(PQ(Q))}var yQ=xQ;function fQ(Q,Y){return Q==null?void 0:Q[Y]}var hQ=fQ;function $Q(Q,Y){var J=hQ(Q,Y);return yQ(J)?J:void 0}var r8=$Q;function mQ(Q,Y){return Q===Y||Q!==Q&&Y!==Y}var lQ=mQ,pQ=r8(Object,"create"),q9=pQ;function dQ(){this.__data__=q9?q9(null):{},this.size=0}var uQ=dQ;function cQ(Q){var Y=this.has(Q)&&delete this.__data__[Q];return this.size-=Y?1:0,Y}var nQ=cQ,iQ="__lodash_hash_undefined__",oQ=Object.prototype,rQ=oQ.hasOwnProperty;function sQ(Q){var Y=this.__data__;if(q9){var J=Y[Q];return J===iQ?void 0:J}return rQ.call(Y,Q)?Y[Q]:void 0}var aQ=sQ,tQ=Object.prototype,eQ=tQ.hasOwnProperty;function WX(Q){var Y=this.__data__;return q9?Y[Q]!==void 0:eQ.call(Y,Q)}var QX=WX,XX="__lodash_hash_undefined__";function YX(Q,Y){var J=this.__data__;return this.size+=this.has(Q)?0:1,J[Q]=q9&&Y===void 0?XX:Y,this}var JX=YX;function e1(Q){var Y=-1,J=Q==null?0:Q.length;this.clear();while(++Y-1}var LX=MX;function jX(Q,Y){var J=this.__data__,W=b9(J,Q);if(W<0)++this.size,J.push([Q,Y]);else J[W][1]=Y;return this}var AX=jX;function W9(Q){var Y=-1,J=Q==null?0:Q.length;this.clear();while(++Y{if(!Q||Q.trim()==="")return null;let Y=Q.split(",").map((F)=>F.trim()).filter(Boolean);if(Y.length===0)return null;let J=Y.some((F)=>F.startsWith("!")),W=Y.some((F)=>!F.startsWith("!"));if(J&&W)return null;let z=Y.map((F)=>F.replace(/^!/,"").toLowerCase());return{include:J?[]:z,exclude:J?z:[],isExclusive:J}});function fX(Q){let Y=[],J=Q.match(/^MCP server ["']([^"']+)["']/);if(J&&J[1])Y.push("mcp"),Y.push(J[1].toLowerCase());else{let F=Q.match(/^([^:[]+):/);if(F&&F[1])Y.push(F[1].trim().toLowerCase())}let W=Q.match(/^\[([^\]]+)]/);if(W&&W[1])Y.push(W[1].trim().toLowerCase());if(Q.toLowerCase().includes("statsig event:"))Y.push("statsig");let z=Q.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);if(z&&z[1]){let F=z[1].trim().toLowerCase();if(F.length<30&&!F.includes(" "))Y.push(F)}return Array.from(new Set(Y))}function hX(Q,Y){if(!Y)return!0;if(Q.length===0)return!1;if(Y.isExclusive)return!Q.some((J)=>Y.exclude.includes(J));else return Q.some((J)=>Y.include.includes(J))}function $X(Q,Y){if(!Y)return!0;let J=fX(Q);return hX(J,Y)}function pX(){return process.env.CLAUDE_CONFIG_DIR??mX(lX(),".claude")}function v8(Q){if(!Q)return!1;if(typeof Q==="boolean")return Q;let Y=Q.toLowerCase().trim();return["1","true","yes","on"].includes(Y)}var uX={name:"BASH_MAX_OUTPUT_LENGTH",default:30000,validate:(Q)=>{if(!Q)return{effective:30000,status:"valid"};let W=parseInt(Q,10);if(isNaN(W)||W<=0)return{effective:30000,status:"invalid",message:`Invalid value "${Q}" (using default: 30000)`};if(W>150000)return{effective:150000,status:"capped",message:`Capped from ${W} to 150000`};return{effective:W,status:"valid"}}},cX={name:"CLAUDE_CODE_MAX_OUTPUT_TOKENS",default:32000,validate:(Q)=>{if(!Q)return{effective:32000,status:"valid"};let Y=parseInt(Q,10);if(isNaN(Y)||Y<=0)return{effective:32000,status:"invalid",message:`Invalid value "${Q}" (using default: 32000)`};if(Y>32000)return{effective:32000,status:"capped",message:`Capped from ${Y} to 32000`};return{effective:Y,status:"valid"}}};function nX(){return{originalCwd:g8(),totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,startTime:Date.now(),lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:g8(),modelUsage:{},mainLoopModelOverride:void 0,maxRateLimitFallbackActive:!1,initialMainLoopModel:null,modelStrings:null,isNonInteractiveSession:!0,isInteractive:!1,clientType:"cli",sessionIngressToken:void 0,oauthTokenFromFd:void 0,apiKeyFromFd:void 0,flagSettingsPath:void 0,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,sessionId:dX(),loggerProvider:null,eventLogger:null,meterProvider:null,agentColorMap:new Map,agentColorIndex:0,envVarValidators:[uX,cX],lastAPIRequest:null,inMemoryErrorLog:[]}}var iX=nX();function oX(){return iX.sessionId}var mJ=V9(()=>{return v8(process.env.DEBUG)||v8(process.env.DEBUG_SDK)||process.argv.includes("--debug")||process.argv.includes("-d")||t8()||process.argv.some((Q)=>Q.startsWith("--debug="))}),rX=V9(()=>{let Q=process.argv.find((J)=>J.startsWith("--debug="));if(!Q)return null;let Y=Q.substring(8);return yX(Y)}),t8=V9(()=>{return process.argv.includes("--debug-to-stderr")||process.argv.includes("-d2e")});function sX(Q){let Y=rX();return $X(Q,Y)}var aX=!1;function K1(Q,{level:Y}={level:"debug"}){if(!sX(Q))return;if(aX&&Q.includes(` -`))Q=JSON.stringify(Q);let J=`[${Y.toUpperCase()}] ${Q.trim()} -`;if(t8()){xX(J);return}if(!L1().existsSync(n9(_9())))L1().mkdirSync(n9(_9()));L1().appendFileSync(_9(),J),tX()}function _9(){return process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??a8(pX(),"debug",`${oX()}.txt`)}var tX=V9(()=>{try{let Q=_9(),Y=n9(Q),J=a8(Y,"latest");if(!L1().existsSync(Y))L1().mkdirSync(Y);if(L1().existsSync(J))try{L1().unlinkSync(J)}catch{}L1().symlinkSync(Q,J)}catch{}});class e8{transport;isSingleUserTurn;canUseTool;hooks;abortController;pendingControlResponses=new Map;cleanupPerformed=!1;sdkMessages;inputStream=new c8;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;sdkMcpTransports=new Map;pendingMcpResponses=new Map;firstResultReceivedPromise;firstResultReceivedResolve;constructor(Q,Y,J,W,z,F=new Map){this.transport=Q,this.isSingleUserTurn=Y,this.canUseTool=J,this.hooks=W,this.abortController=z;for(let[X,B]of F){let K=new n8((H)=>this.sendMcpServerMessageToCli(X,H));this.sdkMcpTransports.set(X,K),B.connect(K)}this.sdkMessages=this.readSdkMessages(),this.firstResultReceivedPromise=new Promise((X)=>{this.firstResultReceivedResolve=X}),this.readMessages(),this.initialization=this.initialize(),this.initialization.catch(()=>{})}setError(Q){this.inputStream.error(Q)}cleanup(Q){if(this.cleanupPerformed)return;this.cleanupPerformed=!0;try{if(this.transport.close(),this.pendingControlResponses.clear(),this.pendingMcpResponses.clear(),Q)this.inputStream.error(Q);else this.inputStream.done()}catch(Y){}}next(...[Q]){return this.sdkMessages.next(...[Q])}return(Q){return this.sdkMessages.return(Q)}throw(Q){return this.sdkMessages.throw(Q)}[Symbol.asyncIterator](){return this.sdkMessages}[Symbol.asyncDispose](){return this.sdkMessages[Symbol.asyncDispose]()}async readMessages(){try{for await(let Q of this.transport.readMessages()){if(Q.type==="control_response"){let Y=this.pendingControlResponses.get(Q.response.request_id);if(Y)Y(Q.response);continue}else if(Q.type==="control_request"){this.handleControlRequest(Q);continue}else if(Q.type==="control_cancel_request"){this.handleControlCancelRequest(Q);continue}else if(Q.type==="keep_alive")continue;if(Q.type==="result"){if(this.firstResultReceivedResolve)this.firstResultReceivedResolve();if(this.isSingleUserTurn)this.transport.endInput()}this.inputStream.enqueue(Q)}this.inputStream.done(),this.cleanup()}catch(Q){this.inputStream.error(Q),this.cleanup(Q)}}async handleControlRequest(Q){let Y=new AbortController;this.cancelControllers.set(Q.request_id,Y);try{let J=await this.processControlRequest(Q,Y.signal),W={type:"control_response",response:{subtype:"success",request_id:Q.request_id,response:J}};await Promise.resolve(this.transport.write(JSON.stringify(W)+` -`))}catch(J){let W={type:"control_response",response:{subtype:"error",request_id:Q.request_id,error:J.message||String(J)}};await Promise.resolve(this.transport.write(JSON.stringify(W)+` -`))}finally{this.cancelControllers.delete(Q.request_id)}}handleControlCancelRequest(Q){let Y=this.cancelControllers.get(Q.request_id);if(Y)Y.abort(),this.cancelControllers.delete(Q.request_id)}async processControlRequest(Q,Y){if(Q.request.subtype==="can_use_tool"){if(!this.canUseTool)throw new Error("canUseTool callback is not provided.");return this.canUseTool(Q.request.tool_name,Q.request.input,{signal:Y,suggestions:Q.request.permission_suggestions})}else if(Q.request.subtype==="hook_callback")return await this.handleHookCallbacks(Q.request.callback_id,Q.request.input,Q.request.tool_use_id,Y);else if(Q.request.subtype==="mcp_message"){let J=Q.request,W=this.sdkMcpTransports.get(J.server_name);if(!W)throw new Error(`SDK MCP server not found: ${J.server_name}`);if("method"in J.message&&"id"in J.message&&J.message.id!==null)return{mcp_response:await this.handleMcpControlRequest(J.server_name,J,W)};else{if(W.onmessage)W.onmessage(J.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}throw new Error("Unsupported control request subtype: "+Q.request.subtype)}async*readSdkMessages(){for await(let Q of this.inputStream)yield Q}async initialize(){let Q;if(this.hooks){Q={};for(let[z,F]of Object.entries(this.hooks))if(F.length>0)Q[z]=F.map((X)=>{let B=[];for(let K of X.hooks){let H=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(H,K),B.push(H)}return{matcher:X.matcher,hookCallbackIds:B}})}let Y=this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,J={subtype:"initialize",hooks:Q,sdkMcpServers:Y};return(await this.request(J)).response}async interrupt(){await this.request({subtype:"interrupt"})}async setPermissionMode(Q){await this.request({subtype:"set_permission_mode",mode:Q})}async setModel(Q){await this.request({subtype:"set_model",model:Q})}request(Q){let Y=Math.random().toString(36).substring(2,15),J={request_id:Y,type:"control_request",request:Q};return new Promise((W,z)=>{this.pendingControlResponses.set(Y,(F)=>{if(F.subtype==="success")W(F);else z(new Error(F.error))}),Promise.resolve(this.transport.write(JSON.stringify(J)+` -`))})}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async accountInfo(){return(await this.initialization).account}async streamInput(Q){K1("[Query.streamInput] Starting to process input stream"),K1(`[Query.streamInput] this.sdkMcpTransports.size = ${this.sdkMcpTransports.size}`);try{let Y=0;for await(let J of Q){if(Y++,K1(`[Query.streamInput] Processing message ${Y}: ${J.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(JSON.stringify(J)+` -`))}if(K1(`[Query.streamInput] Finished processing ${Y} messages from input stream`),K1(`[Query.streamInput] About to check MCP servers. this.sdkMcpTransports.size = ${this.sdkMcpTransports.size}`),this.sdkMcpTransports.size>0&&this.firstResultReceivedPromise){K1("[Query.streamInput] Entering Promise.race to wait for result");let J=1e4,W;if(await Promise.race([this.firstResultReceivedPromise.then(()=>{if(K1("[Query.streamInput] Received first result, closing input stream"),W)clearTimeout(W)}),new Promise((z)=>{W=setTimeout(()=>{K1("[Query.streamInput] Timed out waiting for first result, closing input stream"),z()},J)})]),W)clearTimeout(W)}K1("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(Y){if(!(Y instanceof f1))throw Y}}handleHookCallbacks(Q,Y,J,W){let z=this.hookCallbacks.get(Q);if(!z)throw new Error(`No hook callback found for ID: ${Q}`);return z(Y,J,{signal:W})}sendMcpServerMessageToCli(Q,Y){if("id"in Y&&Y.id!==null&&Y.id!==void 0){let J=`${Q}:${Y.id}`,W=this.pendingMcpResponses.get(J);if(W){W.resolve(Y),this.pendingMcpResponses.delete(J);return}}throw new Error("No pending request found")}handleMcpControlRequest(Q,Y,J){let W="id"in Y.message?Y.message.id:null,z=`${Q}:${W}`;return new Promise((F,X)=>{let B=null,K=()=>{if(B)clearTimeout(B);this.pendingMcpResponses.delete(z)},H=(w)=>{K(),F(w)},O=(w)=>{K(),X(w)};if(this.pendingMcpResponses.set(z,{resolve:H,reject:O}),J.onmessage)J.onmessage(Y.message);else{K(),X(new Error("No message handler registered"));return}B=setTimeout(()=>{if(this.pendingMcpResponses.has(z))K(),X(new Error("Request timeout"))},30000)})}}function eX({prompt:Q,options:{abortController:Y=p8(),additionalDirectories:J=[],agents:W,allowedTools:z=[],appendSystemPrompt:F,canUseTool:X,continue:B,customSystemPrompt:K,cwd:H,disallowedTools:O=[],env:w,executable:_=d8()?"bun":"node",executableArgs:j=[],extraArgs:Z={},fallbackModel:U,forkSession:N,hooks:V,includePartialMessages:L,maxThinkingTokens:D,maxTurns:y,mcpServers:S,model:I,pathToClaudeCodeExecutable:P,permissionMode:g="default",permissionPromptToolName:x,resume:b,resumeSessionAt:k,settingSources:R,stderr:T,strictMcpConfig:f}={}}){if(!w)w={...process.env};if(!w.CLAUDE_CODE_ENTRYPOINT)w.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!P)throw new Error("pathToClaudeCodeExecutable is required");let $={},p=new Map;if(S)for(let[J0,a]of Object.entries(S))if(a.type==="sdk"&&"instance"in a)p.set(J0,a.instance),$[J0]={type:"sdk",name:J0};else $[J0]=a;let d=typeof Q==="string",X0=new u8({abortController:Y,additionalDirectories:J,agents:W,cwd:H,executable:_,executableArgs:j,extraArgs:Z,pathToClaudeCodeExecutable:P,env:w,forkSession:N,stderr:T,customSystemPrompt:K,appendSystemPrompt:F,maxThinkingTokens:D,maxTurns:y,model:I,fallbackModel:U,permissionMode:g,permissionPromptToolName:x,continueConversation:B,resume:b,resumeSessionAt:k,settingSources:R,allowedTools:z,disallowedTools:O,mcpServers:$,strictMcpConfig:f,canUseTool:!!X,hooks:!!V,includePartialMessages:L}),s=new e8(X0,d,X,V,Y,p);if(typeof Q==="string")X0.write(JSON.stringify({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:Q}]},parent_tool_use_id:null})+` -`);else s.streamInput(Q);return s}var G={};F6(G,{void:()=>f5,util:()=>N0,unknown:()=>x5,union:()=>l5,undefined:()=>v5,tuple:()=>u5,transformer:()=>y8,symbol:()=>S5,string:()=>GW,strictObject:()=>m5,setErrorMap:()=>X5,set:()=>i5,record:()=>c5,quotelessJson:()=>W5,promise:()=>e5,preprocess:()=>XY,pipeline:()=>YY,ostring:()=>JY,optional:()=>WY,onumber:()=>zY,oboolean:()=>GY,objectUtil:()=>i9,object:()=>$5,number:()=>BW,nullable:()=>QY,null:()=>g5,never:()=>y5,nativeEnum:()=>t5,nan:()=>T5,map:()=>n5,makeIssue:()=>E9,literal:()=>s5,lazy:()=>r5,late:()=>_5,isValid:()=>I1,isDirty:()=>r9,isAsync:()=>K9,isAborted:()=>o9,intersection:()=>d5,instanceof:()=>P5,getParsedType:()=>M1,getErrorMap:()=>T9,function:()=>o5,enum:()=>a5,effect:()=>y8,discriminatedUnion:()=>p5,defaultErrorMap:()=>m1,datetimeRegex:()=>YW,date:()=>b5,custom:()=>zW,coerce:()=>BY,boolean:()=>FW,bigint:()=>E5,array:()=>h5,any:()=>k5,addIssueToContext:()=>c,ZodVoid:()=>M9,ZodUnknown:()=>A1,ZodUnion:()=>u1,ZodUndefined:()=>p1,ZodType:()=>F0,ZodTuple:()=>G1,ZodTransformer:()=>r0,ZodSymbol:()=>N9,ZodString:()=>e0,ZodSet:()=>P1,ZodSchema:()=>F0,ZodRecord:()=>L9,ZodReadonly:()=>a1,ZodPromise:()=>T1,ZodPipeline:()=>O9,ZodParsedType:()=>i,ZodOptional:()=>Q1,ZodObject:()=>T0,ZodNumber:()=>V1,ZodNullable:()=>j1,ZodNull:()=>d1,ZodNever:()=>z1,ZodNativeEnum:()=>o1,ZodNaN:()=>A9,ZodMap:()=>j9,ZodLiteral:()=>i1,ZodLazy:()=>n1,ZodIssueCode:()=>l,ZodIntersection:()=>c1,ZodFunction:()=>$1,ZodFirstPartyTypeKind:()=>e,ZodError:()=>u0,ZodEnum:()=>Z1,ZodEffects:()=>r0,ZodDiscriminatedUnion:()=>v9,ZodDefault:()=>r1,ZodDate:()=>C1,ZodCatch:()=>s1,ZodBranded:()=>g9,ZodBoolean:()=>l1,ZodBigInt:()=>O1,ZodArray:()=>W1,ZodAny:()=>_1,Schema:()=>F0,ParseStatus:()=>f0,OK:()=>$0,NEVER:()=>FY,INVALID:()=>t,EMPTY_PATH:()=>Y5,DIRTY:()=>h1,BRAND:()=>C5});var N0;(function(Q){Q.assertEqual=(z)=>{};function Y(z){}Q.assertIs=Y;function J(z){throw new Error}Q.assertNever=J,Q.arrayToEnum=(z)=>{let F={};for(let X of z)F[X]=X;return F},Q.getValidEnumValues=(z)=>{let F=Q.objectKeys(z).filter((B)=>typeof z[z[B]]!=="number"),X={};for(let B of F)X[B]=z[B];return Q.objectValues(X)},Q.objectValues=(z)=>{return Q.objectKeys(z).map(function(F){return z[F]})},Q.objectKeys=typeof Object.keys==="function"?(z)=>Object.keys(z):(z)=>{let F=[];for(let X in z)if(Object.prototype.hasOwnProperty.call(z,X))F.push(X);return F},Q.find=(z,F)=>{for(let X of z)if(F(X))return X;return},Q.isInteger=typeof Number.isInteger==="function"?(z)=>Number.isInteger(z):(z)=>typeof z==="number"&&Number.isFinite(z)&&Math.floor(z)===z;function W(z,F=" | "){return z.map((X)=>typeof X==="string"?`'${X}'`:X).join(F)}Q.joinValues=W,Q.jsonStringifyReplacer=(z,F)=>{if(typeof F==="bigint")return F.toString();return F}})(N0||(N0={}));var i9;(function(Q){Q.mergeShapes=(Y,J)=>{return{...Y,...J}}})(i9||(i9={}));var i=N0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),M1=(Q)=>{switch(typeof Q){case"undefined":return i.undefined;case"string":return i.string;case"number":return Number.isNaN(Q)?i.nan:i.number;case"boolean":return i.boolean;case"function":return i.function;case"bigint":return i.bigint;case"symbol":return i.symbol;case"object":if(Array.isArray(Q))return i.array;if(Q===null)return i.null;if(Q.then&&typeof Q.then==="function"&&Q.catch&&typeof Q.catch==="function")return i.promise;if(typeof Map!=="undefined"&&Q instanceof Map)return i.map;if(typeof Set!=="undefined"&&Q instanceof Set)return i.set;if(typeof Date!=="undefined"&&Q instanceof Date)return i.date;return i.object;default:return i.unknown}},l=N0.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"]),W5=(Q)=>{return JSON.stringify(Q,null,2).replace(/"([^"]+)":/g,"$1:")};class u0 extends Error{get errors(){return this.issues}constructor(Q){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let Y=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,Y);else this.__proto__=Y;this.name="ZodError",this.issues=Q}format(Q){let Y=Q||function(z){return z.message},J={_errors:[]},W=(z)=>{for(let F of z.issues)if(F.code==="invalid_union")F.unionErrors.map(W);else if(F.code==="invalid_return_type")W(F.returnTypeError);else if(F.code==="invalid_arguments")W(F.argumentsError);else if(F.path.length===0)J._errors.push(Y(F));else{let X=J,B=0;while(BY.message){let Y={},J=[];for(let W of this.issues)if(W.path.length>0){let z=W.path[0];Y[z]=Y[z]||[],Y[z].push(Q(W))}else J.push(Q(W));return{formErrors:J,fieldErrors:Y}}get formErrors(){return this.flatten()}}u0.create=(Q)=>{return new u0(Q)};var Q5=(Q,Y)=>{let J;switch(Q.code){case l.invalid_type:if(Q.received===i.undefined)J="Required";else J=`Expected ${Q.expected}, received ${Q.received}`;break;case l.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify(Q.expected,N0.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:J=`Unrecognized key(s) in object: ${N0.joinValues(Q.keys,", ")}`;break;case l.invalid_union:J="Invalid input";break;case l.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${N0.joinValues(Q.options)}`;break;case l.invalid_enum_value:J=`Invalid enum value. Expected ${N0.joinValues(Q.options)}, received '${Q.received}'`;break;case l.invalid_arguments:J="Invalid function arguments";break;case l.invalid_return_type:J="Invalid function return type";break;case l.invalid_date:J="Invalid date";break;case l.invalid_string:if(typeof Q.validation==="object")if("includes"in Q.validation){if(J=`Invalid input: must include "${Q.validation.includes}"`,typeof Q.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${Q.validation.position}`}else if("startsWith"in Q.validation)J=`Invalid input: must start with "${Q.validation.startsWith}"`;else if("endsWith"in Q.validation)J=`Invalid input: must end with "${Q.validation.endsWith}"`;else N0.assertNever(Q.validation);else if(Q.validation!=="regex")J=`Invalid ${Q.validation}`;else J="Invalid";break;case l.too_small:if(Q.type==="array")J=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at least":"more than"} ${Q.minimum} element(s)`;else if(Q.type==="string")J=`String must contain ${Q.exact?"exactly":Q.inclusive?"at least":"over"} ${Q.minimum} character(s)`;else if(Q.type==="number")J=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`;else if(Q.type==="bigint")J=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`;else if(Q.type==="date")J=`Date must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(Q.minimum))}`;else J="Invalid input";break;case l.too_big:if(Q.type==="array")J=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at most":"less than"} ${Q.maximum} element(s)`;else if(Q.type==="string")J=`String must contain ${Q.exact?"exactly":Q.inclusive?"at most":"under"} ${Q.maximum} character(s)`;else if(Q.type==="number")J=`Number must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`;else if(Q.type==="bigint")J=`BigInt must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`;else if(Q.type==="date")J=`Date must be ${Q.exact?"exactly":Q.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(Q.maximum))}`;else J="Invalid input";break;case l.custom:J="Invalid input";break;case l.invalid_intersection_types:J="Intersection results could not be merged";break;case l.not_multiple_of:J=`Number must be a multiple of ${Q.multipleOf}`;break;case l.not_finite:J="Number must be finite";break;default:J=Y.defaultError,N0.assertNever(Q)}return{message:J}},m1=Q5,WW=m1;function X5(Q){WW=Q}function T9(){return WW}var E9=(Q)=>{let{data:Y,path:J,errorMaps:W,issueData:z}=Q,F=[...J,...z.path||[]],X={...z,path:F};if(z.message!==void 0)return{...z,path:F,message:z.message};let B="",K=W.filter((H)=>!!H).slice().reverse();for(let H of K)B=H(X,{data:Y,defaultError:B}).message;return{...z,path:F,message:B}},Y5=[];function c(Q,Y){let J=T9(),W=E9({issueData:Y,data:Q.data,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,J,J===m1?void 0:m1].filter((z)=>!!z)});Q.common.issues.push(W)}class f0{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(Q,Y){let J=[];for(let W of Y){if(W.status==="aborted")return t;if(W.status==="dirty")Q.dirty();J.push(W.value)}return{status:Q.value,value:J}}static async mergeObjectAsync(Q,Y){let J=[];for(let W of Y){let z=await W.key,F=await W.value;J.push({key:z,value:F})}return f0.mergeObjectSync(Q,J)}static mergeObjectSync(Q,Y){let J={};for(let W of Y){let{key:z,value:F}=W;if(z.status==="aborted")return t;if(F.status==="aborted")return t;if(z.status==="dirty")Q.dirty();if(F.status==="dirty")Q.dirty();if(z.value!=="__proto__"&&(typeof F.value!=="undefined"||W.alwaysSet))J[z.value]=F.value}return{status:Q.value,value:J}}}var t=Object.freeze({status:"aborted"}),h1=(Q)=>({status:"dirty",value:Q}),$0=(Q)=>({status:"valid",value:Q}),o9=(Q)=>Q.status==="aborted",r9=(Q)=>Q.status==="dirty",I1=(Q)=>Q.status==="valid",K9=(Q)=>typeof Promise!=="undefined"&&Q instanceof Promise,r;(function(Q){Q.errToObj=(Y)=>typeof Y==="string"?{message:Y}:Y||{},Q.toString=(Y)=>typeof Y==="string"?Y:Y?.message})(r||(r={}));class X1{constructor(Q,Y,J,W){this._cachedPath=[],this.parent=Q,this.data=Y,this._path=J,this._key=W}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var k8=(Q,Y)=>{if(I1(Y))return{success:!0,data:Y.value};else{if(!Q.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new u0(Q.common.issues);return this._error=J,this._error}}}};function B0(Q){if(!Q)return{};let{errorMap:Y,invalid_type_error:J,required_error:W,description:z}=Q;if(Y&&(J||W))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(Y)return{errorMap:Y,description:z};return{errorMap:(X,B)=>{let{message:K}=Q;if(X.code==="invalid_enum_value")return{message:K??B.defaultError};if(typeof B.data==="undefined")return{message:K??W??B.defaultError};if(X.code!=="invalid_type")return{message:B.defaultError};return{message:K??J??B.defaultError}},description:z}}class F0{get description(){return this._def.description}_getType(Q){return M1(Q.data)}_getOrReturnCtx(Q,Y){return Y||{common:Q.parent.common,data:Q.data,parsedType:M1(Q.data),schemaErrorMap:this._def.errorMap,path:Q.path,parent:Q.parent}}_processInputParams(Q){return{status:new f0,ctx:{common:Q.parent.common,data:Q.data,parsedType:M1(Q.data),schemaErrorMap:this._def.errorMap,path:Q.path,parent:Q.parent}}}_parseSync(Q){let Y=this._parse(Q);if(K9(Y))throw new Error("Synchronous parse encountered promise.");return Y}_parseAsync(Q){let Y=this._parse(Q);return Promise.resolve(Y)}parse(Q,Y){let J=this.safeParse(Q,Y);if(J.success)return J.data;throw J.error}safeParse(Q,Y){let J={common:{issues:[],async:Y?.async??!1,contextualErrorMap:Y?.errorMap},path:Y?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:M1(Q)},W=this._parseSync({data:Q,path:J.path,parent:J});return k8(J,W)}"~validate"(Q){let Y={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:M1(Q)};if(!this["~standard"].async)try{let J=this._parseSync({data:Q,path:[],parent:Y});return I1(J)?{value:J.value}:{issues:Y.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;Y.common={issues:[],async:!0}}return this._parseAsync({data:Q,path:[],parent:Y}).then((J)=>I1(J)?{value:J.value}:{issues:Y.common.issues})}async parseAsync(Q,Y){let J=await this.safeParseAsync(Q,Y);if(J.success)return J.data;throw J.error}async safeParseAsync(Q,Y){let J={common:{issues:[],contextualErrorMap:Y?.errorMap,async:!0},path:Y?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:M1(Q)},W=this._parse({data:Q,path:J.path,parent:J}),z=await(K9(W)?W:Promise.resolve(W));return k8(J,z)}refine(Q,Y){let J=(W)=>{if(typeof Y==="string"||typeof Y==="undefined")return{message:Y};else if(typeof Y==="function")return Y(W);else return Y};return this._refinement((W,z)=>{let F=Q(W),X=()=>z.addIssue({code:l.custom,...J(W)});if(typeof Promise!=="undefined"&&F instanceof Promise)return F.then((B)=>{if(!B)return X(),!1;else return!0});if(!F)return X(),!1;else return!0})}refinement(Q,Y){return this._refinement((J,W)=>{if(!Q(J))return W.addIssue(typeof Y==="function"?Y(J,W):Y),!1;else return!0})}_refinement(Q){return new r0({schema:this,typeName:e.ZodEffects,effect:{type:"refinement",refinement:Q}})}superRefine(Q){return this._refinement(Q)}constructor(Q){this.spa=this.safeParseAsync,this._def=Q,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:(Y)=>this["~validate"](Y)}}optional(){return Q1.create(this,this._def)}nullable(){return j1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W1.create(this)}promise(){return T1.create(this,this._def)}or(Q){return u1.create([this,Q],this._def)}and(Q){return c1.create(this,Q,this._def)}transform(Q){return new r0({...B0(this._def),schema:this,typeName:e.ZodEffects,effect:{type:"transform",transform:Q}})}default(Q){let Y=typeof Q==="function"?Q:()=>Q;return new r1({...B0(this._def),innerType:this,defaultValue:Y,typeName:e.ZodDefault})}brand(){return new g9({typeName:e.ZodBranded,type:this,...B0(this._def)})}catch(Q){let Y=typeof Q==="function"?Q:()=>Q;return new s1({...B0(this._def),innerType:this,catchValue:Y,typeName:e.ZodCatch})}describe(Q){return new this.constructor({...this._def,description:Q})}pipe(Q){return O9.create(this,Q)}readonly(){return a1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var J5=/^c[^\s-]{8,}$/i,z5=/^[0-9a-z]+$/,G5=/^[0-9A-HJKMNP-TV-Z]{26}$/i,B5=/^[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,F5=/^[a-z0-9_-]{21}$/i,H5=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,U5=/^[-+]?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)?)??$/,q5=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,K5="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",u9,N5=/^(?:(?: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])$/,M5=/^(?:(?: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])$/,L5=/^(([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]))$/,j5=/^(([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])$/,A5=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,V5=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,QW="((\\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])))",O5=new RegExp(`^${QW}$`);function XW(Q){let Y="[0-5]\\d";if(Q.precision)Y=`${Y}\\.\\d{${Q.precision}}`;else if(Q.precision==null)Y=`${Y}(\\.\\d+)?`;let J=Q.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${Y})${J}`}function Z5(Q){return new RegExp(`^${XW(Q)}$`)}function YW(Q){let Y=`${QW}T${XW(Q)}`,J=[];if(J.push(Q.local?"Z?":"Z"),Q.offset)J.push("([+-]\\d{2}:?\\d{2})");return Y=`${Y}(${J.join("|")})`,new RegExp(`^${Y}$`)}function w5(Q,Y){if((Y==="v4"||!Y)&&N5.test(Q))return!0;if((Y==="v6"||!Y)&&L5.test(Q))return!0;return!1}function R5(Q,Y){if(!H5.test(Q))return!1;try{let[J]=Q.split(".");if(!J)return!1;let W=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),z=JSON.parse(atob(W));if(typeof z!=="object"||z===null)return!1;if("typ"in z&&z?.typ!=="JWT")return!1;if(!z.alg)return!1;if(Y&&z.alg!==Y)return!1;return!0}catch{return!1}}function D5(Q,Y){if((Y==="v4"||!Y)&&M5.test(Q))return!0;if((Y==="v6"||!Y)&&j5.test(Q))return!0;return!1}class e0 extends F0{_parse(Q){if(this._def.coerce)Q.data=String(Q.data);if(this._getType(Q)!==i.string){let z=this._getOrReturnCtx(Q);return c(z,{code:l.invalid_type,expected:i.string,received:z.parsedType}),t}let J=new f0,W=void 0;for(let z of this._def.checks)if(z.kind==="min"){if(Q.data.lengthz.value)W=this._getOrReturnCtx(Q,W),c(W,{code:l.too_big,maximum:z.value,type:"string",inclusive:!0,exact:!1,message:z.message}),J.dirty()}else if(z.kind==="length"){let F=Q.data.length>z.value,X=Q.data.lengthQ.test(W),{validation:Y,code:l.invalid_string,...r.errToObj(J)})}_addCheck(Q){return new e0({...this._def,checks:[...this._def.checks,Q]})}email(Q){return this._addCheck({kind:"email",...r.errToObj(Q)})}url(Q){return this._addCheck({kind:"url",...r.errToObj(Q)})}emoji(Q){return this._addCheck({kind:"emoji",...r.errToObj(Q)})}uuid(Q){return this._addCheck({kind:"uuid",...r.errToObj(Q)})}nanoid(Q){return this._addCheck({kind:"nanoid",...r.errToObj(Q)})}cuid(Q){return this._addCheck({kind:"cuid",...r.errToObj(Q)})}cuid2(Q){return this._addCheck({kind:"cuid2",...r.errToObj(Q)})}ulid(Q){return this._addCheck({kind:"ulid",...r.errToObj(Q)})}base64(Q){return this._addCheck({kind:"base64",...r.errToObj(Q)})}base64url(Q){return this._addCheck({kind:"base64url",...r.errToObj(Q)})}jwt(Q){return this._addCheck({kind:"jwt",...r.errToObj(Q)})}ip(Q){return this._addCheck({kind:"ip",...r.errToObj(Q)})}cidr(Q){return this._addCheck({kind:"cidr",...r.errToObj(Q)})}datetime(Q){if(typeof Q==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:Q});return this._addCheck({kind:"datetime",precision:typeof Q?.precision==="undefined"?null:Q?.precision,offset:Q?.offset??!1,local:Q?.local??!1,...r.errToObj(Q?.message)})}date(Q){return this._addCheck({kind:"date",message:Q})}time(Q){if(typeof Q==="string")return this._addCheck({kind:"time",precision:null,message:Q});return this._addCheck({kind:"time",precision:typeof Q?.precision==="undefined"?null:Q?.precision,...r.errToObj(Q?.message)})}duration(Q){return this._addCheck({kind:"duration",...r.errToObj(Q)})}regex(Q,Y){return this._addCheck({kind:"regex",regex:Q,...r.errToObj(Y)})}includes(Q,Y){return this._addCheck({kind:"includes",value:Q,position:Y?.position,...r.errToObj(Y?.message)})}startsWith(Q,Y){return this._addCheck({kind:"startsWith",value:Q,...r.errToObj(Y)})}endsWith(Q,Y){return this._addCheck({kind:"endsWith",value:Q,...r.errToObj(Y)})}min(Q,Y){return this._addCheck({kind:"min",value:Q,...r.errToObj(Y)})}max(Q,Y){return this._addCheck({kind:"max",value:Q,...r.errToObj(Y)})}length(Q,Y){return this._addCheck({kind:"length",value:Q,...r.errToObj(Y)})}nonempty(Q){return this.min(1,r.errToObj(Q))}trim(){return new e0({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e0({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e0({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((Q)=>Q.kind==="datetime")}get isDate(){return!!this._def.checks.find((Q)=>Q.kind==="date")}get isTime(){return!!this._def.checks.find((Q)=>Q.kind==="time")}get isDuration(){return!!this._def.checks.find((Q)=>Q.kind==="duration")}get isEmail(){return!!this._def.checks.find((Q)=>Q.kind==="email")}get isURL(){return!!this._def.checks.find((Q)=>Q.kind==="url")}get isEmoji(){return!!this._def.checks.find((Q)=>Q.kind==="emoji")}get isUUID(){return!!this._def.checks.find((Q)=>Q.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((Q)=>Q.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((Q)=>Q.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((Q)=>Q.kind==="cuid2")}get isULID(){return!!this._def.checks.find((Q)=>Q.kind==="ulid")}get isIP(){return!!this._def.checks.find((Q)=>Q.kind==="ip")}get isCIDR(){return!!this._def.checks.find((Q)=>Q.kind==="cidr")}get isBase64(){return!!this._def.checks.find((Q)=>Q.kind==="base64")}get isBase64url(){return!!this._def.checks.find((Q)=>Q.kind==="base64url")}get minLength(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q}get maxLength(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value{return new e0({checks:[],typeName:e.ZodString,coerce:Q?.coerce??!1,...B0(Q)})};function I5(Q,Y){let J=(Q.toString().split(".")[1]||"").length,W=(Y.toString().split(".")[1]||"").length,z=J>W?J:W,F=Number.parseInt(Q.toFixed(z).replace(".","")),X=Number.parseInt(Y.toFixed(z).replace(".",""));return F%X/10**z}class V1 extends F0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(Q){if(this._def.coerce)Q.data=Number(Q.data);if(this._getType(Q)!==i.number){let z=this._getOrReturnCtx(Q);return c(z,{code:l.invalid_type,expected:i.number,received:z.parsedType}),t}let J=void 0,W=new f0;for(let z of this._def.checks)if(z.kind==="int"){if(!N0.isInteger(Q.data))J=this._getOrReturnCtx(Q,J),c(J,{code:l.invalid_type,expected:"integer",received:"float",message:z.message}),W.dirty()}else if(z.kind==="min"){if(z.inclusive?Q.dataz.value:Q.data>=z.value)J=this._getOrReturnCtx(Q,J),c(J,{code:l.too_big,maximum:z.value,type:"number",inclusive:z.inclusive,exact:!1,message:z.message}),W.dirty()}else if(z.kind==="multipleOf"){if(I5(Q.data,z.value)!==0)J=this._getOrReturnCtx(Q,J),c(J,{code:l.not_multiple_of,multipleOf:z.value,message:z.message}),W.dirty()}else if(z.kind==="finite"){if(!Number.isFinite(Q.data))J=this._getOrReturnCtx(Q,J),c(J,{code:l.not_finite,message:z.message}),W.dirty()}else N0.assertNever(z);return{status:W.value,value:Q.data}}gte(Q,Y){return this.setLimit("min",Q,!0,r.toString(Y))}gt(Q,Y){return this.setLimit("min",Q,!1,r.toString(Y))}lte(Q,Y){return this.setLimit("max",Q,!0,r.toString(Y))}lt(Q,Y){return this.setLimit("max",Q,!1,r.toString(Y))}setLimit(Q,Y,J,W){return new V1({...this._def,checks:[...this._def.checks,{kind:Q,value:Y,inclusive:J,message:r.toString(W)}]})}_addCheck(Q){return new V1({...this._def,checks:[...this._def.checks,Q]})}int(Q){return this._addCheck({kind:"int",message:r.toString(Q)})}positive(Q){return this._addCheck({kind:"min",value:0,inclusive:!1,message:r.toString(Q)})}negative(Q){return this._addCheck({kind:"max",value:0,inclusive:!1,message:r.toString(Q)})}nonpositive(Q){return this._addCheck({kind:"max",value:0,inclusive:!0,message:r.toString(Q)})}nonnegative(Q){return this._addCheck({kind:"min",value:0,inclusive:!0,message:r.toString(Q)})}multipleOf(Q,Y){return this._addCheck({kind:"multipleOf",value:Q,message:r.toString(Y)})}finite(Q){return this._addCheck({kind:"finite",message:r.toString(Q)})}safe(Q){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:r.toString(Q)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:r.toString(Q)})}get minValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q}get maxValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.valueQ.kind==="int"||Q.kind==="multipleOf"&&N0.isInteger(Q.value))}get isFinite(){let Q=null,Y=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(Y===null||J.value>Y)Y=J.value}else if(J.kind==="max"){if(Q===null||J.value{return new V1({checks:[],typeName:e.ZodNumber,coerce:Q?.coerce||!1,...B0(Q)})};class O1 extends F0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(Q){if(this._def.coerce)try{Q.data=BigInt(Q.data)}catch{return this._getInvalidInput(Q)}if(this._getType(Q)!==i.bigint)return this._getInvalidInput(Q);let J=void 0,W=new f0;for(let z of this._def.checks)if(z.kind==="min"){if(z.inclusive?Q.dataz.value:Q.data>=z.value)J=this._getOrReturnCtx(Q,J),c(J,{code:l.too_big,type:"bigint",maximum:z.value,inclusive:z.inclusive,message:z.message}),W.dirty()}else if(z.kind==="multipleOf"){if(Q.data%z.value!==BigInt(0))J=this._getOrReturnCtx(Q,J),c(J,{code:l.not_multiple_of,multipleOf:z.value,message:z.message}),W.dirty()}else N0.assertNever(z);return{status:W.value,value:Q.data}}_getInvalidInput(Q){let Y=this._getOrReturnCtx(Q);return c(Y,{code:l.invalid_type,expected:i.bigint,received:Y.parsedType}),t}gte(Q,Y){return this.setLimit("min",Q,!0,r.toString(Y))}gt(Q,Y){return this.setLimit("min",Q,!1,r.toString(Y))}lte(Q,Y){return this.setLimit("max",Q,!0,r.toString(Y))}lt(Q,Y){return this.setLimit("max",Q,!1,r.toString(Y))}setLimit(Q,Y,J,W){return new O1({...this._def,checks:[...this._def.checks,{kind:Q,value:Y,inclusive:J,message:r.toString(W)}]})}_addCheck(Q){return new O1({...this._def,checks:[...this._def.checks,Q]})}positive(Q){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:r.toString(Q)})}negative(Q){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:r.toString(Q)})}nonpositive(Q){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:r.toString(Q)})}nonnegative(Q){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:r.toString(Q)})}multipleOf(Q,Y){return this._addCheck({kind:"multipleOf",value:Q,message:r.toString(Y)})}get minValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q}get maxValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value{return new O1({checks:[],typeName:e.ZodBigInt,coerce:Q?.coerce??!1,...B0(Q)})};class l1 extends F0{_parse(Q){if(this._def.coerce)Q.data=Boolean(Q.data);if(this._getType(Q)!==i.boolean){let J=this._getOrReturnCtx(Q);return c(J,{code:l.invalid_type,expected:i.boolean,received:J.parsedType}),t}return $0(Q.data)}}l1.create=(Q)=>{return new l1({typeName:e.ZodBoolean,coerce:Q?.coerce||!1,...B0(Q)})};class C1 extends F0{_parse(Q){if(this._def.coerce)Q.data=new Date(Q.data);if(this._getType(Q)!==i.date){let z=this._getOrReturnCtx(Q);return c(z,{code:l.invalid_type,expected:i.date,received:z.parsedType}),t}if(Number.isNaN(Q.data.getTime())){let z=this._getOrReturnCtx(Q);return c(z,{code:l.invalid_date}),t}let J=new f0,W=void 0;for(let z of this._def.checks)if(z.kind==="min"){if(Q.data.getTime()z.value)W=this._getOrReturnCtx(Q,W),c(W,{code:l.too_big,message:z.message,inclusive:!0,exact:!1,maximum:z.value,type:"date"}),J.dirty()}else N0.assertNever(z);return{status:J.value,value:new Date(Q.data.getTime())}}_addCheck(Q){return new C1({...this._def,checks:[...this._def.checks,Q]})}min(Q,Y){return this._addCheck({kind:"min",value:Q.getTime(),message:r.toString(Y)})}max(Q,Y){return this._addCheck({kind:"max",value:Q.getTime(),message:r.toString(Y)})}get minDate(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q!=null?new Date(Q):null}get maxDate(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value{return new C1({checks:[],coerce:Q?.coerce||!1,typeName:e.ZodDate,...B0(Q)})};class N9 extends F0{_parse(Q){if(this._getType(Q)!==i.symbol){let J=this._getOrReturnCtx(Q);return c(J,{code:l.invalid_type,expected:i.symbol,received:J.parsedType}),t}return $0(Q.data)}}N9.create=(Q)=>{return new N9({typeName:e.ZodSymbol,...B0(Q)})};class p1 extends F0{_parse(Q){if(this._getType(Q)!==i.undefined){let J=this._getOrReturnCtx(Q);return c(J,{code:l.invalid_type,expected:i.undefined,received:J.parsedType}),t}return $0(Q.data)}}p1.create=(Q)=>{return new p1({typeName:e.ZodUndefined,...B0(Q)})};class d1 extends F0{_parse(Q){if(this._getType(Q)!==i.null){let J=this._getOrReturnCtx(Q);return c(J,{code:l.invalid_type,expected:i.null,received:J.parsedType}),t}return $0(Q.data)}}d1.create=(Q)=>{return new d1({typeName:e.ZodNull,...B0(Q)})};class _1 extends F0{constructor(){super(...arguments);this._any=!0}_parse(Q){return $0(Q.data)}}_1.create=(Q)=>{return new _1({typeName:e.ZodAny,...B0(Q)})};class A1 extends F0{constructor(){super(...arguments);this._unknown=!0}_parse(Q){return $0(Q.data)}}A1.create=(Q)=>{return new A1({typeName:e.ZodUnknown,...B0(Q)})};class z1 extends F0{_parse(Q){let Y=this._getOrReturnCtx(Q);return c(Y,{code:l.invalid_type,expected:i.never,received:Y.parsedType}),t}}z1.create=(Q)=>{return new z1({typeName:e.ZodNever,...B0(Q)})};class M9 extends F0{_parse(Q){if(this._getType(Q)!==i.undefined){let J=this._getOrReturnCtx(Q);return c(J,{code:l.invalid_type,expected:i.void,received:J.parsedType}),t}return $0(Q.data)}}M9.create=(Q)=>{return new M9({typeName:e.ZodVoid,...B0(Q)})};class W1 extends F0{_parse(Q){let{ctx:Y,status:J}=this._processInputParams(Q),W=this._def;if(Y.parsedType!==i.array)return c(Y,{code:l.invalid_type,expected:i.array,received:Y.parsedType}),t;if(W.exactLength!==null){let F=Y.data.length>W.exactLength.value,X=Y.data.lengthW.maxLength.value)c(Y,{code:l.too_big,maximum:W.maxLength.value,type:"array",inclusive:!0,exact:!1,message:W.maxLength.message}),J.dirty()}if(Y.common.async)return Promise.all([...Y.data].map((F,X)=>{return W.type._parseAsync(new X1(Y,F,Y.path,X))})).then((F)=>{return f0.mergeArray(J,F)});let z=[...Y.data].map((F,X)=>{return W.type._parseSync(new X1(Y,F,Y.path,X))});return f0.mergeArray(J,z)}get element(){return this._def.type}min(Q,Y){return new W1({...this._def,minLength:{value:Q,message:r.toString(Y)}})}max(Q,Y){return new W1({...this._def,maxLength:{value:Q,message:r.toString(Y)}})}length(Q,Y){return new W1({...this._def,exactLength:{value:Q,message:r.toString(Y)}})}nonempty(Q){return this.min(1,Q)}}W1.create=(Q,Y)=>{return new W1({type:Q,minLength:null,maxLength:null,exactLength:null,typeName:e.ZodArray,...B0(Y)})};function y1(Q){if(Q instanceof T0){let Y={};for(let J in Q.shape){let W=Q.shape[J];Y[J]=Q1.create(y1(W))}return new T0({...Q._def,shape:()=>Y})}else if(Q instanceof W1)return new W1({...Q._def,type:y1(Q.element)});else if(Q instanceof Q1)return Q1.create(y1(Q.unwrap()));else if(Q instanceof j1)return j1.create(y1(Q.unwrap()));else if(Q instanceof G1)return G1.create(Q.items.map((Y)=>y1(Y)));else return Q}class T0 extends F0{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let Q=this._def.shape(),Y=N0.objectKeys(Q);return this._cached={shape:Q,keys:Y},this._cached}_parse(Q){if(this._getType(Q)!==i.object){let K=this._getOrReturnCtx(Q);return c(K,{code:l.invalid_type,expected:i.object,received:K.parsedType}),t}let{status:J,ctx:W}=this._processInputParams(Q),{shape:z,keys:F}=this._getCached(),X=[];if(!(this._def.catchall instanceof z1&&this._def.unknownKeys==="strip")){for(let K in W.data)if(!F.includes(K))X.push(K)}let B=[];for(let K of F){let H=z[K],O=W.data[K];B.push({key:{status:"valid",value:K},value:H._parse(new X1(W,O,W.path,K)),alwaysSet:K in W.data})}if(this._def.catchall instanceof z1){let K=this._def.unknownKeys;if(K==="passthrough")for(let H of X)B.push({key:{status:"valid",value:H},value:{status:"valid",value:W.data[H]}});else if(K==="strict"){if(X.length>0)c(W,{code:l.unrecognized_keys,keys:X}),J.dirty()}else if(K==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let K=this._def.catchall;for(let H of X){let O=W.data[H];B.push({key:{status:"valid",value:H},value:K._parse(new X1(W,O,W.path,H)),alwaysSet:H in W.data})}}if(W.common.async)return Promise.resolve().then(async()=>{let K=[];for(let H of B){let O=await H.key,w=await H.value;K.push({key:O,value:w,alwaysSet:H.alwaysSet})}return K}).then((K)=>{return f0.mergeObjectSync(J,K)});else return f0.mergeObjectSync(J,B)}get shape(){return this._def.shape()}strict(Q){return r.errToObj,new T0({...this._def,unknownKeys:"strict",...Q!==void 0?{errorMap:(Y,J)=>{let W=this._def.errorMap?.(Y,J).message??J.defaultError;if(Y.code==="unrecognized_keys")return{message:r.errToObj(Q).message??W};return{message:W}}}:{}})}strip(){return new T0({...this._def,unknownKeys:"strip"})}passthrough(){return new T0({...this._def,unknownKeys:"passthrough"})}extend(Q){return new T0({...this._def,shape:()=>({...this._def.shape(),...Q})})}merge(Q){return new T0({unknownKeys:Q._def.unknownKeys,catchall:Q._def.catchall,shape:()=>({...this._def.shape(),...Q._def.shape()}),typeName:e.ZodObject})}setKey(Q,Y){return this.augment({[Q]:Y})}catchall(Q){return new T0({...this._def,catchall:Q})}pick(Q){let Y={};for(let J of N0.objectKeys(Q))if(Q[J]&&this.shape[J])Y[J]=this.shape[J];return new T0({...this._def,shape:()=>Y})}omit(Q){let Y={};for(let J of N0.objectKeys(this.shape))if(!Q[J])Y[J]=this.shape[J];return new T0({...this._def,shape:()=>Y})}deepPartial(){return y1(this)}partial(Q){let Y={};for(let J of N0.objectKeys(this.shape)){let W=this.shape[J];if(Q&&!Q[J])Y[J]=W;else Y[J]=W.optional()}return new T0({...this._def,shape:()=>Y})}required(Q){let Y={};for(let J of N0.objectKeys(this.shape))if(Q&&!Q[J])Y[J]=this.shape[J];else{let z=this.shape[J];while(z instanceof Q1)z=z._def.innerType;Y[J]=z}return new T0({...this._def,shape:()=>Y})}keyof(){return JW(N0.objectKeys(this.shape))}}T0.create=(Q,Y)=>{return new T0({shape:()=>Q,unknownKeys:"strip",catchall:z1.create(),typeName:e.ZodObject,...B0(Y)})};T0.strictCreate=(Q,Y)=>{return new T0({shape:()=>Q,unknownKeys:"strict",catchall:z1.create(),typeName:e.ZodObject,...B0(Y)})};T0.lazycreate=(Q,Y)=>{return new T0({shape:Q,unknownKeys:"strip",catchall:z1.create(),typeName:e.ZodObject,...B0(Y)})};class u1 extends F0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=this._def.options;function W(z){for(let X of z)if(X.result.status==="valid")return X.result;for(let X of z)if(X.result.status==="dirty")return Y.common.issues.push(...X.ctx.common.issues),X.result;let F=z.map((X)=>new u0(X.ctx.common.issues));return c(Y,{code:l.invalid_union,unionErrors:F}),t}if(Y.common.async)return Promise.all(J.map(async(z)=>{let F={...Y,common:{...Y.common,issues:[]},parent:null};return{result:await z._parseAsync({data:Y.data,path:Y.path,parent:F}),ctx:F}})).then(W);else{let z=void 0,F=[];for(let B of J){let K={...Y,common:{...Y.common,issues:[]},parent:null},H=B._parseSync({data:Y.data,path:Y.path,parent:K});if(H.status==="valid")return H;else if(H.status==="dirty"&&!z)z={result:H,ctx:K};if(K.common.issues.length)F.push(K.common.issues)}if(z)return Y.common.issues.push(...z.ctx.common.issues),z.result;let X=F.map((B)=>new u0(B));return c(Y,{code:l.invalid_union,unionErrors:X}),t}}get options(){return this._def.options}}u1.create=(Q,Y)=>{return new u1({options:Q,typeName:e.ZodUnion,...B0(Y)})};var N1=(Q)=>{if(Q instanceof n1)return N1(Q.schema);else if(Q instanceof r0)return N1(Q.innerType());else if(Q instanceof i1)return[Q.value];else if(Q instanceof Z1)return Q.options;else if(Q instanceof o1)return N0.objectValues(Q.enum);else if(Q instanceof r1)return N1(Q._def.innerType);else if(Q instanceof p1)return[void 0];else if(Q instanceof d1)return[null];else if(Q instanceof Q1)return[void 0,...N1(Q.unwrap())];else if(Q instanceof j1)return[null,...N1(Q.unwrap())];else if(Q instanceof g9)return N1(Q.unwrap());else if(Q instanceof a1)return N1(Q.unwrap());else if(Q instanceof s1)return N1(Q._def.innerType);else return[]};class v9 extends F0{_parse(Q){let{ctx:Y}=this._processInputParams(Q);if(Y.parsedType!==i.object)return c(Y,{code:l.invalid_type,expected:i.object,received:Y.parsedType}),t;let J=this.discriminator,W=Y.data[J],z=this.optionsMap.get(W);if(!z)return c(Y,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),t;if(Y.common.async)return z._parseAsync({data:Y.data,path:Y.path,parent:Y});else return z._parseSync({data:Y.data,path:Y.path,parent:Y})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(Q,Y,J){let W=new Map;for(let z of Y){let F=N1(z.shape[Q]);if(!F.length)throw new Error(`A discriminator value for key \`${Q}\` could not be extracted from all schema options`);for(let X of F){if(W.has(X))throw new Error(`Discriminator property ${String(Q)} has duplicate value ${String(X)}`);W.set(X,z)}}return new v9({typeName:e.ZodDiscriminatedUnion,discriminator:Q,options:Y,optionsMap:W,...B0(J)})}}function s9(Q,Y){let J=M1(Q),W=M1(Y);if(Q===Y)return{valid:!0,data:Q};else if(J===i.object&&W===i.object){let z=N0.objectKeys(Y),F=N0.objectKeys(Q).filter((B)=>z.indexOf(B)!==-1),X={...Q,...Y};for(let B of F){let K=s9(Q[B],Y[B]);if(!K.valid)return{valid:!1};X[B]=K.data}return{valid:!0,data:X}}else if(J===i.array&&W===i.array){if(Q.length!==Y.length)return{valid:!1};let z=[];for(let F=0;F{if(o9(z)||o9(F))return t;let X=s9(z.value,F.value);if(!X.valid)return c(J,{code:l.invalid_intersection_types}),t;if(r9(z)||r9(F))Y.dirty();return{status:Y.value,value:X.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([z,F])=>W(z,F));else return W(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}c1.create=(Q,Y,J)=>{return new c1({left:Q,right:Y,typeName:e.ZodIntersection,...B0(J)})};class G1 extends F0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==i.array)return c(J,{code:l.invalid_type,expected:i.array,received:J.parsedType}),t;if(J.data.lengththis._def.items.length)c(J,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y.dirty();let z=[...J.data].map((F,X)=>{let B=this._def.items[X]||this._def.rest;if(!B)return null;return B._parse(new X1(J,F,J.path,X))}).filter((F)=>!!F);if(J.common.async)return Promise.all(z).then((F)=>{return f0.mergeArray(Y,F)});else return f0.mergeArray(Y,z)}get items(){return this._def.items}rest(Q){return new G1({...this._def,rest:Q})}}G1.create=(Q,Y)=>{if(!Array.isArray(Q))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new G1({items:Q,typeName:e.ZodTuple,rest:null,...B0(Y)})};class L9 extends F0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==i.object)return c(J,{code:l.invalid_type,expected:i.object,received:J.parsedType}),t;let W=[],z=this._def.keyType,F=this._def.valueType;for(let X in J.data)W.push({key:z._parse(new X1(J,X,J.path,X)),value:F._parse(new X1(J,J.data[X],J.path,X)),alwaysSet:X in J.data});if(J.common.async)return f0.mergeObjectAsync(Y,W);else return f0.mergeObjectSync(Y,W)}get element(){return this._def.valueType}static create(Q,Y,J){if(Y instanceof F0)return new L9({keyType:Q,valueType:Y,typeName:e.ZodRecord,...B0(J)});return new L9({keyType:e0.create(),valueType:Q,typeName:e.ZodRecord,...B0(Y)})}}class j9 extends F0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==i.map)return c(J,{code:l.invalid_type,expected:i.map,received:J.parsedType}),t;let W=this._def.keyType,z=this._def.valueType,F=[...J.data.entries()].map(([X,B],K)=>{return{key:W._parse(new X1(J,X,J.path,[K,"key"])),value:z._parse(new X1(J,B,J.path,[K,"value"]))}});if(J.common.async){let X=new Map;return Promise.resolve().then(async()=>{for(let B of F){let K=await B.key,H=await B.value;if(K.status==="aborted"||H.status==="aborted")return t;if(K.status==="dirty"||H.status==="dirty")Y.dirty();X.set(K.value,H.value)}return{status:Y.value,value:X}})}else{let X=new Map;for(let B of F){let{key:K,value:H}=B;if(K.status==="aborted"||H.status==="aborted")return t;if(K.status==="dirty"||H.status==="dirty")Y.dirty();X.set(K.value,H.value)}return{status:Y.value,value:X}}}}j9.create=(Q,Y,J)=>{return new j9({valueType:Y,keyType:Q,typeName:e.ZodMap,...B0(J)})};class P1 extends F0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==i.set)return c(J,{code:l.invalid_type,expected:i.set,received:J.parsedType}),t;let W=this._def;if(W.minSize!==null){if(J.data.sizeW.maxSize.value)c(J,{code:l.too_big,maximum:W.maxSize.value,type:"set",inclusive:!0,exact:!1,message:W.maxSize.message}),Y.dirty()}let z=this._def.valueType;function F(B){let K=new Set;for(let H of B){if(H.status==="aborted")return t;if(H.status==="dirty")Y.dirty();K.add(H.value)}return{status:Y.value,value:K}}let X=[...J.data.values()].map((B,K)=>z._parse(new X1(J,B,J.path,K)));if(J.common.async)return Promise.all(X).then((B)=>F(B));else return F(X)}min(Q,Y){return new P1({...this._def,minSize:{value:Q,message:r.toString(Y)}})}max(Q,Y){return new P1({...this._def,maxSize:{value:Q,message:r.toString(Y)}})}size(Q,Y){return this.min(Q,Y).max(Q,Y)}nonempty(Q){return this.min(1,Q)}}P1.create=(Q,Y)=>{return new P1({valueType:Q,minSize:null,maxSize:null,typeName:e.ZodSet,...B0(Y)})};class $1 extends F0{constructor(){super(...arguments);this.validate=this.implement}_parse(Q){let{ctx:Y}=this._processInputParams(Q);if(Y.parsedType!==i.function)return c(Y,{code:l.invalid_type,expected:i.function,received:Y.parsedType}),t;function J(X,B){return E9({data:X,path:Y.path,errorMaps:[Y.common.contextualErrorMap,Y.schemaErrorMap,T9(),m1].filter((K)=>!!K),issueData:{code:l.invalid_arguments,argumentsError:B}})}function W(X,B){return E9({data:X,path:Y.path,errorMaps:[Y.common.contextualErrorMap,Y.schemaErrorMap,T9(),m1].filter((K)=>!!K),issueData:{code:l.invalid_return_type,returnTypeError:B}})}let z={errorMap:Y.common.contextualErrorMap},F=Y.data;if(this._def.returns instanceof T1){let X=this;return $0(async function(...B){let K=new u0([]),H=await X._def.args.parseAsync(B,z).catch((_)=>{throw K.addIssue(J(B,_)),K}),O=await Reflect.apply(F,this,H);return await X._def.returns._def.type.parseAsync(O,z).catch((_)=>{throw K.addIssue(W(O,_)),K})})}else{let X=this;return $0(function(...B){let K=X._def.args.safeParse(B,z);if(!K.success)throw new u0([J(B,K.error)]);let H=Reflect.apply(F,this,K.data),O=X._def.returns.safeParse(H,z);if(!O.success)throw new u0([W(H,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...Q){return new $1({...this._def,args:G1.create(Q).rest(A1.create())})}returns(Q){return new $1({...this._def,returns:Q})}implement(Q){return this.parse(Q)}strictImplement(Q){return this.parse(Q)}static create(Q,Y,J){return new $1({args:Q?Q:G1.create([]).rest(A1.create()),returns:Y||A1.create(),typeName:e.ZodFunction,...B0(J)})}}class n1 extends F0{get schema(){return this._def.getter()}_parse(Q){let{ctx:Y}=this._processInputParams(Q);return this._def.getter()._parse({data:Y.data,path:Y.path,parent:Y})}}n1.create=(Q,Y)=>{return new n1({getter:Q,typeName:e.ZodLazy,...B0(Y)})};class i1 extends F0{_parse(Q){if(Q.data!==this._def.value){let Y=this._getOrReturnCtx(Q);return c(Y,{received:Y.data,code:l.invalid_literal,expected:this._def.value}),t}return{status:"valid",value:Q.data}}get value(){return this._def.value}}i1.create=(Q,Y)=>{return new i1({value:Q,typeName:e.ZodLiteral,...B0(Y)})};function JW(Q,Y){return new Z1({values:Q,typeName:e.ZodEnum,...B0(Y)})}class Z1 extends F0{_parse(Q){if(typeof Q.data!=="string"){let Y=this._getOrReturnCtx(Q),J=this._def.values;return c(Y,{expected:N0.joinValues(J),received:Y.parsedType,code:l.invalid_type}),t}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(Q.data)){let Y=this._getOrReturnCtx(Q),J=this._def.values;return c(Y,{received:Y.data,code:l.invalid_enum_value,options:J}),t}return $0(Q.data)}get options(){return this._def.values}get enum(){let Q={};for(let Y of this._def.values)Q[Y]=Y;return Q}get Values(){let Q={};for(let Y of this._def.values)Q[Y]=Y;return Q}get Enum(){let Q={};for(let Y of this._def.values)Q[Y]=Y;return Q}extract(Q,Y=this._def){return Z1.create(Q,{...this._def,...Y})}exclude(Q,Y=this._def){return Z1.create(this.options.filter((J)=>!Q.includes(J)),{...this._def,...Y})}}Z1.create=JW;class o1 extends F0{_parse(Q){let Y=N0.getValidEnumValues(this._def.values),J=this._getOrReturnCtx(Q);if(J.parsedType!==i.string&&J.parsedType!==i.number){let W=N0.objectValues(Y);return c(J,{expected:N0.joinValues(W),received:J.parsedType,code:l.invalid_type}),t}if(!this._cache)this._cache=new Set(N0.getValidEnumValues(this._def.values));if(!this._cache.has(Q.data)){let W=N0.objectValues(Y);return c(J,{received:J.data,code:l.invalid_enum_value,options:W}),t}return $0(Q.data)}get enum(){return this._def.values}}o1.create=(Q,Y)=>{return new o1({values:Q,typeName:e.ZodNativeEnum,...B0(Y)})};class T1 extends F0{unwrap(){return this._def.type}_parse(Q){let{ctx:Y}=this._processInputParams(Q);if(Y.parsedType!==i.promise&&Y.common.async===!1)return c(Y,{code:l.invalid_type,expected:i.promise,received:Y.parsedType}),t;let J=Y.parsedType===i.promise?Y.data:Promise.resolve(Y.data);return $0(J.then((W)=>{return this._def.type.parseAsync(W,{path:Y.path,errorMap:Y.common.contextualErrorMap})}))}}T1.create=(Q,Y)=>{return new T1({type:Q,typeName:e.ZodPromise,...B0(Y)})};class r0 extends F0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===e.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q),W=this._def.effect||null,z={addIssue:(F)=>{if(c(J,F),F.fatal)Y.abort();else Y.dirty()},get path(){return J.path}};if(z.addIssue=z.addIssue.bind(z),W.type==="preprocess"){let F=W.transform(J.data,z);if(J.common.async)return Promise.resolve(F).then(async(X)=>{if(Y.value==="aborted")return t;let B=await this._def.schema._parseAsync({data:X,path:J.path,parent:J});if(B.status==="aborted")return t;if(B.status==="dirty")return h1(B.value);if(Y.value==="dirty")return h1(B.value);return B});else{if(Y.value==="aborted")return t;let X=this._def.schema._parseSync({data:F,path:J.path,parent:J});if(X.status==="aborted")return t;if(X.status==="dirty")return h1(X.value);if(Y.value==="dirty")return h1(X.value);return X}}if(W.type==="refinement"){let F=(X)=>{let B=W.refinement(X,z);if(J.common.async)return Promise.resolve(B);if(B instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return X};if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(X.status==="aborted")return t;if(X.status==="dirty")Y.dirty();return F(X.value),{status:Y.value,value:X.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(X.status==="aborted")return t;if(X.status==="dirty")Y.dirty();return F(X.value).then(()=>{return{status:Y.value,value:X.value}})})}if(W.type==="transform")if(J.common.async===!1){let F=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!I1(F))return t;let X=W.transform(F.value,z);if(X instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:Y.value,value:X}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((F)=>{if(!I1(F))return t;return Promise.resolve(W.transform(F.value,z)).then((X)=>({status:Y.value,value:X}))});N0.assertNever(W)}}r0.create=(Q,Y,J)=>{return new r0({schema:Q,typeName:e.ZodEffects,effect:Y,...B0(J)})};r0.createWithPreprocess=(Q,Y,J)=>{return new r0({schema:Y,effect:{type:"preprocess",transform:Q},typeName:e.ZodEffects,...B0(J)})};class Q1 extends F0{_parse(Q){if(this._getType(Q)===i.undefined)return $0(void 0);return this._def.innerType._parse(Q)}unwrap(){return this._def.innerType}}Q1.create=(Q,Y)=>{return new Q1({innerType:Q,typeName:e.ZodOptional,...B0(Y)})};class j1 extends F0{_parse(Q){if(this._getType(Q)===i.null)return $0(null);return this._def.innerType._parse(Q)}unwrap(){return this._def.innerType}}j1.create=(Q,Y)=>{return new j1({innerType:Q,typeName:e.ZodNullable,...B0(Y)})};class r1 extends F0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=Y.data;if(Y.parsedType===i.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:Y.path,parent:Y})}removeDefault(){return this._def.innerType}}r1.create=(Q,Y)=>{return new r1({innerType:Q,typeName:e.ZodDefault,defaultValue:typeof Y.default==="function"?Y.default:()=>Y.default,...B0(Y)})};class s1 extends F0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J={...Y,common:{...Y.common,issues:[]}},W=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(K9(W))return W.then((z)=>{return{status:"valid",value:z.status==="valid"?z.value:this._def.catchValue({get error(){return new u0(J.common.issues)},input:J.data})}});else return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new u0(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}s1.create=(Q,Y)=>{return new s1({innerType:Q,typeName:e.ZodCatch,catchValue:typeof Y.catch==="function"?Y.catch:()=>Y.catch,...B0(Y)})};class A9 extends F0{_parse(Q){if(this._getType(Q)!==i.nan){let J=this._getOrReturnCtx(Q);return c(J,{code:l.invalid_type,expected:i.nan,received:J.parsedType}),t}return{status:"valid",value:Q.data}}}A9.create=(Q)=>{return new A9({typeName:e.ZodNaN,...B0(Q)})};var C5=Symbol("zod_brand");class g9 extends F0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=Y.data;return this._def.type._parse({data:J,path:Y.path,parent:Y})}unwrap(){return this._def.type}}class O9 extends F0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.common.async)return(async()=>{let z=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(z.status==="aborted")return t;if(z.status==="dirty")return Y.dirty(),h1(z.value);else return this._def.out._parseAsync({data:z.value,path:J.path,parent:J})})();else{let W=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return t;if(W.status==="dirty")return Y.dirty(),{status:"dirty",value:W.value};else return this._def.out._parseSync({data:W.value,path:J.path,parent:J})}}static create(Q,Y){return new O9({in:Q,out:Y,typeName:e.ZodPipeline})}}class a1 extends F0{_parse(Q){let Y=this._def.innerType._parse(Q),J=(W)=>{if(I1(W))W.value=Object.freeze(W.value);return W};return K9(Y)?Y.then((W)=>J(W)):J(Y)}unwrap(){return this._def.innerType}}a1.create=(Q,Y)=>{return new a1({innerType:Q,typeName:e.ZodReadonly,...B0(Y)})};function x8(Q,Y){let J=typeof Q==="function"?Q(Y):typeof Q==="string"?{message:Q}:Q;return typeof J==="string"?{message:J}:J}function zW(Q,Y={},J){if(Q)return _1.create().superRefine((W,z)=>{let F=Q(W);if(F instanceof Promise)return F.then((X)=>{if(!X){let B=x8(Y,W),K=B.fatal??J??!0;z.addIssue({code:"custom",...B,fatal:K})}});if(!F){let X=x8(Y,W),B=X.fatal??J??!0;z.addIssue({code:"custom",...X,fatal:B})}return});return _1.create()}var _5={object:T0.lazycreate},e;(function(Q){Q.ZodString="ZodString",Q.ZodNumber="ZodNumber",Q.ZodNaN="ZodNaN",Q.ZodBigInt="ZodBigInt",Q.ZodBoolean="ZodBoolean",Q.ZodDate="ZodDate",Q.ZodSymbol="ZodSymbol",Q.ZodUndefined="ZodUndefined",Q.ZodNull="ZodNull",Q.ZodAny="ZodAny",Q.ZodUnknown="ZodUnknown",Q.ZodNever="ZodNever",Q.ZodVoid="ZodVoid",Q.ZodArray="ZodArray",Q.ZodObject="ZodObject",Q.ZodUnion="ZodUnion",Q.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Q.ZodIntersection="ZodIntersection",Q.ZodTuple="ZodTuple",Q.ZodRecord="ZodRecord",Q.ZodMap="ZodMap",Q.ZodSet="ZodSet",Q.ZodFunction="ZodFunction",Q.ZodLazy="ZodLazy",Q.ZodLiteral="ZodLiteral",Q.ZodEnum="ZodEnum",Q.ZodEffects="ZodEffects",Q.ZodNativeEnum="ZodNativeEnum",Q.ZodOptional="ZodOptional",Q.ZodNullable="ZodNullable",Q.ZodDefault="ZodDefault",Q.ZodCatch="ZodCatch",Q.ZodPromise="ZodPromise",Q.ZodBranded="ZodBranded",Q.ZodPipeline="ZodPipeline",Q.ZodReadonly="ZodReadonly"})(e||(e={}));var P5=(Q,Y={message:`Input not instance of ${Q.name}`})=>zW((J)=>J instanceof Q,Y),GW=e0.create,BW=V1.create,T5=A9.create,E5=O1.create,FW=l1.create,b5=C1.create,S5=N9.create,v5=p1.create,g5=d1.create,k5=_1.create,x5=A1.create,y5=z1.create,f5=M9.create,h5=W1.create,$5=T0.create,m5=T0.strictCreate,l5=u1.create,p5=v9.create,d5=c1.create,u5=G1.create,c5=L9.create,n5=j9.create,i5=P1.create,o5=$1.create,r5=n1.create,s5=i1.create,a5=Z1.create,t5=o1.create,e5=T1.create,y8=r0.create,WY=Q1.create,QY=j1.create,XY=r0.createWithPreprocess,YY=O9.create,JY=()=>GW().optional(),zY=()=>BW().optional(),GY=()=>FW().optional(),BY={string:(Q)=>e0.create({...Q,coerce:!0}),number:(Q)=>V1.create({...Q,coerce:!0}),boolean:(Q)=>l1.create({...Q,coerce:!0}),bigint:(Q)=>O1.create({...Q,coerce:!0}),date:(Q)=>C1.create({...Q,coerce:!0})},FY=t;var k9="2.0",HW=G.union([G.string(),G.number().int()]),UW=G.string(),HY=G.object({progressToken:G.optional(HW)}).passthrough(),s0=G.object({_meta:G.optional(HY)}).passthrough(),m0=G.object({method:G.string(),params:G.optional(s0)}),Z9=G.object({_meta:G.optional(G.object({}).passthrough())}).passthrough(),B1=G.object({method:G.string(),params:G.optional(Z9)}),a0=G.object({_meta:G.optional(G.object({}).passthrough())}).passthrough(),x9=G.union([G.string(),G.number().int()]),UY=G.object({jsonrpc:G.literal(k9),id:x9}).merge(m0).strict();var qY=G.object({jsonrpc:G.literal(k9)}).merge(B1).strict();var KY=G.object({jsonrpc:G.literal(k9),id:x9,result:a0}).strict();var f8;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError"})(f8||(f8={}));var NY=G.object({jsonrpc:G.literal(k9),id:x9,error:G.object({code:G.number().int(),message:G.string(),data:G.optional(G.unknown())})}).strict();var lJ=G.union([UY,qY,KY,NY]),qW=a0.strict(),KW=B1.extend({method:G.literal("notifications/cancelled"),params:Z9.extend({requestId:x9,reason:G.string().optional()})}),w9=G.object({name:G.string(),title:G.optional(G.string())}).passthrough(),NW=w9.extend({version:G.string()}),MY=G.object({experimental:G.optional(G.object({}).passthrough()),sampling:G.optional(G.object({}).passthrough()),elicitation:G.optional(G.object({}).passthrough()),roots:G.optional(G.object({listChanged:G.optional(G.boolean())}).passthrough())}).passthrough(),LY=m0.extend({method:G.literal("initialize"),params:s0.extend({protocolVersion:G.string(),capabilities:MY,clientInfo:NW})}),jY=G.object({experimental:G.optional(G.object({}).passthrough()),logging:G.optional(G.object({}).passthrough()),completions:G.optional(G.object({}).passthrough()),prompts:G.optional(G.object({listChanged:G.optional(G.boolean())}).passthrough()),resources:G.optional(G.object({subscribe:G.optional(G.boolean()),listChanged:G.optional(G.boolean())}).passthrough()),tools:G.optional(G.object({listChanged:G.optional(G.boolean())}).passthrough())}).passthrough(),AY=a0.extend({protocolVersion:G.string(),capabilities:jY,serverInfo:NW,instructions:G.optional(G.string())}),VY=B1.extend({method:G.literal("notifications/initialized")}),MW=m0.extend({method:G.literal("ping")}),OY=G.object({progress:G.number(),total:G.optional(G.number()),message:G.optional(G.string())}).passthrough(),LW=B1.extend({method:G.literal("notifications/progress"),params:Z9.merge(OY).extend({progressToken:HW})}),y9=m0.extend({params:s0.extend({cursor:G.optional(UW)}).optional()}),f9=a0.extend({nextCursor:G.optional(UW)}),jW=G.object({uri:G.string(),mimeType:G.optional(G.string()),_meta:G.optional(G.object({}).passthrough())}).passthrough(),AW=jW.extend({text:G.string()}),J8=G.string().refine((Q)=>{try{return atob(Q),!0}catch(Y){return!1}},{message:"Invalid Base64 string"}),VW=jW.extend({blob:J8}),OW=w9.extend({uri:G.string(),description:G.optional(G.string()),mimeType:G.optional(G.string()),_meta:G.optional(G.object({}).passthrough())}),ZY=w9.extend({uriTemplate:G.string(),description:G.optional(G.string()),mimeType:G.optional(G.string()),_meta:G.optional(G.object({}).passthrough())}),wY=y9.extend({method:G.literal("resources/list")}),RY=f9.extend({resources:G.array(OW)}),DY=y9.extend({method:G.literal("resources/templates/list")}),IY=f9.extend({resourceTemplates:G.array(ZY)}),CY=m0.extend({method:G.literal("resources/read"),params:s0.extend({uri:G.string()})}),_Y=a0.extend({contents:G.array(G.union([AW,VW]))}),PY=B1.extend({method:G.literal("notifications/resources/list_changed")}),TY=m0.extend({method:G.literal("resources/subscribe"),params:s0.extend({uri:G.string()})}),EY=m0.extend({method:G.literal("resources/unsubscribe"),params:s0.extend({uri:G.string()})}),bY=B1.extend({method:G.literal("notifications/resources/updated"),params:Z9.extend({uri:G.string()})}),SY=G.object({name:G.string(),description:G.optional(G.string()),required:G.optional(G.boolean())}).passthrough(),vY=w9.extend({description:G.optional(G.string()),arguments:G.optional(G.array(SY)),_meta:G.optional(G.object({}).passthrough())}),gY=y9.extend({method:G.literal("prompts/list")}),kY=f9.extend({prompts:G.array(vY)}),xY=m0.extend({method:G.literal("prompts/get"),params:s0.extend({name:G.string(),arguments:G.optional(G.record(G.string()))})}),z8=G.object({type:G.literal("text"),text:G.string(),_meta:G.optional(G.object({}).passthrough())}).passthrough(),G8=G.object({type:G.literal("image"),data:J8,mimeType:G.string(),_meta:G.optional(G.object({}).passthrough())}).passthrough(),B8=G.object({type:G.literal("audio"),data:J8,mimeType:G.string(),_meta:G.optional(G.object({}).passthrough())}).passthrough(),yY=G.object({type:G.literal("resource"),resource:G.union([AW,VW]),_meta:G.optional(G.object({}).passthrough())}).passthrough(),fY=OW.extend({type:G.literal("resource_link")}),ZW=G.union([z8,G8,B8,fY,yY]),hY=G.object({role:G.enum(["user","assistant"]),content:ZW}).passthrough(),$Y=a0.extend({description:G.optional(G.string()),messages:G.array(hY)}),mY=B1.extend({method:G.literal("notifications/prompts/list_changed")}),lY=G.object({title:G.optional(G.string()),readOnlyHint:G.optional(G.boolean()),destructiveHint:G.optional(G.boolean()),idempotentHint:G.optional(G.boolean()),openWorldHint:G.optional(G.boolean())}).passthrough(),pY=w9.extend({description:G.optional(G.string()),inputSchema:G.object({type:G.literal("object"),properties:G.optional(G.object({}).passthrough()),required:G.optional(G.array(G.string()))}).passthrough(),outputSchema:G.optional(G.object({type:G.literal("object"),properties:G.optional(G.object({}).passthrough()),required:G.optional(G.array(G.string()))}).passthrough()),annotations:G.optional(lY),_meta:G.optional(G.object({}).passthrough())}),dY=y9.extend({method:G.literal("tools/list")}),uY=f9.extend({tools:G.array(pY)}),wW=a0.extend({content:G.array(ZW).default([]),structuredContent:G.object({}).passthrough().optional(),isError:G.optional(G.boolean())}),pJ=wW.or(a0.extend({toolResult:G.unknown()})),cY=m0.extend({method:G.literal("tools/call"),params:s0.extend({name:G.string(),arguments:G.optional(G.record(G.unknown()))})}),nY=B1.extend({method:G.literal("notifications/tools/list_changed")}),RW=G.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),iY=m0.extend({method:G.literal("logging/setLevel"),params:s0.extend({level:RW})}),oY=B1.extend({method:G.literal("notifications/message"),params:Z9.extend({level:RW,logger:G.optional(G.string()),data:G.unknown()})}),rY=G.object({name:G.string().optional()}).passthrough(),sY=G.object({hints:G.optional(G.array(rY)),costPriority:G.optional(G.number().min(0).max(1)),speedPriority:G.optional(G.number().min(0).max(1)),intelligencePriority:G.optional(G.number().min(0).max(1))}).passthrough(),aY=G.object({role:G.enum(["user","assistant"]),content:G.union([z8,G8,B8])}).passthrough(),tY=m0.extend({method:G.literal("sampling/createMessage"),params:s0.extend({messages:G.array(aY),systemPrompt:G.optional(G.string()),includeContext:G.optional(G.enum(["none","thisServer","allServers"])),temperature:G.optional(G.number()),maxTokens:G.number().int(),stopSequences:G.optional(G.array(G.string())),metadata:G.optional(G.object({}).passthrough()),modelPreferences:G.optional(sY)})}),eY=a0.extend({model:G.string(),stopReason:G.optional(G.enum(["endTurn","stopSequence","maxTokens"]).or(G.string())),role:G.enum(["user","assistant"]),content:G.discriminatedUnion("type",[z8,G8,B8])}),WJ=G.object({type:G.literal("boolean"),title:G.optional(G.string()),description:G.optional(G.string()),default:G.optional(G.boolean())}).passthrough(),QJ=G.object({type:G.literal("string"),title:G.optional(G.string()),description:G.optional(G.string()),minLength:G.optional(G.number()),maxLength:G.optional(G.number()),format:G.optional(G.enum(["email","uri","date","date-time"]))}).passthrough(),XJ=G.object({type:G.enum(["number","integer"]),title:G.optional(G.string()),description:G.optional(G.string()),minimum:G.optional(G.number()),maximum:G.optional(G.number())}).passthrough(),YJ=G.object({type:G.literal("string"),title:G.optional(G.string()),description:G.optional(G.string()),enum:G.array(G.string()),enumNames:G.optional(G.array(G.string()))}).passthrough(),JJ=G.union([WJ,QJ,XJ,YJ]),zJ=m0.extend({method:G.literal("elicitation/create"),params:s0.extend({message:G.string(),requestedSchema:G.object({type:G.literal("object"),properties:G.record(G.string(),JJ),required:G.optional(G.array(G.string()))}).passthrough()})}),GJ=a0.extend({action:G.enum(["accept","decline","cancel"]),content:G.optional(G.record(G.string(),G.unknown()))}),BJ=G.object({type:G.literal("ref/resource"),uri:G.string()}).passthrough(),FJ=G.object({type:G.literal("ref/prompt"),name:G.string()}).passthrough(),HJ=m0.extend({method:G.literal("completion/complete"),params:s0.extend({ref:G.union([FJ,BJ]),argument:G.object({name:G.string(),value:G.string()}).passthrough(),context:G.optional(G.object({arguments:G.optional(G.record(G.string(),G.string()))}))})}),UJ=a0.extend({completion:G.object({values:G.array(G.string()).max(100),total:G.optional(G.number().int()),hasMore:G.optional(G.boolean())}).passthrough()}),qJ=G.object({uri:G.string().startsWith("file://"),name:G.optional(G.string()),_meta:G.optional(G.object({}).passthrough())}).passthrough(),KJ=m0.extend({method:G.literal("roots/list")}),NJ=a0.extend({roots:G.array(qJ)}),MJ=B1.extend({method:G.literal("notifications/roots/list_changed")}),dJ=G.union([MW,LY,HJ,iY,xY,gY,wY,DY,CY,TY,EY,cY,dY]),uJ=G.union([KW,LW,VY,MJ]),cJ=G.union([qW,eY,GJ,NJ]),nJ=G.union([MW,tY,zJ,KJ]),iJ=G.union([KW,LW,oY,bY,PY,nY,mY]),oJ=G.union([qW,AY,UJ,$Y,kY,RY,IY,_Y,wW,uY]);var rJ=B6(p6(),1);var sJ=Symbol("Let zodToJsonSchema decide on which parser to use");var aJ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var a9;(function(Q){Q.Completable="McpCompletable"})(a9||(a9={}));class t9 extends F0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=Y.data;return this._def.type._parse({data:J,path:Y.path,parent:Y})}unwrap(){return this._def.type}}t9.create=(Q,Y)=>{return new t9({type:Q,typeName:a9.Completable,complete:Y.complete,...LJ(Y)})};function LJ(Q){if(!Q)return{};let{errorMap:Y,invalid_type_error:J,required_error:W,description:z}=Q;if(Y&&(J||W))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(Y)return{errorMap:Y,description:z};return{errorMap:(X,B)=>{var K,H;let{message:O}=Q;if(X.code==="invalid_enum_value")return{message:O!==null&&O!==void 0?O:B.defaultError};if(typeof B.data==="undefined")return{message:(K=O!==null&&O!==void 0?O:W)!==null&&K!==void 0?K:B.defaultError};if(X.code!=="invalid_type")return{message:B.defaultError};return{message:(H=O!==null&&O!==void 0?O:J)!==null&&H!==void 0?H:B.defaultError}},description:z}}function DW({prompt:Q,options:Y}){let{systemPrompt:J,settingSources:W,...z}=Y??{},F,X;if(J===void 0)F="";else if(typeof J==="string")F=J;else if(J.type==="preset")X=J.append;let B=z.pathToClaudeCodeExecutable;if(!B){let K=d6(import.meta.url),H=_8(K,"..");B=_8(H,"cli.js")}return process.env.CLAUDE_AGENT_SDK_VERSION="0.1.15",eX({prompt:Q,options:{...z,pathToClaudeCodeExecutable:B,customSystemPrompt:F,appendSystemPrompt:X,settingSources:W??[]}})}import{Database as AJ}from"bun:sqlite";import{join as c0,dirname as Q7,basename as X7}from"path";import{homedir as IW}from"os";import{existsSync as G7,mkdirSync as jJ}from"fs";var F1=process.env.CLAUDE_MEM_DATA_DIR||c0(IW(),".claude-mem"),F8=process.env.CLAUDE_CONFIG_DIR||c0(IW(),".claude"),B7=c0(F1,"archives"),F7=c0(F1,"logs"),H7=c0(F1,"trash"),U7=c0(F1,"backups"),q7=c0(F1,"chroma"),K7=c0(F1,"settings.json"),CW=c0(F1,"claude-mem.db"),N7=c0(F8,"settings.json"),M7=c0(F8,"commands"),L7=c0(F8,"CLAUDE.md");function _W(Q){return c0(F1,`worker-${Q}.sock`)}function PW(Q){jJ(Q,{recursive:!0})}class H8{db;constructor(){PW(F1),this.db=new AJ(CW,{create:!0,readwrite:!0}),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA foreign_keys = ON")}getRecentSummaries(Q,Y=10){return this.db.query(` - SELECT - request, investigated, learned, completed, next_steps, - files_read, files_edited, notes, created_at - FROM session_summaries - WHERE project = ? - ORDER BY created_at_epoch DESC - LIMIT ? - `).all(Q,Y)}findActiveSDKSession(Q){return this.db.query(` - SELECT id, sdk_session_id, project - FROM sdk_sessions - WHERE claude_session_id = ? AND status = 'active' - LIMIT 1 - `).get(Q)||null}createSDKSession(Q,Y,J){let W=new Date,z=W.getTime();return this.db.query(` - INSERT INTO sdk_sessions - (claude_session_id, project, user_prompt, started_at, started_at_epoch, status) - VALUES (?, ?, ?, ?, ?, 'active') - `).run(Q,Y,J,W.toISOString(),z),this.db.query("SELECT last_insert_rowid() as id").get().id}updateSDKSessionId(Q,Y){this.db.query(` - UPDATE sdk_sessions - SET sdk_session_id = ? - WHERE id = ? - `).run(Y,Q)}storeObservation(Q,Y,J,W){let z=new Date,F=z.getTime();this.db.query(` - INSERT INTO observations - (sdk_session_id, project, text, type, created_at, created_at_epoch) - VALUES (?, ?, ?, ?, ?, ?) - `).run(Q,Y,W,J,z.toISOString(),F)}storeSummary(Q,Y,J){let W=new Date,z=W.getTime();this.db.query(` - INSERT INTO session_summaries - (sdk_session_id, project, request, investigated, learned, completed, - next_steps, files_read, files_edited, notes, created_at, created_at_epoch) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(Q,Y,J.request||null,J.investigated||null,J.learned||null,J.completed||null,J.next_steps||null,J.files_read||null,J.files_edited||null,J.notes||null,W.toISOString(),z)}markSessionCompleted(Q){let Y=new Date,J=Y.getTime();this.db.query(` - UPDATE sdk_sessions - SET status = 'completed', completed_at = ?, completed_at_epoch = ? - WHERE id = ? - `).run(Y.toISOString(),J,Q)}markSessionFailed(Q){let Y=new Date,J=Y.getTime();this.db.query(` - UPDATE sdk_sessions - SET status = 'failed', completed_at = ?, completed_at_epoch = ? - WHERE id = ? - `).run(Y.toISOString(),J,Q)}close(){this.db.close()}}function TW(Q,Y,J){return`You are a memory assistant for the "${Q}" project. - -SESSION CONTEXT ---------------- -Session ID: ${Y} -User's Goal: ${J} -Date: ${new Date().toISOString().split("T")[0]} - -YOUR ROLE ---------- -You will observe tool executions during this Claude Code session. Your job is to: - -1. Extract meaningful insights (not just raw data) -2. Store atomic observations in SQLite -3. Focus on: key decisions, patterns discovered, problems solved, technical insights - -WHAT TO CAPTURE ----------------- -\u2713 Architecture decisions (e.g., "chose PostgreSQL over MongoDB for ACID guarantees") -\u2713 Bug fixes (e.g., "fixed race condition in auth middleware by adding mutex") -\u2713 New features (e.g., "implemented JWT refresh token flow") -\u2713 Refactorings (e.g., "extracted validation logic into separate service") -\u2713 Discoveries (e.g., "found that API rate limit is 100 req/min") - -\u2717 NOT routine operations (reading files, listing directories) -\u2717 NOT work-in-progress (only completed work) -\u2717 NOT obvious facts (e.g., "TypeScript file has types") - -HOW TO STORE OBSERVATIONS --------------------------- -When you identify something worth remembering, output your observation in this EXACT XML format: - -\`\`\`xml - - feature - Implemented JWT token refresh flow with 7-day expiry - -\`\`\` - -Valid types: decision, bugfix, feature, refactor, discovery - -Structure requirements: -- is the root element -- must be one of the 5 valid types (single word) -- contains your concise observation (one sentence preferred) -- No additional fields or nesting - -The SDK worker will parse all blocks from your response using regex and store them in SQLite. - -You can include your reasoning before or after the observation block, or just output the observation by itself. - -EXAMPLE -------- -Bad: "Read src/auth.ts file" -Good: "Implemented JWT token refresh flow with 7-day expiry" - -Wait for tool observations. Acknowledge this message briefly.`}function EW(Q){return`TOOL OBSERVATION -================ -Tool: ${Q.tool_name} -Time: ${new Date(Q.created_at_epoch).toISOString()} - -Input: -${JSON.stringify(JSON.parse(Q.tool_input),null,2)} - -Output: -${JSON.stringify(JSON.parse(Q.tool_output),null,2)} - -ANALYSIS TASK -------------- -1. Does this observation contain something worth remembering? -2. If YES: Output the observation in this EXACT XML format: - - \`\`\`xml - - feature - Your concise observation here - - \`\`\` - - Requirements: - - Use one of these types: decision, bugfix, feature, refactor, discovery - - Keep text concise (one sentence preferred) - - No markdown formatting inside - - No additional XML fields - -3. If NO: Just acknowledge and wait for next observation - -Remember: Quality over quantity. Only store meaningful insights.`}function bW(Q){return`SESSION ENDING -============== -The Claude Code session is finishing. - -FINAL TASK ----------- -1. Review the observations you've stored this session -2. Generate a structured summary that answers these questions: - - What did user request? - - What did you investigate? - - What did you learn? - - What did you do? - - What's next? - - Files read - - Files edited - - Notes - -3. Generate the structured summary and output it in this EXACT XML format: - -\`\`\`xml - - Implement JWT authentication system - Existing auth middleware, session management, token storage patterns - Current system uses session cookies; no JWT support; race condition in middleware - Implemented JWT token + refresh flow with 7-day expiry; fixed race condition with mutex; added token validation middleware - Add token revocation API endpoint; write integration tests - - src/auth.ts - src/middleware/session.ts - src/types/user.ts - - - src/auth.ts - src/middleware/auth.ts - src/routes/auth.ts - - Token secret stored in .env; refresh tokens use rotation strategy - -\`\`\` - -Structure requirements: -- is the root element -- All 8 child elements are REQUIRED: request, investigated, learned, completed, next_steps, files_read, files_edited, notes -- and must contain child elements (one per file) -- If no files were read/edited, use empty tags: -- Text fields can be multiple sentences but avoid markdown formatting -- Use underscores in element names: next_steps, files_read, files_edited - -The SDK worker will parse the block and extract all fields to store in SQLite. - -Generate the summary now in the required XML format.`}function vW(Q){let Y=[],J=/\s*([^<]+)<\/type>\s*([^<]+)<\/text>\s*<\/observation>/g,W;while((W=J.exec(Q))!==null){let z=W[1].trim(),F=W[2].trim();if(!["decision","bugfix","feature","refactor","discovery"].includes(z)){console.warn(`[SDK Parser] Invalid observation type: ${z}, skipping`);continue}Y.push({type:z,text:F})}return Y}function gW(Q){let J=/([\s\S]*?)<\/summary>/.exec(Q);if(!J)return null;let W=J[1],z=X9(W,"request"),F=X9(W,"investigated"),X=X9(W,"learned"),B=X9(W,"completed"),K=X9(W,"next_steps"),H=X9(W,"notes"),O=SW(W,"files_read"),w=SW(W,"files_edited");if(!z||!F||!X||!B||!K||!H)return console.warn("[SDK Parser] Summary missing required fields"),null;return{request:z,investigated:F,learned:X,completed:B,next_steps:K,files_read:O,files_edited:w,notes:H}}function X9(Q,Y){let W=new RegExp(`<${Y}>([^<]*)`).exec(Q);return W?W[1].trim():null}function SW(Q,Y){let J=[],z=new RegExp(`<${Y}>(.*?)`,"s").exec(Q);if(!z)return J;let F=z[1],X=/([^<]+)<\/file>/g,B;while((B=X.exec(F))!==null)J.push(B[1].trim());return J}var xW="claude-sonnet-4-5",OJ=["Glob","Grep","ListMcpResourcesTool","WebSearch"];async function yW(){console.error("[SDK Worker DEBUG] main() called");let Q=parseInt(process.argv[2],10);if(console.error(`[SDK Worker DEBUG] Session DB ID: ${Q}`),!Q)console.error("[SDK Worker] Missing session ID argument"),process.exit(1);let Y=new fW(Q);console.error("[SDK Worker DEBUG] SDKWorker instance created"),await Y.run()}class fW{sessionDbId;db;socketPath;server=null;sdkSessionId=null;project="";userPrompt="";abortController;isFinalized=!1;pendingMessages=[];constructor(Q){this.sessionDbId=Q,this.db=new H8,this.abortController=new AbortController,this.socketPath=_W(Q),console.error("[claude-mem worker] Worker instance created",{sessionDbId:Q,socketPath:this.socketPath})}async run(){console.error("[claude-mem worker] Worker run() started",{sessionDbId:this.sessionDbId,socketPath:this.socketPath});try{let Q=await this.loadSession();if(!Q)console.error("[claude-mem worker] Session not found in database",{sessionDbId:this.sessionDbId}),process.exit(1);console.error("[claude-mem worker] Session loaded successfully",{sessionDbId:this.sessionDbId,project:Q.project,sdkSessionId:Q.sdk_session_id,userPromptLength:Q.user_prompt?.length||0}),this.project=Q.project,this.userPrompt=Q.user_prompt,await this.startSocketServer(),console.error("[claude-mem worker] Socket server started successfully",{socketPath:this.socketPath,sessionDbId:this.sessionDbId}),console.error("[claude-mem worker] Starting SDK agent",{sessionDbId:this.sessionDbId,model:xW}),await this.runSDKAgent(),console.error("[claude-mem worker] SDK agent completed, marking session as completed",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId}),this.db.markSessionCompleted(this.sessionDbId),this.db.close(),this.cleanup()}catch(Q){console.error("[claude-mem worker] Fatal error in run()",{sessionDbId:this.sessionDbId,error:Q.message,stack:Q.stack}),this.db.markSessionFailed(this.sessionDbId),this.db.close(),this.cleanup(),process.exit(1)}}async startSocketServer(){if(console.error("[SDK Worker DEBUG] Starting socket server..."),console.error(`[SDK Worker DEBUG] Socket path: ${this.socketPath}`),h9(this.socketPath))console.error("[SDK Worker DEBUG] Removing existing socket"),kW(this.socketPath);return new Promise((Q,Y)=>{console.error("[SDK Worker DEBUG] Creating net server..."),this.server=VJ.createServer((J)=>{console.error("[claude-mem worker] Socket connection received",{sessionDbId:this.sessionDbId,socketPath:this.socketPath});let W="";J.on("data",(z)=>{console.error("[claude-mem worker] Data received on socket",{sessionDbId:this.sessionDbId,chunkSize:z.length}),W+=z.toString();let F=W.split(` -`);W=F.pop()||"";for(let X of F)if(X.trim())try{let B=JSON.parse(X);console.error("[claude-mem worker] Message received from socket",{sessionDbId:this.sessionDbId,messageType:B.type,rawMessage:X.substring(0,500)}),this.handleMessage(B)}catch(B){console.error("[claude-mem worker] Invalid message - failed to parse JSON",{sessionDbId:this.sessionDbId,error:B instanceof Error?B.message:String(B),rawLine:X.substring(0,200)})}}),J.on("error",(z)=>{console.error("[claude-mem worker] Socket connection error",{sessionDbId:this.sessionDbId,error:z.message,stack:z.stack})})}),this.server.on("error",(J)=>{if(J.code==="EADDRINUSE")console.error("[claude-mem worker] Socket already in use",{socketPath:this.socketPath,sessionDbId:this.sessionDbId});else console.error("[claude-mem worker] Server error",{sessionDbId:this.sessionDbId,error:J.message,code:J.code,stack:J.stack});Y(J)}),this.server.listen(this.socketPath,()=>{console.error("[SDK Worker DEBUG] listen() callback fired"),console.error(`[SDK Worker DEBUG] Checking if socket exists: ${h9(this.socketPath)}`),Q()})})}handleMessage(Q){if(console.error("[claude-mem worker] Processing message in handleMessage()",{sessionDbId:this.sessionDbId,messageType:Q.type,pendingMessagesCount:this.pendingMessages.length}),this.pendingMessages.push(Q),Q.type==="finalize")console.error("[claude-mem worker] FINALIZE message detected - queued for processing",{sessionDbId:this.sessionDbId,pendingMessagesCount:this.pendingMessages.length});else if(Q.type==="observation")console.error("[claude-mem worker] Observation message queued",{sessionDbId:this.sessionDbId,toolName:Q.tool_name,inputLength:Q.tool_input?.length||0,outputLength:Q.tool_output?.length||0})}async loadSession(){return this.db.db.query(` - SELECT id, sdk_session_id, project, user_prompt - FROM sdk_sessions - WHERE id = ? - LIMIT 1 - `).get(this.sessionDbId)}async runSDKAgent(){let Q=process.env.CLAUDE_CODE_PATH||"/Users/alexnewman/.nvm/versions/node/v24.5.0/bin/claude";console.error(`[SDK Worker DEBUG] About to call query with claudePath: ${Q}`);let Y=DW({prompt:this.createMessageGenerator(),options:{model:xW,disallowedTools:OJ,abortController:this.abortController,pathToClaudeCodeExecutable:Q}});for await(let J of Y)if(J.type==="system"&&J.subtype==="init"){let W=J;if(W.session_id)console.error("[claude-mem worker] SDK session initialized",{sessionDbId:this.sessionDbId,sdkSessionId:W.session_id}),this.sdkSessionId=W.session_id,this.db.updateSDKSessionId(this.sessionDbId,W.session_id)}else if(J.type==="assistant"){let W=J.message.content,z=Array.isArray(W)?W.filter((F)=>F.type==="text").map((F)=>F.text).join(` -`):typeof W==="string"?W:"";console.error("[claude-mem worker] SDK agent response received",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId,contentLength:z.length,contentPreview:z.substring(0,200)}),this.handleAgentMessage(z)}}async*createMessageGenerator(){let Q=`session-${this.sessionDbId}`,Y=TW(this.project,Q,this.userPrompt);console.error("[claude-mem worker] Yielding initial prompt to SDK agent",{sessionDbId:this.sessionDbId,claudeSessionId:Q,project:this.project,promptLength:Y.length}),yield{type:"user",session_id:this.sdkSessionId||Q,parent_tool_use_id:null,message:{role:"user",content:Y}};while(!this.isFinalized){if(this.pendingMessages.length===0){await this.sleep(100);continue}while(this.pendingMessages.length>0){let J=this.pendingMessages.shift();if(J.type==="finalize"){console.error("[claude-mem worker] Processing FINALIZE message in generator",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId}),this.isFinalized=!0;let W=await this.loadSession();if(W){let z=bW(W);console.error("[claude-mem worker] Yielding finalize prompt to SDK agent",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId,promptLength:z.length,promptPreview:z.substring(0,300)}),yield{type:"user",session_id:this.sdkSessionId||Q,parent_tool_use_id:null,message:{role:"user",content:z}}}else console.error("[claude-mem worker] Failed to load session for finalize prompt",{sessionDbId:this.sessionDbId});break}if(J.type==="observation"){let W=EW({id:0,tool_name:J.tool_name,tool_input:J.tool_input,tool_output:J.tool_output,created_at_epoch:Date.now()});console.error("[claude-mem worker] Yielding observation prompt to SDK agent",{sessionDbId:this.sessionDbId,toolName:J.tool_name,promptLength:W.length}),yield{type:"user",session_id:this.sdkSessionId||Q,parent_tool_use_id:null,message:{role:"user",content:W}}}}}}handleAgentMessage(Q){console.error("[claude-mem worker] Parsing agent message for observations and summary",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId,contentLength:Q.length});let Y=vW(Q);console.error("[claude-mem worker] Observations parsed from response",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId,observationCount:Y.length});for(let W of Y)if(this.sdkSessionId)console.error("[claude-mem worker] Storing observation in database",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId,project:this.project,observationType:W.type,observationTextLength:W.text?.length||0}),this.db.storeObservation(this.sdkSessionId,this.project,W.type,W.text);else console.error("[claude-mem worker] Cannot store observation - no SDK session ID",{sessionDbId:this.sessionDbId,observationType:W.type});console.error("[claude-mem worker] Attempting to parse summary from response",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId});let J=gW(Q);if(J&&this.sdkSessionId){console.error("[claude-mem worker] Summary parsed successfully",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId,project:this.project,hasRequest:!!J.request,hasInvestigated:!!J.investigated,hasLearned:!!J.learned,hasCompleted:!!J.completed,filesReadCount:J.files_read?.length||0,filesEditedCount:J.files_edited?.length||0});let W={request:J.request,investigated:J.investigated,learned:J.learned,completed:J.completed,next_steps:J.next_steps,files_read:JSON.stringify(J.files_read),files_edited:JSON.stringify(J.files_edited),notes:J.notes};console.error("[claude-mem worker] Storing summary in database",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId,project:this.project}),this.db.storeSummary(this.sdkSessionId,this.project,W),console.error("[claude-mem worker] Summary stored successfully in database",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId,project:this.project})}else if(J&&!this.sdkSessionId)console.error("[claude-mem worker] Summary parsed but cannot store - no SDK session ID",{sessionDbId:this.sessionDbId});else console.error("[claude-mem worker] No summary found in response",{sessionDbId:this.sessionDbId,sdkSessionId:this.sdkSessionId})}cleanup(){if(console.error("[claude-mem worker] Cleaning up worker resources",{sessionDbId:this.sessionDbId,socketPath:this.socketPath,hasServer:!!this.server,socketExists:h9(this.socketPath)}),this.server)this.server.close();if(h9(this.socketPath))kW(this.socketPath);console.error("[claude-mem worker] Cleanup complete",{sessionDbId:this.sessionDbId})}sleep(Q){return new Promise((Y)=>setTimeout(Y,Q))}}yW().catch((Q)=>{console.error("[SDK Worker] Fatal error:",Q),process.exit(1)}); diff --git a/scripts/build-hooks.js b/scripts/build-hooks.js index 4857142c..7c215fe7 100644 --- a/scripts/build-hooks.js +++ b/scripts/build-hooks.js @@ -25,8 +25,13 @@ const WORKER_SERVICE = { source: 'src/services/worker-service.ts' }; +const SEARCH_SERVER = { + name: 'search-server', + source: 'src/servers/search-server.ts' +}; + async function buildHooks() { - console.log('๐Ÿ”จ Building claude-mem hooks and worker service...\n'); + console.log('๐Ÿ”จ Building claude-mem hooks, worker service, and search server...\n'); try { // Read version from package.json @@ -103,9 +108,34 @@ async function buildHooks() { console.log(`โœ“ ${hook.name} built (${sizeInKB} KB)`); } - console.log('\nโœ… All hooks and worker service built successfully!'); + // Build search server + console.log(`\n๐Ÿ”ง Building search server...`); + await build({ + entryPoints: [SEARCH_SERVER.source], + bundle: true, + platform: 'node', + target: 'node18', + format: 'esm', + outfile: `${hooksDir}/${SEARCH_SERVER.name}.js`, + minify: true, + external: ['better-sqlite3'], + define: { + '__DEFAULT_PACKAGE_VERSION__': `"${version}"` + }, + banner: { + js: '#!/usr/bin/env node' + } + }); + + // Make search server executable + fs.chmodSync(`${hooksDir}/${SEARCH_SERVER.name}.js`, 0o755); + const searchStats = fs.statSync(`${hooksDir}/${SEARCH_SERVER.name}.js`); + console.log(`โœ“ search-server built (${(searchStats.size / 1024).toFixed(2)} KB)`); + + console.log('\nโœ… All hooks, worker service, and search server built successfully!'); console.log(` Hooks: ${hooksDir}/`); console.log(` Worker: ${distDir}/worker-service.cjs`); + console.log(` Search: ${hooksDir}/search-server.js`); } catch (error) { console.error('\nโŒ Build failed:', error.message); diff --git a/scripts/replay-transcript.ts b/scripts/replay-transcript.ts index e7b55065..38e78482 100755 --- a/scripts/replay-transcript.ts +++ b/scripts/replay-transcript.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env bun +#!/usr/bin/env node /** * Transcript Replay Tool * @@ -197,7 +197,7 @@ async function replayTranscript(transcriptPath: string, projectName: string = 'c // Spawn worker exactly as production hooks do const workerPath = join(process.cwd(), 'scripts/hooks/worker.js'); - const worker = spawn('bun', [workerPath, String(sessionId)], { + const worker = spawn('node', [workerPath, String(sessionId)], { detached: false, // Keep attached to see errors stdio: ['ignore', 'pipe', 'pipe'] // Pipe output to see what's happening }); diff --git a/src/bin/hooks/worker.ts b/src/bin/hooks/worker.ts index 8118a30f..c2fb0015 100644 --- a/src/bin/hooks/worker.ts +++ b/src/bin/hooks/worker.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env bun +#!/usr/bin/env node /** * Worker Entry Point diff --git a/src/sdk/worker.ts b/src/sdk/worker.ts index 3ce32842..f46d1c32 100644 --- a/src/sdk/worker.ts +++ b/src/sdk/worker.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env bun +#!/usr/bin/env node /** * SDK Worker Process * Background server that processes tool observations via Unix socket diff --git a/src/servers/search-server.ts b/src/servers/search-server.ts new file mode 100644 index 00000000..911a47a9 --- /dev/null +++ b/src/servers/search-server.ts @@ -0,0 +1,465 @@ +#!/usr/bin/env node + +/** + * Claude-mem MCP Search Server + * Exposes SessionSearch capabilities as MCP tools with search_result formatting + */ + +import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk'; +import { z } from 'zod'; +import { SessionSearch } from '../services/sqlite/SessionSearch.js'; +import { ObservationSearchResult, SessionSummarySearchResult } from '../services/sqlite/types.js'; + +// Initialize search instance +let search: SessionSearch; +try { + search = new SessionSearch(); +} catch (error: any) { + console.error('[search-server] Failed to initialize search:', error.message); + process.exit(1); +} + +/** + * Format observation as search_result with citations + */ +function formatObservationResult(obs: ObservationSearchResult, index: number) { + const source = `claude-mem://observation/${obs.id}`; + const title = obs.title || `Observation #${obs.id}`; + + // Build content from available fields + const contentParts: string[] = []; + + if (obs.subtitle) { + contentParts.push(`**${obs.subtitle}**`); + } + + if (obs.narrative) { + contentParts.push(obs.narrative); + } + + if (obs.text) { + contentParts.push(obs.text); + } + + // Add metadata + const metadata: string[] = []; + metadata.push(`Type: ${obs.type}`); + + if (obs.facts) { + try { + const facts = JSON.parse(obs.facts); + if (facts.length > 0) { + metadata.push(`Facts: ${facts.join('; ')}`); + } + } catch {} + } + + if (obs.concepts) { + try { + const concepts = JSON.parse(obs.concepts); + if (concepts.length > 0) { + metadata.push(`Concepts: ${concepts.join(', ')}`); + } + } catch {} + } + + if (obs.files_read || obs.files_modified) { + const files: string[] = []; + if (obs.files_read) { + try { + files.push(...JSON.parse(obs.files_read)); + } catch {} + } + if (obs.files_modified) { + try { + files.push(...JSON.parse(obs.files_modified)); + } catch {} + } + if (files.length > 0) { + metadata.push(`Files: ${[...new Set(files)].join(', ')}`); + } + } + + if (metadata.length > 0) { + contentParts.push(`\n---\n${metadata.join(' | ')}`); + } + + const content = contentParts.join('\n\n'); + + return { + type: 'search_result' as const, + source, + title, + content: [{ + type: 'text' as const, + text: content || 'No content available' + }], + citations: { enabled: true } + }; +} + +/** + * Format session summary as search_result with citations + */ +function formatSessionResult(session: SessionSummarySearchResult, index: number) { + const source = `claude-mem://session/${session.sdk_session_id}`; + const title = session.request || `Session ${session.sdk_session_id.substring(0, 8)}`; + + // Build content from available fields + const contentParts: string[] = []; + + if (session.completed) { + contentParts.push(`**Completed:** ${session.completed}`); + } + + if (session.learned) { + contentParts.push(`**Learned:** ${session.learned}`); + } + + if (session.investigated) { + contentParts.push(`**Investigated:** ${session.investigated}`); + } + + if (session.next_steps) { + contentParts.push(`**Next Steps:** ${session.next_steps}`); + } + + if (session.notes) { + contentParts.push(`**Notes:** ${session.notes}`); + } + + // Add metadata + const metadata: string[] = []; + + if (session.files_read || session.files_edited) { + const files: string[] = []; + if (session.files_read) { + try { + files.push(...JSON.parse(session.files_read)); + } catch {} + } + if (session.files_edited) { + try { + files.push(...JSON.parse(session.files_edited)); + } catch {} + } + if (files.length > 0) { + metadata.push(`Files: ${[...new Set(files)].join(', ')}`); + } + } + + const date = new Date(session.created_at_epoch).toLocaleDateString(); + metadata.push(`Date: ${date}`); + + if (metadata.length > 0) { + contentParts.push(`\n---\n${metadata.join(' | ')}`); + } + + const content = contentParts.join('\n\n'); + + return { + type: 'search_result' as const, + source, + title, + content: [{ + type: 'text' as const, + text: content || 'No content available' + }], + citations: { enabled: true } + }; +} + +/** + * Common filter schema + */ +const filterSchema = z.object({ + project: z.string().optional().describe('Filter by project name'), + type: z.union([ + z.enum(['decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change']), + z.array(z.enum(['decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change'])) + ]).optional().describe('Filter by observation type'), + concepts: z.union([z.string(), z.array(z.string())]).optional().describe('Filter by concept tags'), + files: z.union([z.string(), z.array(z.string())]).optional().describe('Filter by file paths (partial match)'), + dateRange: z.object({ + start: z.union([z.string(), z.number()]).optional().describe('Start date (ISO string or epoch)'), + end: z.union([z.string(), z.number()]).optional().describe('End date (ISO string or epoch)') + }).optional().describe('Filter by date range'), + limit: z.number().min(1).max(100).default(20).describe('Maximum number of results'), + offset: z.number().min(0).default(0).describe('Number of results to skip'), + orderBy: z.enum(['relevance', 'date_desc', 'date_asc']).default('relevance').describe('Sort order') +}); + +/** + * Create and start the MCP server + */ +const server = createSdkMcpServer({ + name: 'claude-mem-search', + version: '1.0.0', + tools: [ + // Tool 1: Search observations + tool( + 'search_observations', + 'Search observations using full-text search across titles, narratives, facts, and concepts', + { + query: z.string().describe('Search query for FTS5 full-text search'), + ...filterSchema.shape + }, + async (args) => { + try { + const { query, ...options } = args; + const results = search.searchObservations(query, options); + + if (results.length === 0) { + return { + content: [{ + type: 'text' as const, + text: `No observations found matching "${query}"` + }] + }; + } + + return { + content: results.map((obs, i) => formatObservationResult(obs, i)) + }; + } catch (error: any) { + return { + content: [{ + type: 'text' as const, + text: `Search failed: ${error.message}` + }] + }; + } + } + ), + + // Tool 2: Search sessions + tool( + 'search_sessions', + 'Search session summaries using full-text search across requests, completions, learnings, and notes', + { + query: z.string().describe('Search query for FTS5 full-text search'), + project: z.string().optional().describe('Filter by project name'), + dateRange: z.object({ + start: z.union([z.string(), z.number()]).optional(), + end: z.union([z.string(), z.number()]).optional() + }).optional().describe('Filter by date range'), + limit: z.number().min(1).max(100).default(20).describe('Maximum number of results'), + offset: z.number().min(0).default(0).describe('Number of results to skip'), + orderBy: z.enum(['relevance', 'date_desc', 'date_asc']).default('relevance').describe('Sort order') + }, + async (args) => { + try { + const { query, ...options } = args; + const results = search.searchSessions(query, options); + + if (results.length === 0) { + return { + content: [{ + type: 'text' as const, + text: `No sessions found matching "${query}"` + }] + }; + } + + return { + content: results.map((session, i) => formatSessionResult(session, i)) + }; + } catch (error: any) { + return { + content: [{ + type: 'text' as const, + text: `Search failed: ${error.message}` + }] + }; + } + } + ), + + // Tool 3: Find by concept + tool( + 'find_by_concept', + 'Find observations tagged with a specific concept', + { + concept: z.string().describe('Concept tag to search for'), + project: z.string().optional().describe('Filter by project name'), + dateRange: z.object({ + start: z.union([z.string(), z.number()]).optional(), + end: z.union([z.string(), z.number()]).optional() + }).optional().describe('Filter by date range') + }, + async (args) => { + try { + const { concept, ...filters } = args; + const results = search.findByConcept(concept, filters); + + if (results.length === 0) { + return { + content: [{ + type: 'text' as const, + text: `No observations found with concept "${concept}"` + }] + }; + } + + return { + content: results.map((obs, i) => formatObservationResult(obs, i)) + }; + } catch (error: any) { + return { + content: [{ + type: 'text' as const, + text: `Search failed: ${error.message}` + }] + }; + } + } + ), + + // Tool 4: Find by file + tool( + 'find_by_file', + 'Find observations and sessions that reference a specific file path', + { + filePath: z.string().describe('File path to search for (supports partial matching)'), + project: z.string().optional().describe('Filter by project name'), + dateRange: z.object({ + start: z.union([z.string(), z.number()]).optional(), + end: z.union([z.string(), z.number()]).optional() + }).optional().describe('Filter by date range') + }, + async (args) => { + try { + const { filePath, ...filters } = args; + const results = search.findByFile(filePath, filters); + + const totalResults = results.observations.length + results.sessions.length; + + if (totalResults === 0) { + return { + content: [{ + type: 'text' as const, + text: `No results found for file "${filePath}"` + }] + }; + } + + const content: any[] = []; + + // Add observations + results.observations.forEach((obs, i) => { + content.push(formatObservationResult(obs, i)); + }); + + // Add sessions + results.sessions.forEach((session, i) => { + content.push(formatSessionResult(session, i + results.observations.length)); + }); + + return { content }; + } catch (error: any) { + return { + content: [{ + type: 'text' as const, + text: `Search failed: ${error.message}` + }] + }; + } + } + ), + + // Tool 5: Find by type + tool( + 'find_by_type', + 'Find observations of a specific type (decision, bugfix, feature, refactor, discovery, change)', + { + type: z.union([ + z.enum(['decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change']), + z.array(z.enum(['decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change'])) + ]).describe('Observation type(s) to filter by'), + project: z.string().optional().describe('Filter by project name'), + dateRange: z.object({ + start: z.union([z.string(), z.number()]).optional(), + end: z.union([z.string(), z.number()]).optional() + }).optional().describe('Filter by date range') + }, + async (args) => { + try { + const { type, ...filters } = args; + const results = search.findByType(type, filters); + + if (results.length === 0) { + const typeStr = Array.isArray(type) ? type.join(', ') : type; + return { + content: [{ + type: 'text' as const, + text: `No observations found with type "${typeStr}"` + }] + }; + } + + return { + content: results.map((obs, i) => formatObservationResult(obs, i)) + }; + } catch (error: any) { + return { + content: [{ + type: 'text' as const, + text: `Search failed: ${error.message}` + }] + }; + } + } + ), + + // Tool 6: Advanced search + tool( + 'advanced_search', + 'Advanced search combining full-text search with structured filters across both observations and sessions', + { + textQuery: z.string().optional().describe('Optional text query for FTS5 search'), + searchSessions: z.boolean().default(true).describe('Include session summaries in results'), + ...filterSchema.shape + }, + async (args) => { + try { + const results = search.advancedSearch(args); + + const totalResults = results.observations.length + results.sessions.length; + + if (totalResults === 0) { + return { + content: [{ + type: 'text' as const, + text: 'No results found matching the search criteria' + }] + }; + } + + const content: any[] = []; + + // Add observations + results.observations.forEach((obs, i) => { + content.push(formatObservationResult(obs, i)); + }); + + // Add sessions + results.sessions.forEach((session, i) => { + content.push(formatSessionResult(session, i + results.observations.length)); + }); + + return { content }; + } catch (error: any) { + return { + content: [{ + type: 'text' as const, + text: `Search failed: ${error.message}` + }] + }; + } + } + ) + ] +}); + +// Start the server +console.error('[search-server] Starting claude-mem search server...'); diff --git a/test-socket.js b/test-socket.js deleted file mode 100644 index 755ac4d3..00000000 --- a/test-socket.js +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bun -import net from 'net'; -import { existsSync } from 'fs'; - -const socketPath = '/Users/alexnewman/.claude-mem/test-bun.sock'; - -const server = net.createServer(() => {}); - -server.listen(socketPath, () => { - console.log('Server listening'); - console.log('existsSync says:', existsSync(socketPath)); - console.log('Checking with ls...'); -}); - -server.on('error', (err) => { - console.error('Error:', err); - process.exit(1); -}); diff --git a/test-worker.sh b/test-worker.sh deleted file mode 100755 index f2303d00..00000000 --- a/test-worker.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash -set -e - -echo "Creating session..." -echo '{"session_id":"test-socket-789","cwd":"/Users/alexnewman/Scripts/claude-mem","prompt":"testing"}' | bun src/bin/cli.ts new - -sleep 1 - -SESSION_ID=$(sqlite3 ~/.claude-mem/claude-mem.db "SELECT id FROM sdk_sessions ORDER BY id DESC LIMIT 1;") -echo "Session ID: $SESSION_ID" - -echo "Starting worker..." -bun src/sdk/worker.ts $SESSION_ID 2>&1 & -WORKER_PID=$! -echo "Worker PID: $WORKER_PID" - -sleep 3 - -if ps -p $WORKER_PID > /dev/null 2>&1; then - echo "โœ… Worker is RUNNING!" - if [ -e ~/.claude-mem/worker-$SESSION_ID.sock ]; then - echo "โœ… Socket file exists!" - ls -la ~/.claude-mem/worker-$SESSION_ID.sock - else - echo "โŒ Socket file NOT found" - fi - - # Try to send a message - echo "Sending test observation..." - echo '{"type":"observation","tool_name":"TestTool","tool_input":"{}","tool_output":"{}"}' | nc -U ~/.claude-mem/worker-$SESSION_ID.sock - echo "Message sent!" - - sleep 2 - - # Send finalize - echo "Sending finalize..." - echo '{"type":"finalize"}' | nc -U ~/.claude-mem/worker-$SESSION_ID.sock - - sleep 2 - if ps -p $WORKER_PID > /dev/null 2>&1; then - echo "โš ๏ธ Worker still running after finalize" - kill $WORKER_PID - else - echo "โœ… Worker exited cleanly after finalize" - fi -else - echo "โŒ Worker exited prematurely" -fi diff --git a/tests/database-schema.test.ts b/tests/database-schema.test.ts deleted file mode 100644 index 78c34139..00000000 --- a/tests/database-schema.test.ts +++ /dev/null @@ -1,203 +0,0 @@ -#!/usr/bin/env bun -/** - * Test script for Phase 1 implementation - * Tests database schema and hook functions - */ - -import { DatabaseManager, migrations } from '../src/services/sqlite/index.js'; -import { HooksDatabase } from '../src/services/sqlite/HooksDatabase.js'; -import path from 'path'; -import fs from 'fs'; - -async function testDatabaseSchema() { - console.log('๐Ÿงช Testing Database Schema...\n'); - - // Initialize database with migrations - const manager = DatabaseManager.getInstance(); - for (const migration of migrations) { - manager.registerMigration(migration); - } - - const db = await manager.initialize(); - console.log('โœ… Database initialized'); - - // Check that migration 004 was applied - const version = manager.getCurrentVersion(); - console.log(`โœ… Current schema version: ${version}`); - - if (version < 4) { - console.error('โŒ Migration 004 was not applied!'); - process.exit(1); - } - - // Verify tables exist - const tables = [ - 'sdk_sessions', - 'observation_queue', - 'observations', - 'session_summaries' - ]; - - for (const table of tables) { - const query = db.query(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`); - const result = query.get(table); - if (!result) { - console.error(`โŒ Table ${table} does not exist!`); - process.exit(1); - } - console.log(`โœ… Table ${table} exists`); - } - - console.log('\nโœ… All schema tests passed!\n'); - // Don't close yet - keep connection for other tests -} - -async function testHooksDatabase() { - console.log('๐Ÿงช Testing Hooks Database...\n'); - - const hooksDb = new HooksDatabase(); - - // Clean up any existing test data first - try { - const manager = DatabaseManager.getInstance(); - const db = manager.getConnection(); - db.run('DELETE FROM session_summaries WHERE project = ?', ['test-project']); - db.run('DELETE FROM observations WHERE project = ?', ['test-project']); - db.run('DELETE FROM observation_queue WHERE sdk_session_id LIKE ?', ['test-sdk-session-id%']); - db.run('DELETE FROM sdk_sessions WHERE project = ? OR claude_session_id = ?', ['test-project', 'test-claude-session-1']); - } catch (error) { - // Ignore cleanup errors - } - - // Test creating an SDK session - const sessionId = hooksDb.createSDKSession( - 'test-claude-session-1', - 'test-project', - 'Test user prompt' - ); - console.log(`โœ… Created SDK session with ID: ${sessionId}`); - - // Test finding active session - const found = hooksDb.findActiveSDKSession('test-claude-session-1'); - if (!found || found.id !== sessionId) { - console.error('โŒ Could not find created session!'); - process.exit(1); - } - console.log(`โœ… Found active session: ${found.project}`); - - // Test updating SDK session ID - hooksDb.updateSDKSessionId(sessionId, 'test-sdk-session-id'); - const updated = hooksDb.findActiveSDKSession('test-claude-session-1'); - if (!updated || updated.sdk_session_id !== 'test-sdk-session-id') { - console.error('โŒ SDK session ID was not updated!'); - process.exit(1); - } - console.log(`โœ… Updated SDK session ID: ${updated.sdk_session_id}`); - - // Test queuing observation - hooksDb.queueObservation( - 'test-sdk-session-id', - 'Read', - '{"file_path": "test.ts"}', - '{"content": "test content"}' - ); - console.log('โœ… Queued observation'); - - // Test getting pending observations - const pending = hooksDb.getPendingObservations('test-sdk-session-id', 10); - if (pending.length !== 1) { - console.error('โŒ Expected 1 pending observation!'); - process.exit(1); - } - console.log(`โœ… Found ${pending.length} pending observation(s)`); - - // Test marking observation as processed - hooksDb.markObservationProcessed(pending[0].id); - const stillPending = hooksDb.getPendingObservations('test-sdk-session-id', 10); - if (stillPending.length !== 0) { - console.error('โŒ Observation was not marked as processed!'); - process.exit(1); - } - console.log('โœ… Marked observation as processed'); - - // Test storing observation - hooksDb.storeObservation( - 'test-sdk-session-id', - 'test-project', - 'feature', - 'Implemented test feature' - ); - console.log('โœ… Stored observation'); - - // Test storing summary - hooksDb.storeSummary( - 'test-sdk-session-id', - 'test-project', - { - request: 'Test request', - completed: 'Test completed', - learned: 'Test learned', - next_steps: 'Test next steps', - files_edited: '["test.ts"]' - } - ); - console.log('โœ… Stored summary'); - - // Test getting recent summaries - const summaries = hooksDb.getRecentSummaries('test-project', 10); - if (summaries.length !== 1) { - console.error('โŒ Expected 1 summary!'); - process.exit(1); - } - console.log(`โœ… Found ${summaries.length} summary(ies)`); - console.log(` Request: ${summaries[0].request}`); - - // Test marking session as completed - hooksDb.markSessionCompleted(sessionId); - const completed = hooksDb.findActiveSDKSession('test-claude-session-1'); - if (completed) { - console.error('โŒ Session should not be active after completion!'); - process.exit(1); - } - console.log('โœ… Marked session as completed'); - - hooksDb.close(); - console.log('\nโœ… All hooks database tests passed!\n'); -} - -async function cleanup() { - console.log('๐Ÿงน Cleaning up test data...\n'); - - try { - const manager = DatabaseManager.getInstance(); - const db = manager.getConnection(); - - // Clean up test data - db.run('DELETE FROM session_summaries WHERE project = ?', ['test-project']); - db.run('DELETE FROM observations WHERE project = ?', ['test-project']); - db.run('DELETE FROM observation_queue WHERE sdk_session_id = ?', ['test-sdk-session-id']); - db.run('DELETE FROM sdk_sessions WHERE project = ?', ['test-project']); - - console.log('โœ… Test data cleaned up\n'); - manager.close(); - } catch (error: any) { - // Database might already be closed, that's okay - console.log('โœ… Test data cleanup skipped (database already closed)\n'); - } -} - -// Run tests -(async () => { - try { - await testDatabaseSchema(); - await testHooksDatabase(); - await cleanup(); - - console.log('๐ŸŽ‰ Phase 1 implementation tests passed!\n'); - process.exit(0); - } catch (error: any) { - console.error(`\nโŒ Test failed: ${error.message}`); - console.error(error.stack); - process.exit(1); - } -})(); diff --git a/tests/hooks-database-integration.test.ts b/tests/hooks-database-integration.test.ts deleted file mode 100644 index ba567ec7..00000000 --- a/tests/hooks-database-integration.test.ts +++ /dev/null @@ -1,253 +0,0 @@ -#!/usr/bin/env bun -/** - * Phase 3 Integration Tests - * Tests the complete hook lifecycle and end-to-end integration - * - * Note: These tests verify database integration rather than calling hooks directly - * since hooks call process.exit() which would terminate the test process - */ - -import { describe, it, expect, beforeAll, afterAll } from 'bun:test'; -import { HooksDatabase } from '../src/services/sqlite/HooksDatabase.js'; -import { DatabaseManager } from '../src/services/sqlite/Database.js'; -import { migrations } from '../src/services/sqlite/migrations.js'; -import fs from 'fs'; -import path from 'path'; - -// Test database path -const TEST_DB_DIR = '/tmp/claude-mem-phase3-test'; -const TEST_DB_PATH = path.join(TEST_DB_DIR, 'claude-mem.db'); - -describe('Phase 3: Hook Database Integration', () => { - beforeAll(async () => { - // Create test directory - fs.mkdirSync(TEST_DB_DIR, { recursive: true }); - - // Set test environment - process.env.CLAUDE_MEM_DATA_DIR = TEST_DB_DIR; - - // Initialize database with migrations - const dbManager = DatabaseManager.getInstance(); - migrations.forEach(m => dbManager.registerMigration(m)); - await dbManager.initialize(); - dbManager.close(); - }); - - afterAll(() => { - // Clean up test database and all files - if (fs.existsSync(TEST_DB_DIR)) { - const files = fs.readdirSync(TEST_DB_DIR); - files.forEach(file => { - fs.unlinkSync(path.join(TEST_DB_DIR, file)); - }); - fs.rmdirSync(TEST_DB_DIR); - } - }); - - describe('HooksDatabase - Session Management', () => { - it('should create and find SDK sessions', () => { - const db = new HooksDatabase(); - - const sessionId = db.createSDKSession( - 'test-claude-session-1', - 'my-project', - 'Implement authentication' - ); - - expect(sessionId).toBeGreaterThan(0); - - const found = db.findActiveSDKSession('test-claude-session-1'); - expect(found).not.toBeNull(); - expect(found!.project).toBe('my-project'); - expect(found!.id).toBe(sessionId); - - db.close(); - }); - - it('should update SDK session ID', () => { - const db = new HooksDatabase(); - - const sessionId = db.createSDKSession( - 'test-claude-session-2', - 'my-project', - 'Test prompt' - ); - - db.updateSDKSessionId(sessionId, 'sdk-session-abc'); - - const found = db.findActiveSDKSession('test-claude-session-2'); - expect(found!.sdk_session_id).toBe('sdk-session-abc'); - - db.close(); - }); - - it('should mark session as completed', () => { - const db = new HooksDatabase(); - - const sessionId = db.createSDKSession( - 'test-claude-session-3', - 'my-project', - 'Test prompt' - ); - - db.markSessionCompleted(sessionId); - - const found = db.findActiveSDKSession('test-claude-session-3'); - expect(found).toBeNull(); // Should not find active session - - db.close(); - }); - }); - - describe('HooksDatabase - Observation Queue', () => { - it('should queue and retrieve observations', () => { - const db = new HooksDatabase(); - - // Create session first (FK constraint requirement) - const sessionId = db.createSDKSession('claude-queue-1', 'test-project', 'Test'); - db.updateSDKSessionId(sessionId, 'sdk-queue-test-1'); - - db.queueObservation( - 'sdk-queue-test-1', - 'Read', - JSON.stringify({ file_path: 'src/app.ts' }), - JSON.stringify({ content: 'test content' }) - ); - - const pending = db.getPendingObservations('sdk-queue-test-1', 10); - expect(pending).toHaveLength(1); - expect(pending[0].tool_name).toBe('Read'); - - db.close(); - }); - - it('should mark observations as processed', () => { - const db = new HooksDatabase(); - - // Create session first (FK constraint requirement) - const sessionId = db.createSDKSession('claude-queue-2', 'test-project', 'Test'); - db.updateSDKSessionId(sessionId, 'sdk-queue-test-2'); - - db.queueObservation( - 'sdk-queue-test-2', - 'Edit', - JSON.stringify({ file_path: 'src/app.ts' }), - JSON.stringify({ success: true }) - ); - - const pending = db.getPendingObservations('sdk-queue-test-2', 10); - expect(pending).toHaveLength(1); - - db.markObservationProcessed(pending[0].id); - - const stillPending = db.getPendingObservations('sdk-queue-test-2', 10); - expect(stillPending).toHaveLength(0); - - db.close(); - }); - - it('should queue FINALIZE messages', () => { - const db = new HooksDatabase(); - - // Create session first (FK constraint requirement) - const sessionId = db.createSDKSession('claude-finalize', 'test-project', 'Test'); - db.updateSDKSessionId(sessionId, 'sdk-finalize-test'); - - db.queueObservation('sdk-finalize-test', 'FINALIZE', '{}', '{}'); - - const pending = db.getPendingObservations('sdk-finalize-test', 10); - expect(pending).toHaveLength(1); - expect(pending[0].tool_name).toBe('FINALIZE'); - - db.close(); - }); - }); - - describe('HooksDatabase - Observations Storage', () => { - it('should store observations from SDK', () => { - const db = new HooksDatabase(); - - // Create session first (FK constraint requirement) - const sessionId = db.createSDKSession('claude-obs-1', 'my-project', 'Test'); - db.updateSDKSessionId(sessionId, 'sdk-obs-test-1'); - - db.storeObservation( - 'sdk-obs-test-1', - 'my-project', - 'feature', - 'Implemented JWT authentication' - ); - - const dbInstance = (db as any).db; - const query = dbInstance.query('SELECT * FROM observations WHERE sdk_session_id = ?'); - const observations = query.all('sdk-obs-test-1'); - - expect(observations).toHaveLength(1); - expect(observations[0].type).toBe('feature'); - expect(observations[0].text).toBe('Implemented JWT authentication'); - - db.close(); - }); - }); - - describe('HooksDatabase - Summaries', () => { - it('should store and retrieve summaries', () => { - const db = new HooksDatabase(); - - // Create session first (FK constraint requirement) - const sessionId = db.createSDKSession('claude-summary-1', 'my-project', 'Test'); - db.updateSDKSessionId(sessionId, 'sdk-summary-test-1'); - - db.storeSummary('sdk-summary-test-1', 'my-project', { - request: 'Implement authentication', - investigated: 'Existing patterns', - learned: 'No JWT support', - completed: 'Implemented JWT', - next_steps: 'Add tests', - files_read: JSON.stringify(['src/auth.ts']), - files_edited: JSON.stringify(['src/auth.ts']), - notes: 'Used bcrypt' - }); - - const summaries = db.getRecentSummaries('my-project', 10); - expect(summaries.length).toBeGreaterThan(0); - - const summary = summaries.find(s => s.request === 'Implement authentication'); - expect(summary).not.toBeUndefined(); - expect(summary!.completed).toBe('Implemented JWT'); - - db.close(); - }); - - it('should return recent summaries only for specific project', () => { - const db = new HooksDatabase(); - - // Create sessions first (FK constraint requirement) - const session1Id = db.createSDKSession('claude-proj-1', 'project-1', 'Test'); - db.updateSDKSessionId(session1Id, 'sdk-proj1'); - - const session2Id = db.createSDKSession('claude-proj-2', 'project-2', 'Test'); - db.updateSDKSessionId(session2Id, 'sdk-proj2'); - - db.storeSummary('sdk-proj1', 'project-1', { - request: 'Feature for project 1', - completed: 'Done' - }); - - db.storeSummary('sdk-proj2', 'project-2', { - request: 'Feature for project 2', - completed: 'Done' - }); - - const proj1Summaries = db.getRecentSummaries('project-1', 10); - const proj2Summaries = db.getRecentSummaries('project-2', 10); - - expect(proj1Summaries.every(s => s.request?.includes('project 1'))).toBe(true); - expect(proj2Summaries.every(s => s.request?.includes('project 2'))).toBe(true); - - db.close(); - }); - }); -}); - -console.log('Running Phase 3 Integration Tests...'); diff --git a/tests/sdk-prompts-parser.test.ts b/tests/sdk-prompts-parser.test.ts deleted file mode 100644 index ef1c69c0..00000000 --- a/tests/sdk-prompts-parser.test.ts +++ /dev/null @@ -1,336 +0,0 @@ -#!/usr/bin/env bun -/** - * Phase 2 End-to-End Tests - * Tests SDK prompts, parser, and integration with HooksDatabase - */ - -import { describe, it, expect, beforeAll, afterAll } from 'bun:test'; -import { buildInitPrompt, buildObservationPrompt, buildFinalizePrompt } from '../src/sdk/prompts.js'; -import { parseObservations, parseSummary } from '../src/sdk/parser.js'; -import { HooksDatabase } from '../src/services/sqlite/HooksDatabase.js'; -import { DatabaseManager } from '../src/services/sqlite/Database.js'; -import { migrations } from '../src/services/sqlite/migrations.js'; -import fs from 'fs'; -import path from 'path'; - -// Test database path -const TEST_DB_DIR = '/tmp/claude-mem-test'; -const TEST_DB_PATH = path.join(TEST_DB_DIR, 'claude-mem.db'); - -describe('SDK Prompts', () => { - it('should build init prompt with all required sections', () => { - const prompt = buildInitPrompt('test-project', 'session-123', 'Implement JWT auth'); - - expect(prompt).toContain('test-project'); - expect(prompt).toContain('session-123'); - expect(prompt).toContain('Implement JWT auth'); - expect(prompt).toContain('SESSION CONTEXT'); - expect(prompt).toContain('YOUR ROLE'); - expect(prompt).toContain('WHAT TO CAPTURE'); - expect(prompt).toContain('HOW TO STORE OBSERVATIONS'); - expect(prompt).toContain(''); - expect(prompt).toContain(''); - expect(prompt).toContain(''); - }); - - it('should build observation prompt with tool details', () => { - const obs = { - id: 1, - tool_name: 'Edit', - tool_input: JSON.stringify({ file: 'src/auth.ts' }), - tool_output: JSON.stringify({ success: true }), - created_at_epoch: Date.now() - }; - - const prompt = buildObservationPrompt(obs); - - expect(prompt).toContain('TOOL OBSERVATION'); - expect(prompt).toContain('Edit'); - expect(prompt).toContain('src/auth.ts'); - expect(prompt).toContain('ANALYSIS TASK'); - }); - - it('should build finalize prompt with session context', () => { - const session = { - id: 1, - sdk_session_id: 'sdk-123', - project: 'test-project', - user_prompt: 'Implement JWT auth' - }; - - const prompt = buildFinalizePrompt(session); - - expect(prompt).toContain('SESSION ENDING'); - expect(prompt).toContain('FINAL TASK'); - expect(prompt).toContain(''); - expect(prompt).toContain(''); - expect(prompt).toContain(''); - }); -}); - -describe('XML Parser', () => { - describe('parseObservations', () => { - it('should parse single observation', () => { - const text = ` - - feature - Implemented JWT token refresh flow - - `; - - const observations = parseObservations(text); - - expect(observations).toHaveLength(1); - expect(observations[0].type).toBe('feature'); - expect(observations[0].text).toBe('Implemented JWT token refresh flow'); - }); - - it('should parse multiple observations', () => { - const text = ` - - feature - Implemented JWT token refresh flow - - - bugfix - Fixed race condition in auth middleware - - `; - - const observations = parseObservations(text); - - expect(observations).toHaveLength(2); - expect(observations[0].type).toBe('feature'); - expect(observations[1].type).toBe('bugfix'); - }); - - it('should skip observations with invalid types', () => { - const text = ` - - invalid-type - This should be skipped - - - feature - This should be kept - - `; - - const observations = parseObservations(text); - - expect(observations).toHaveLength(1); - expect(observations[0].type).toBe('feature'); - }); - - it('should handle observations with surrounding text', () => { - const text = ` - I analyzed the code and found something interesting: - - - discovery - API rate limit is 100 requests per minute - - - This is an important finding. - `; - - const observations = parseObservations(text); - - expect(observations).toHaveLength(1); - expect(observations[0].type).toBe('discovery'); - }); - }); - - describe('parseSummary', () => { - it('should parse complete summary with all fields', () => { - const text = ` - - Implement JWT authentication system - Existing auth middleware, session management - Current system uses session cookies; no JWT support - Implemented JWT token + refresh flow with 7-day expiry - Add token revocation API endpoint; write integration tests - - src/auth.ts - src/middleware/session.ts - - - src/auth.ts - src/middleware/auth.ts - - Token secret stored in .env - - `; - - const summary = parseSummary(text); - - expect(summary).not.toBeNull(); - expect(summary!.request).toBe('Implement JWT authentication system'); - expect(summary!.investigated).toBe('Existing auth middleware, session management'); - expect(summary!.learned).toBe('Current system uses session cookies; no JWT support'); - expect(summary!.completed).toBe('Implemented JWT token + refresh flow with 7-day expiry'); - expect(summary!.next_steps).toBe('Add token revocation API endpoint; write integration tests'); - expect(summary!.files_read).toEqual(['src/auth.ts', 'src/middleware/session.ts']); - expect(summary!.files_edited).toEqual(['src/auth.ts', 'src/middleware/auth.ts']); - expect(summary!.notes).toBe('Token secret stored in .env'); - }); - - it('should handle empty file arrays', () => { - const text = ` - - Research API documentation - API endpoints and authentication methods - API uses OAuth 2.0 - Documented authentication flow - Implement OAuth client - - - Documentation is incomplete - - `; - - const summary = parseSummary(text); - - expect(summary).not.toBeNull(); - expect(summary!.files_read).toEqual([]); - expect(summary!.files_edited).toEqual([]); - }); - - it('should return null if required fields are missing', () => { - const text = ` - - Implement JWT authentication system - Existing auth middleware - - `; - - const summary = parseSummary(text); - - expect(summary).toBeNull(); - }); - - it('should return null if no summary block found', () => { - const text = 'This is just regular text without a summary.'; - - const summary = parseSummary(text); - - expect(summary).toBeNull(); - }); - }); -}); - -describe('HooksDatabase Integration', () => { - let db: HooksDatabase; - - beforeAll(async () => { - // Create test directory - fs.mkdirSync(TEST_DB_DIR, { recursive: true }); - - // Set test environment - process.env.CLAUDE_MEM_DATA_DIR = TEST_DB_DIR; - - // Initialize database with migrations - const dbManager = DatabaseManager.getInstance(); - migrations.forEach(m => dbManager.registerMigration(m)); - await dbManager.initialize(); - dbManager.close(); - }); - - afterAll(() => { - // Clean up test database and all files - if (fs.existsSync(TEST_DB_DIR)) { - const files = fs.readdirSync(TEST_DB_DIR); - files.forEach(file => { - fs.unlinkSync(path.join(TEST_DB_DIR, file)); - }); - fs.rmdirSync(TEST_DB_DIR); - } - }); - - it('should store and retrieve observations', () => { - db = new HooksDatabase(); - - // Create session - const sessionId = db.createSDKSession('claude-123', 'test-project', 'Test prompt'); - db.updateSDKSessionId(sessionId, 'sdk-123'); - - // Store observation - db.storeObservation('sdk-123', 'test-project', 'feature', 'Implemented JWT auth'); - - // Verify storage - const dbInstance = (db as any).db; - const query = dbInstance.query('SELECT * FROM observations WHERE sdk_session_id = ?'); - const observations = query.all('sdk-123'); - - expect(observations).toHaveLength(1); - expect(observations[0].type).toBe('feature'); - expect(observations[0].text).toBe('Implemented JWT auth'); - expect(observations[0].project).toBe('test-project'); - - db.close(); - }); - - it('should store and retrieve summaries', () => { - db = new HooksDatabase(); - - // Create session - const sessionId = db.createSDKSession('claude-456', 'test-project', 'Test prompt'); - db.updateSDKSessionId(sessionId, 'sdk-456'); - - // Store summary - const summaryData = { - request: 'Implement feature', - investigated: 'Existing code', - learned: 'Found patterns', - completed: 'Implemented feature', - next_steps: 'Add tests', - files_read: JSON.stringify(['src/app.ts']), - files_edited: JSON.stringify(['src/app.ts']), - notes: 'Used TypeScript' - }; - - db.storeSummary('sdk-456', 'test-project', summaryData); - - // Verify storage - const summaries = db.getRecentSummaries('test-project', 10); - - expect(summaries).toHaveLength(1); - expect(summaries[0].request).toBe('Implement feature'); - expect(summaries[0].completed).toBe('Implemented feature'); - - db.close(); - }); - - it('should queue and process observations', () => { - db = new HooksDatabase(); - - // Create session - const sessionId = db.createSDKSession('claude-789', 'test-project', 'Test prompt'); - db.updateSDKSessionId(sessionId, 'sdk-789'); - - // Queue observation - db.queueObservation( - 'sdk-789', - 'Edit', - JSON.stringify({ file: 'src/auth.ts' }), - JSON.stringify({ success: true }) - ); - - // Get pending observations - const pending = db.getPendingObservations('sdk-789', 10); - - expect(pending).toHaveLength(1); - expect(pending[0].tool_name).toBe('Edit'); - - // Mark as processed - db.markObservationProcessed(pending[0].id); - - // Verify no pending observations - const pendingAfter = db.getPendingObservations('sdk-789', 10); - expect(pendingAfter).toHaveLength(0); - - db.close(); - }); -}); - -console.log('Running Phase 2 Tests...'); diff --git a/tests/session-lifecycle.test.ts b/tests/session-lifecycle.test.ts deleted file mode 100644 index a85d25d4..00000000 --- a/tests/session-lifecycle.test.ts +++ /dev/null @@ -1,286 +0,0 @@ -#!/usr/bin/env bun -/** - * Phase 3 End-to-End Lifecycle Test - * Simulates a complete Claude Code session lifecycle through database operations - * - * This test verifies that all hook database operations work together correctly - * to support a full session from initialization to summary generation - */ - -import { describe, it, expect, beforeAll, afterAll } from 'bun:test'; -import { HooksDatabase } from '../src/services/sqlite/HooksDatabase.js'; -import { DatabaseManager } from '../src/services/sqlite/Database.js'; -import { migrations } from '../src/services/sqlite/migrations.js'; -import fs from 'fs'; -import path from 'path'; - -// Test database path -const TEST_DB_DIR = '/tmp/claude-mem-e2e-test'; - -describe('Phase 3: End-to-End Lifecycle', () => { - beforeAll(async () => { - // Clean up any existing test directory - if (fs.existsSync(TEST_DB_DIR)) { - const files = fs.readdirSync(TEST_DB_DIR); - files.forEach(file => { - fs.unlinkSync(path.join(TEST_DB_DIR, file)); - }); - fs.rmdirSync(TEST_DB_DIR); - } - - // Create test directory - fs.mkdirSync(TEST_DB_DIR, { recursive: true }); - - // Set test environment - process.env.CLAUDE_MEM_DATA_DIR = TEST_DB_DIR; - - // Initialize database with migrations - const dbManager = DatabaseManager.getInstance(); - migrations.forEach(m => dbManager.registerMigration(m)); - await dbManager.initialize(); - dbManager.close(); - }); - - afterAll(() => { - // Clean up test database and all files - if (fs.existsSync(TEST_DB_DIR)) { - const files = fs.readdirSync(TEST_DB_DIR); - files.forEach(file => { - fs.unlinkSync(path.join(TEST_DB_DIR, file)); - }); - fs.rmdirSync(TEST_DB_DIR); - } - }); - - it('should complete full session lifecycle', () => { - const claudeSessionId = 'e2e-session-1'; - const project = 'my-app'; - const userPrompt = 'Implement user authentication with JWT'; - - // Step 1: Create SDK session (simulates newHook) - console.log('\n=== Step 1: Initialize Session ==='); - let db = new HooksDatabase(); - const sessionId = db.createSDKSession(claudeSessionId, project, userPrompt); - expect(sessionId).toBeGreaterThan(0); - - const session = db.findActiveSDKSession(claudeSessionId); - expect(session).not.toBeNull(); - expect(session!.project).toBe(project); - - // Simulate SDK worker capturing session ID - db.updateSDKSessionId(sessionId, 'sdk-e2e-1'); - db.close(); - - // Step 2: Queue multiple observations (simulates saveHook) - console.log('\n=== Step 2: Queue Observations ==='); - db = new HooksDatabase(); - - const observations = [ - { tool: 'Read', input: { file_path: 'src/auth.ts' }, output: { content: 'export function login() {}' } }, - { tool: 'Edit', input: { file_path: 'src/auth.ts' }, output: { success: true } }, - { tool: 'Write', input: { file_path: 'src/middleware/auth.ts' }, output: { success: true } }, - { tool: 'Bash', input: { command: 'npm install jsonwebtoken' }, output: { stdout: 'added 1 package' } }, - { tool: 'Read', input: { file_path: 'package.json' }, output: { content: '{"dependencies": {}}' } } - ]; - - for (const obs of observations) { - db.queueObservation( - 'sdk-e2e-1', - obs.tool, - JSON.stringify(obs.input), - JSON.stringify(obs.output) - ); - } - - const pending = db.getPendingObservations('sdk-e2e-1', 100); - expect(pending.length).toBe(observations.length); - db.close(); - - // Step 3: Process observations (simulates SDK worker) - console.log('\n=== Step 3: Process Observations ==='); - db = new HooksDatabase(); - - for (const obs of pending) { - // Simulate SDK extracting meaningful observations - if (obs.tool_name === 'Edit' || obs.tool_name === 'Write') { - db.storeObservation( - 'sdk-e2e-1', - project, - 'feature', - `Modified ${JSON.parse(obs.tool_input).file_path}` - ); - } - - db.markObservationProcessed(obs.id); - } - - const stillPending = db.getPendingObservations('sdk-e2e-1', 100); - expect(stillPending.length).toBe(0); - db.close(); - - // Step 4: Queue FINALIZE message (simulates summaryHook) - console.log('\n=== Step 4: Queue FINALIZE ==='); - db = new HooksDatabase(); - db.queueObservation('sdk-e2e-1', 'FINALIZE', '{}', '{}'); - - const finalizeMsg = db.getPendingObservations('sdk-e2e-1', 100); - expect(finalizeMsg.length).toBe(1); - expect(finalizeMsg[0].tool_name).toBe('FINALIZE'); - db.close(); - - // Step 5: Generate summary (simulates SDK worker finalization) - console.log('\n=== Step 5: Generate Summary ==='); - db = new HooksDatabase(); - - db.storeSummary('sdk-e2e-1', project, { - request: 'Implement user authentication with JWT', - investigated: 'Existing auth.ts file and authentication patterns', - learned: 'Current system had basic login function without JWT support', - completed: 'Implemented JWT-based authentication with login function and auth middleware', - next_steps: 'Add token refresh mechanism and write unit tests', - files_read: JSON.stringify(['src/auth.ts', 'package.json']), - files_edited: JSON.stringify(['src/auth.ts', 'src/middleware/auth.ts']), - notes: 'Installed jsonwebtoken package for JWT support' - }); - - db.markSessionCompleted(sessionId); - db.close(); - - // Verify summary stored - db = new HooksDatabase(); - const summaries = db.getRecentSummaries(project, 10); - expect(summaries.length).toBe(1); - expect(summaries[0].request).toBe('Implement user authentication with JWT'); - expect(summaries[0].completed).toContain('JWT-based authentication'); - db.close(); - - // Step 6: Retrieve context for next session (simulates contextHook) - console.log('\n=== Step 6: Retrieve Context ==='); - db = new HooksDatabase(); - const contextSummaries = db.getRecentSummaries(project, 5); - - expect(contextSummaries.length).toBeGreaterThan(0); - expect(contextSummaries[0].request).toBe('Implement user authentication with JWT'); - expect(contextSummaries[0].files_edited).toContain('src/auth.ts'); - - // Verify session is no longer active - const completedSession = db.findActiveSDKSession(claudeSessionId); - expect(completedSession).toBeNull(); - - db.close(); - - console.log('\nโœ… End-to-end lifecycle test passed!'); - }); - - it('should handle performance requirements (< 50ms per operation)', () => { - const db = new HooksDatabase(); - - // Create session - const sessionId = db.createSDKSession('perf-test', 'perf-project', 'Test'); - db.updateSDKSessionId(sessionId, 'sdk-perf-1'); - - // Test queue observation performance - const iterations = 20; - const times: number[] = []; - - for (let i = 0; i < iterations; i++) { - const start = performance.now(); - - db.queueObservation( - 'sdk-perf-1', - 'Read', - JSON.stringify({ file_path: `test-${i}.ts` }), - JSON.stringify({ content: 'test' }) - ); - - const duration = performance.now() - start; - times.push(duration); - } - - const avgTime = times.reduce((a, b) => a + b, 0) / times.length; - const maxTime = Math.max(...times); - - console.log(`\nPerformance Results:`); - console.log(` Average time: ${avgTime.toFixed(2)}ms`); - console.log(` Max time: ${maxTime.toFixed(2)}ms`); - - // Should be well under 50ms requirement - expect(avgTime).toBeLessThan(50); - expect(maxTime).toBeLessThan(100); - - db.close(); - }); - - it('should handle interrupted sessions gracefully', () => { - const db = new HooksDatabase(); - - // Create session - const sessionId = db.createSDKSession( - 'interrupt-test', - 'interrupt-project', - 'Test interruption' - ); - db.updateSDKSessionId(sessionId, 'sdk-interrupt-1'); - - // Queue some observations - for (let i = 0; i < 5; i++) { - db.queueObservation( - 'sdk-interrupt-1', - 'Read', - JSON.stringify({ file_path: `file-${i}.ts` }), - JSON.stringify({ content: `content ${i}` }) - ); - } - - // Simulate user interruption (no FINALIZE message) - // Observations should remain in queue - const pending = db.getPendingObservations('sdk-interrupt-1', 100); - expect(pending.length).toBe(5); - - // Session should still be active - const stillActive = db.findActiveSDKSession('interrupt-test'); - expect(stillActive).not.toBeNull(); - - db.close(); - - console.log('\nโœ… Interrupted session test passed!'); - }); - - it('should support multiple concurrent projects', () => { - const db = new HooksDatabase(); - - // Create sessions for different projects - const proj1Id = db.createSDKSession('session-proj1', 'project-1', 'Feature A'); - const proj2Id = db.createSDKSession('session-proj2', 'project-2', 'Feature B'); - - db.updateSDKSessionId(proj1Id, 'sdk-proj1'); - db.updateSDKSessionId(proj2Id, 'sdk-proj2'); - - // Store summaries for each project - db.storeSummary('sdk-proj1', 'project-1', { - request: 'Feature A for project 1', - completed: 'Implemented feature A' - }); - - db.storeSummary('sdk-proj2', 'project-2', { - request: 'Feature B for project 2', - completed: 'Implemented feature B' - }); - - // Retrieve summaries - should be project-specific - const proj1Summaries = db.getRecentSummaries('project-1', 10); - const proj2Summaries = db.getRecentSummaries('project-2', 10); - - expect(proj1Summaries.length).toBeGreaterThan(0); - expect(proj2Summaries.length).toBeGreaterThan(0); - - expect(proj1Summaries[0].request).toContain('project 1'); - expect(proj2Summaries[0].request).toContain('project 2'); - - db.close(); - - console.log('\nโœ… Multiple projects test passed!'); - }); -}); - -console.log('Running Phase 3 End-to-End Tests...');