@intelliweave/embedded 1.8.61 → 1.8.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -3251,11 +3251,11 @@ import{b as te,c as Ss,d as Es,e as Pe}from"./chunk-AIYMQX7V.js";var Pd=te((Fi,R
|
|
|
3251
3251
|
`},Ky={messageSeparator:"",roleSeparator:kr},Fu=Object.fromEntries(Object.keys(Lu).flatMap(r=>r.startsWith("gpt-4")?[[r,Ky]]:r.startsWith("gpt-3.5-turbo")?[[r,qy]]:[])),wT=Object.keys(Lu);var Mn=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,mi=/(?:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+/giu;function Bu(r){return{tokenSplitRegex:mi,bytePairRankDecoder:r,specialTokensEncoder:new Map([[Ot,100257],[Er,100258],[wr,100259],[Cr,100260],[Nn,100264],[On,100265],[kr,100266],[Ln,100276]])}}function Gu(r){return{tokenSplitRegex:mi,bytePairRankDecoder:r,specialTokensEncoder:new Map([[Ot,199999],[Er,2e5],[wr,200001],[Cr,200002],[Nn,200003],[On,200004],[kr,200005],[Ln,200006]])}}function zu(r){return{expectedVocabularySize:50281,tokenSplitRegex:Mn,bytePairRankDecoder:r,specialTokensEncoder:new Map([[Ot,50256]])}}function Uu(r){return{tokenSplitRegex:Mn,bytePairRankDecoder:r,specialTokensEncoder:new Map([[Ot,50256],[Er,50281],[wr,50282],[Cr,50283]])}}function Hu(r){return{expectedVocabularySize:50257,tokenSplitRegex:Mn,bytePairRankDecoder:r,specialTokensEncoder:new Map([[Ot,50256]])}}function Ds(r,e){let t=e(r);switch(r.toLowerCase()){case"r50k_base":return Hu(t);case"p50k_base":return zu(t);case"p50k_edit":return Uu(t);case"cl100k_base":return Bu(t);case"o200k_base":return Gu(t);default:throw new Error(`Unknown encoding name: ${r}`)}}var pr=class pr{constructor({bytePairRankDecoder:e,specialTokensEncoder:t,expectedVocabularySize:a,modelName:n,...i}){Pe(this,"modelName");Pe(this,"bytePairEncodingCoreProcessor");Pe(this,"specialTokensEncoder");Pe(this,"specialTokensSet");Pe(this,"allSpecialTokenRegex");Pe(this,"defaultSpecialTokenConfig");Pe(this,"vocabularySize");this.specialTokensEncoder=t,this.specialTokensSet=new Set(this.specialTokensEncoder.keys()),this.allSpecialTokenRegex=As(this.specialTokensSet),this.bytePairEncodingCoreProcessor=new di({bytePairRankDecoder:e,specialTokensEncoder:t,...i}),this.defaultSpecialTokenConfig=this.processSpecialTokens();let o=Math.max(e.length-1,vu(t));if(this.vocabularySize=this.bytePairEncodingCoreProcessor.mergeableBytePairRankCount+t.size,a!==void 0){if(this.vocabularySize!==a)throw new Error("The number of mergeable tokens and special tokens must be equal to expectedVocabularySize.");if(o!==a-1)throw new Error(`The model encodings are invalid. The maximum token value must be equal to expectedVocabularySize - 1. Currently ${o}, expected ${a-1}`)}this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),this.encodeGenerator=this.encodeGenerator.bind(this),this.decodeGenerator=this.decodeGenerator.bind(this),this.decodeAsyncGenerator=this.decodeAsyncGenerator.bind(this),this.decodeAsync=this.decodeAsync.bind(this),this.isWithinTokenLimit=this.isWithinTokenLimit.bind(this),this.encodeChat=this.encodeChat.bind(this),this.encodeChatGenerator=this.encodeChatGenerator.bind(this),this.countTokens=this.countTokens.bind(this),this.setMergeCacheSize=this.setMergeCacheSize.bind(this),this.clearMergeCache=this.clearMergeCache.bind(this),this.estimateCost=this.estimateCost.bind(this),this.modelName=n}static getEncodingApi(e,t){let a=Ds(e,t);return new pr(a)}static getEncodingApiForModel(e,t){let a=Mu[e],n=Ds(a,t);return new pr({...n,modelName:e})}processSpecialTokens({allowedSpecial:e,disallowedSpecial:t}={}){let a;if(e===Pn||e?.has(Pn)){e=new Set(this.specialTokensSet);let n=e;if(t===Pn)throw new Error('allowedSpecial and disallowedSpecial cannot both be set to "all".');typeof t=="object"?t.forEach(i=>n.delete(i)):t=new Set}if(!t||t===Pn||t.has(Pn)){t=new Set(this.specialTokensSet);let n=t;e?.size?(e.forEach(i=>n.delete(i)),t.forEach(i=>e.delete(i)),t.size>0&&(a=As(t))):a=this.allSpecialTokenRegex}return{allowedSpecial:e,regexPattern:a}}encodeGenerator(e,t){let a=t?this.processSpecialTokens(t):this.defaultSpecialTokenConfig;if(a.regexPattern){let n=e.match(a.regexPattern);if(n!==null)throw new Error(`Disallowed special token found: ${n[0]}`)}return this.bytePairEncodingCoreProcessor.encodeNativeGenerator(e,a.allowedSpecial)}encode(e,t){let a=t?this.processSpecialTokens(t):this.defaultSpecialTokenConfig;if(a.regexPattern){let n=e.match(a.regexPattern);if(n!==null)throw new Error(`Disallowed special token found: ${n[0]}`)}return this.bytePairEncodingCoreProcessor.encodeNative(e,a.allowedSpecial)}*encodeChatGenerator(e,t=this.modelName){if(!t)throw new Error("Model name must be provided either during initialization or passed in to the method.");let a=Fu[t],n=this.specialTokensEncoder.get(Nn),i=this.specialTokensEncoder.get(On);if(!a||n===void 0||i===void 0)throw new Error(`Model '${t}' does not support chat.`);let o=new Set([kr]),{messageSeparator:s,roleSeparator:l}=a,c=s.length>0?this.encode(s):[],u=l.length>0?this.encode(l,{allowedSpecial:o}):[],p=new Map;for(let{role:m="system",name:d=m,content:g}of e){if(g===void 0)throw new Error("Content must be defined for all messages.");yield[n];let f=p.get(d)??this.encode(d);p.set(d,f),yield f,u.length>0&&(yield u),yield*this.encodeGenerator(g),yield[i],yield c}yield[n],yield*this.encodeGenerator("assistant"),u.length>0&&(yield u)}encodeChat(e,t=this.modelName){return[...this.encodeChatGenerator(e,t)].flat()}isWithinTokenLimit(e,t){let a=typeof e=="string"?this.encodeGenerator(e):this.encodeChatGenerator(e),n=0;for(let i of a)if(n+=i.length,n>t)return!1;return n}countTokens(e,t){if(typeof e=="string"){let i=t?this.processSpecialTokens(t):this.defaultSpecialTokenConfig;if(i.regexPattern){let o=e.match(i.regexPattern);if(o!==null)throw new Error(`Disallowed special token found: ${o[0]}`)}return this.bytePairEncodingCoreProcessor.countNative(e,i.allowedSpecial)}let a=this.encodeChatGenerator(e),n=0;for(let i of a)n+=i.length;return n}setMergeCacheSize(e){this.bytePairEncodingCoreProcessor.setMergeCacheSize(e)}clearMergeCache(){this.bytePairEncodingCoreProcessor.clearMergeCache()}decode(e){return this.bytePairEncodingCoreProcessor.decodeNative(e)}*decodeGenerator(e){let t=this.bytePairEncodingCoreProcessor.decodeNativeGenerator(e),a="";for(let n of t)a+=typeof n=="string"?n:Dn.decode(n,{stream:!0}),!(a.length===0||Ts(a))&&(yield a,a="");a.length>0&&(yield a)}async*decodeAsyncGenerator(e){let t=this.bytePairEncodingCoreProcessor.decodeNativeAsyncIterable(e),a="";for await(let n of t)a+=typeof n=="string"?n:Dn.decode(n,{stream:!0}),!(a.length===0||Ts(a))&&(yield a,a="");a.length>0&&(yield a)}async decodeAsync(e){let t=this.bytePairEncodingCoreProcessor.decodeNativeAsyncIterable(e),a="";for await(let n of t)a+=typeof n=="string"?n:Dn.decode(n,{stream:!0});return a}estimateCost(e,t=this.modelName){if(!t)throw new Error("Model name must be provided either during initialization or passed in to the method.");let a=pi[t];if(!a)throw new Error(`Unknown model: ${t}`);if(!a.cost)throw new Error(`No cost information available for model: ${t}`);let n=a.cost,i={},o=e/1e6;return n.input!==void 0&&(i.input=n.input*o),n.output!==void 0&&(i.output=n.output*o),n.batchInput!==void 0&&(i.batchInput=n.batchInput*o),n.batchOutput!==void 0&&(i.batchOutput=n.batchOutput*o),i}};Pe(pr,"EndOfPrompt",Ln),Pe(pr,"EndOfText",Ot),Pe(pr,"FimMiddle",wr),Pe(pr,"FimPrefix",Er),Pe(pr,"FimSuffix",Cr);var hi=pr;var $y=hi.getEncodingApi("cl100k_base",()=>gu),{decode:lx,decodeAsyncGenerator:cx,decodeGenerator:ux,encode:dx,encodeGenerator:px,isWithinTokenLimit:mx,countTokens:ya,encodeChat:hx,encodeChatGenerator:gx,vocabularySize:fx,setMergeCacheSize:yx,clearMergeCache:bx,estimateCost:vx}=$y;var gi=class{constructor(){this.size=4096;this.groups=[]}createGroup(e){let t=new Ns;return t.id=e,this.groups.push(t),t}group(e){return this.groups.find(t=>t.id===e)}countTokens(){return this.groups.reduce((e,t)=>e+t.tokenCount,0)}removeOverflow(){let e=this.countTokens(),t=this.groups.reduce((a,n)=>a+n.weight,0);for(;e>this.size;){let a=this.groups.slice().sort((i,o)=>{let s=Math.floor(i.weight/t*this.size),l=Math.floor(o.weight/t*this.size),c=i.tokenCount-s;return o.tokenCount-l-c}),n=this.removeOneItem(a);if(!n)throw new Error("Too many items in the token window that cannot be removed.");e-=n.tokenCount}}removeOneItem(e){for(let t of e){let a=t.items.findIndex(i=>!i.cannotRemove);if(a===-1)continue;let n=t.items[a];return t.items.splice(a,1),t.tokenCount-=n.tokenCount,n}return null}},Ns=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
3252
3252
|
`;this.itemPadding=0;this.sortFunction=(e,t)=>e.sortOrder!==t.sortOrder?e.sortOrder-t.sortOrder:e.dateAdded!==t.dateAdded?e.dateAdded-t.dateAdded:e.content.localeCompare(t.content)}setItemPadding(e){return this.itemPadding=e,this.recalculateTokens(),this}sortBy(e){return this.sortFunction=e,this.items.sort(this.sortFunction),this}setSeparator(e){return this.separator==e?this:(this.separator=e,this.recalculateTokens(),this)}setWeight(e){return this.weight=e,this}recalculateTokens(){this.tokenCount=this.items.reduce((e,t)=>(t.tokenCount=ya(t.content)+ya(this.separator)+this.itemPadding,e+t.tokenCount),0)}add(e){typeof e=="string"&&(e={content:e});let t=e;t.id===void 0&&(t.id=Wt());let a=this.items.find(n=>n.id===t.id);return a?(this.tokenCount-=a.tokenCount,Object.assign(a,t),t=a):this.items.push(t),t.dateAdded===void 0&&(t.dateAdded=Date.now()),t.sortOrder===void 0&&(t.sortOrder=0),t.disabled===void 0&&(t.disabled=!1),t.tokenCount=t.disabled?0:ya(e.content)+ya(this.separator)+this.itemPadding,this.tokenCount+=t.tokenCount,this.items.sort(this.sortFunction),t}getAllAsString(){return this.getAll().map(e=>e.content).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}};var Fn=1,Tr=new be("ChatGPT"),fi=class{constructor(e){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let e=new gi;return e.createGroup("context").setSeparator(`
|
|
3253
3253
|
|
|
3254
|
-
`),e.createGroup("actions").setItemPadding(25),e.createGroup("messages").setItemPadding(10),e})();this.config={...this.config,...e},this.tokenWindow.size=this.config.maxTokens||4096}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(e){let t={role:"user",content:e};this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(t),customData:t}),await this.processMessages();let n=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return n?.role=="assistant"&&n.content||""}addAssistantMessage(e){let t={role:"assistant",content:e};this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(t),customData:t})}addUserMessage(e){let t={role:"user",content:e};this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(t),customData:t})}getMessages(){return this.messageGroup.items.map(e=>e.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),Tr.debugEnabled&&Tr.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(a=>a.customData),messages:this.messageGroup.items.map(a=>a.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let t=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(t?.role=="user"||t?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(t?.role=="assistant"&&t?.tool_calls?.length){for(let a of t.tool_calls)await this.processToolCall(a);await this.processMessages()}}async trimMessages(){for(this.tokenWindow.removeOverflow();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendToAPI(e){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let t=0;for(let l=this.messageGroup.items.length-1;l>=0;l--){let c=this.messageGroup.items[l].customData;if(c.role=="assistant"&&c.tool_calls){if(t+=1,t>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(c.role=="user")break}Tr.debugEnabled&&Tr.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(l=>l.customData),messages:this.messageGroup.items.map(l=>l.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let a={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(l=>l.customData)]};for(let l of this.toolGroup.getAll()){let c=l.customData;c.description&&c.description.length>1024&&Tr.warn(`Tool description for "${c.name}" is too long, it will be truncated.`);let u={type:"function",function:{name:c.name,description:(c.description||"").substring(0,1024),parameters:c.params}};a.tools.push(u)}a.user||delete a.user,a.tools.length||delete a.tools;let n={};if(n["Content-Type"]="application/json",this.config.apiKey&&(n.Authorization=`Bearer ${this.config.apiKey}`),e)return a;let i=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:n,body:JSON.stringify(a)});if(!i.ok){let l=`${i.status} ${i.statusText}`;try{let u=await i.json();l=u.errorText||u.error?.message||u.error||l}catch{}let c=new Error(l);throw c.code=i.status,c}let o=null,s=null;if(this.config.stream)for await(let l of uu(i.body)){if(l.data=="[DONE]")break;if(!l.data)continue;let c=JSON.parse(l.data);if(s){for(let u in c.choices[0].delta)if(typeof c.choices[0].delta[u]=="string"){if(u=="role"&&s[u]==c.choices[0].delta[u])continue;s[u]=(s[u]||"")+c.choices[0].delta[u]}for(let u of c.choices[0].delta.tool_calls||[]){if(s.tool_calls||(s.tool_calls=[]),!s.tool_calls[u.index]){s.tool_calls[u.index]=u;continue}let p=s.tool_calls[u.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(u.function?.name||""),p.function.arguments=(p.function.arguments||"")+(u.function?.arguments||"")}}else s={chunkID:c.id,...c.choices[0].delta};s?.content&&!s.content.startsWith("{")&&this.config.onAIMessage?.(s.content,!0)}else o=await i.json(),this.stats.tokensUsed+=o.usage?.total_tokens||0,Tr.debug(`Used ${o.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),s=o.choices?.[0]?.message;if(s||(Tr.warn("No response block in API response."),s={role:"assistant",content:""}),s.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(s),this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(s),customData:s}),s.content&&this.config.onAIMessage?.(s.content,!1)}processIncomingMessage(e){}registerTool(e){this.toolGroup.add({id:e.name,cannotRemove:!e.canRemove,content:JSON.stringify(e),customData:e})}async processToolCall(e){try{let a=this.toolGroup.items.find(s=>s.id==e.function.name)?.customData;if(!a)throw new Error(`Tool "${e.function.name}" not found.`);let n=JSON.parse(e.function.arguments);this.config.onAIToolStart?.(e.function.name,n);let i=await a.callback(n);typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success");let o={role:"tool",content:i,tool_call_id:e.id};this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(o),customData:o})}catch(t){Tr.warn(`Unable to process tool call for "${e?.function?.name}"`,t);let a={role:"tool",content:`Error: ${t.message}`,tool_call_id:e.id};this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(a),customData:a})}}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}};var De=function(){return De=Object.assign||function(e){for(var t,a=1,n=arguments.length;a<n;a++){t=arguments[a];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},De.apply(this,arguments)};function Xy(r,e,t,a){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function s(u){try{c(a.next(u))}catch(p){o(p)}}function l(u){try{c(a.throw(u))}catch(p){o(p)}}function c(u){u.done?i(u.value):n(u.value).then(s,l)}c((a=a.apply(r,e||[])).next())})}function Yy(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},a,n,i,o;return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function s(c){return function(u){return l([c,u])}}function l(c){if(a)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(t=0)),t;)try{if(a=1,n&&(i=c[0]&2?n.return:c[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,c[1])).done)return i;switch(n=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,n=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t)}catch(u){c=[6,u],n=0}finally{a=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function de(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],a=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&a>=r.length&&(r=void 0),{value:r&&r[a++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ue(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var a=t.call(r),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(s){o={error:s}}finally{try{n&&!n.done&&(t=a.return)&&t.call(a)}finally{if(o)throw o.error}}return i}var Zy="ENTRIES",Ku="KEYS",$u="VALUES",rt="",Os=function(){function r(e,t){var a=e._tree,n=Array.from(a.keys());this.set=e,this._type=t,this._path=n.length>0?[{node:a,keys:n}]:[]}return r.prototype.next=function(){var e=this.dive();return this.backtrack(),e},r.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var e=Bn(this._path),t=e.node,a=e.keys;if(Bn(a)===rt)return{done:!1,value:this.result()};var n=t.get(Bn(a));return this._path.push({node:n,keys:Array.from(n.keys())}),this.dive()},r.prototype.backtrack=function(){if(this._path.length!==0){var e=Bn(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}},r.prototype.key=function(){return this.set._prefix+this._path.map(function(e){var t=e.keys;return Bn(t)}).filter(function(e){return e!==rt}).join("")},r.prototype.value=function(){return Bn(this._path).node.get(rt)},r.prototype.result=function(){switch(this._type){case $u:return this.value();case Ku:return this.key();default:return[this.key(),this.value()]}},r.prototype[Symbol.iterator]=function(){return this},r}(),Bn=function(r){return r[r.length-1]},Jy=function(r,e,t){var a=new Map;if(e===void 0)return a;for(var n=e.length+1,i=n+t,o=new Uint8Array(i*n).fill(t+1),s=0;s<n;++s)o[s]=s;for(var l=1;l<i;++l)o[l*n]=l;return Xu(r,e,t,a,o,1,n,""),a},Xu=function(r,e,t,a,n,i,o,s){var l,c,u=i*o;try{e:for(var p=de(r.keys()),m=p.next();!m.done;m=p.next()){var d=m.value;if(d===rt){var g=n[u-1];g<=t&&a.set(s,[r.get(d),g])}else{for(var f=i,y=0;y<d.length;++y,++f){for(var v=d[y],T=o*f,E=T-o,I=n[T],D=Math.max(0,f-t-1),C=Math.min(o-1,f+t),M=D;M<C;++M){var F=v!==e[M],R=n[E+M]+ +F,G=n[E+M+1]+1,z=n[T+M]+1,O=n[T+M+1]=Math.min(R,G,z);O<I&&(I=O)}if(I>t)continue e}Xu(r.get(d),e,t,a,n,f,o,s+d)}}}catch(x){l={error:x}}finally{try{m&&!m.done&&(c=p.return)&&c.call(p)}finally{if(l)throw l.error}}},Ls=function(){function r(e,t){e===void 0&&(e=new Map),t===void 0&&(t=""),this._size=void 0,this._tree=e,this._prefix=t}return r.prototype.atPrefix=function(e){var t,a;if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");var n=Ue(bi(this._tree,e.slice(this._prefix.length)),2),i=n[0],o=n[1];if(i===void 0){var s=Ue(Vs(o),2),l=s[0],c=s[1];try{for(var u=de(l.keys()),p=u.next();!p.done;p=u.next()){var m=p.value;if(m!==rt&&m.startsWith(c)){var d=new Map;return d.set(m.slice(c.length),l.get(m)),new r(d,e)}}}catch(g){t={error:g}}finally{try{p&&!p.done&&(a=u.return)&&a.call(u)}finally{if(t)throw t.error}}}return new r(i,e)},r.prototype.clear=function(){this._size=void 0,this._tree.clear()},r.prototype.delete=function(e){return this._size=void 0,Qy(this._tree,e)},r.prototype.entries=function(){return new Os(this,Zy)},r.prototype.forEach=function(e){var t,a;try{for(var n=de(this),i=n.next();!i.done;i=n.next()){var o=Ue(i.value,2),s=o[0],l=o[1];e(s,l,this)}}catch(c){t={error:c}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}},r.prototype.fuzzyGet=function(e,t){return Jy(this._tree,e,t)},r.prototype.get=function(e){var t=zs(this._tree,e);return t!==void 0?t.get(rt):void 0},r.prototype.has=function(e){var t=zs(this._tree,e);return t!==void 0&&t.has(rt)},r.prototype.keys=function(){return new Os(this,Ku)},r.prototype.set=function(e,t){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var a=Ms(this._tree,e);return a.set(rt,t),this},Object.defineProperty(r.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var e=this.entries();!e.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),r.prototype.update=function(e,t){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var a=Ms(this._tree,e);return a.set(rt,t(a.get(rt))),this},r.prototype.fetch=function(e,t){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var a=Ms(this._tree,e),n=a.get(rt);return n===void 0&&a.set(rt,n=t()),n},r.prototype.values=function(){return new Os(this,$u)},r.prototype[Symbol.iterator]=function(){return this.entries()},r.from=function(e){var t,a,n=new r;try{for(var i=de(e),o=i.next();!o.done;o=i.next()){var s=Ue(o.value,2),l=s[0],c=s[1];n.set(l,c)}}catch(u){t={error:u}}finally{try{o&&!o.done&&(a=i.return)&&a.call(i)}finally{if(t)throw t.error}}return n},r.fromObject=function(e){return r.from(Object.entries(e))},r}(),bi=function(r,e,t){var a,n;if(t===void 0&&(t=[]),e.length===0||r==null)return[r,t];try{for(var i=de(r.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;if(s!==rt&&e.startsWith(s))return t.push([r,s]),bi(r.get(s),e.slice(s.length),t)}}catch(l){a={error:l}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return t.push([r,e]),bi(void 0,"",t)},zs=function(r,e){var t,a;if(e.length===0||r==null)return r;try{for(var n=de(r.keys()),i=n.next();!i.done;i=n.next()){var o=i.value;if(o!==rt&&e.startsWith(o))return zs(r.get(o),e.slice(o.length))}}catch(s){t={error:s}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}},Ms=function(r,e){var t,a,n=e.length;e:for(var i=0;r&&i<n;){try{for(var o=(t=void 0,de(r.keys())),s=o.next();!s.done;s=o.next()){var l=s.value;if(l!==rt&&e[i]===l[0]){for(var c=Math.min(n-i,l.length),u=1;u<c&&e[i+u]===l[u];)++u;var p=r.get(l);if(u===l.length)r=p;else{var m=new Map;m.set(l.slice(u),p),r.set(e.slice(i,i+u),m),r.delete(l),r=m}i+=u;continue e}}}catch(g){t={error:g}}finally{try{s&&!s.done&&(a=o.return)&&a.call(o)}finally{if(t)throw t.error}}var d=new Map;return r.set(e.slice(i),d),d}return r},Qy=function(r,e){var t=Ue(bi(r,e),2),a=t[0],n=t[1];if(a!==void 0){if(a.delete(rt),a.size===0)Yu(n);else if(a.size===1){var i=Ue(a.entries().next().value,2),o=i[0],s=i[1];Zu(n,o,s)}}},Yu=function(r){if(r.length!==0){var e=Ue(Vs(r),2),t=e[0],a=e[1];if(t.delete(a),t.size===0)Yu(r.slice(0,-1));else if(t.size===1){var n=Ue(t.entries().next().value,2),i=n[0],o=n[1];i!==rt&&Zu(r.slice(0,-1),i,o)}}},Zu=function(r,e,t){if(r.length!==0){var a=Ue(Vs(r),2),n=a[0],i=a[1];n.set(i+e,t),n.delete(i)}},Vs=function(r){return r[r.length-1]},ba,Ws="or",Ju="and",eb="and_not",Qu=function(){function r(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var t=e.autoVacuum==null||e.autoVacuum===!0?Gs:e.autoVacuum;this._options=De(De(De({},Bs),e),{autoVacuum:t,searchOptions:De(De({},Vu),e.searchOptions||{}),autoSuggestOptions:De(De({},ib),e.autoSuggestOptions||{})}),this._index=new Ls,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Hs,this.addFields(this._options.fields)}return r.prototype.add=function(e){var t,a,n,i,o,s,l=this._options,c=l.extractField,u=l.tokenize,p=l.processTerm,m=l.fields,d=l.idField,g=c(e,d);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(d,'"'));if(this._idToShortId.has(g))throw new Error("MiniSearch: duplicate ID ".concat(g));var f=this.addDocumentId(g);this.saveStoredFields(f,e);try{for(var y=de(m),v=y.next();!v.done;v=y.next()){var T=v.value,E=c(e,T);if(E!=null){var I=u(E.toString(),T),D=this._fieldIds[T],C=new Set(I).size;this.addFieldLength(f,D,this._documentCount-1,C);try{for(var M=(n=void 0,de(I)),F=M.next();!F.done;F=M.next()){var R=F.value,G=p(R,T);if(Array.isArray(G))try{for(var z=(o=void 0,de(G)),O=z.next();!O.done;O=z.next()){var x=O.value;this.addTerm(D,f,x)}}catch(A){o={error:A}}finally{try{O&&!O.done&&(s=z.return)&&s.call(z)}finally{if(o)throw o.error}}else G&&this.addTerm(D,f,G)}}catch(A){n={error:A}}finally{try{F&&!F.done&&(i=M.return)&&i.call(M)}finally{if(n)throw n.error}}}}}catch(A){t={error:A}}finally{try{v&&!v.done&&(a=y.return)&&a.call(y)}finally{if(t)throw t.error}}},r.prototype.addAll=function(e){var t,a;try{for(var n=de(e),i=n.next();!i.done;i=n.next()){var o=i.value;this.add(o)}}catch(s){t={error:s}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}},r.prototype.addAllAsync=function(e,t){var a=this;t===void 0&&(t={});var n=t.chunkSize,i=n===void 0?10:n,o={chunk:[],promise:Promise.resolve()},s=e.reduce(function(u,p,m){var d=u.chunk,g=u.promise;return d.push(p),(m+1)%i===0?{chunk:[],promise:g.then(function(){return new Promise(function(f){return setTimeout(f,0)})}).then(function(){return a.addAll(d)})}:{chunk:d,promise:g}},o),l=s.chunk,c=s.promise;return c.then(function(){return a.addAll(l)})},r.prototype.remove=function(e){var t,a,n,i,o,s,l=this._options,c=l.tokenize,u=l.processTerm,p=l.extractField,m=l.fields,d=l.idField,g=p(e,d);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(d,'"'));var f=this._idToShortId.get(g);if(f==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(g,": it is not in the index"));try{for(var y=de(m),v=y.next();!v.done;v=y.next()){var T=v.value,E=p(e,T);if(E!=null){var I=c(E.toString(),T),D=this._fieldIds[T],C=new Set(I).size;this.removeFieldLength(f,D,this._documentCount,C);try{for(var M=(n=void 0,de(I)),F=M.next();!F.done;F=M.next()){var R=F.value,G=u(R,T);if(Array.isArray(G))try{for(var z=(o=void 0,de(G)),O=z.next();!O.done;O=z.next()){var x=O.value;this.removeTerm(D,f,x)}}catch(A){o={error:A}}finally{try{O&&!O.done&&(s=z.return)&&s.call(z)}finally{if(o)throw o.error}}else G&&this.removeTerm(D,f,G)}}catch(A){n={error:A}}finally{try{F&&!F.done&&(i=M.return)&&i.call(M)}finally{if(n)throw n.error}}}}}catch(A){t={error:A}}finally{try{v&&!v.done&&(a=y.return)&&a.call(y)}finally{if(t)throw t.error}}this._storedFields.delete(f),this._documentIds.delete(f),this._idToShortId.delete(g),this._fieldLength.delete(f),this._documentCount-=1},r.prototype.removeAll=function(e){var t,a;if(e)try{for(var n=de(e),i=n.next();!i.done;i=n.next()){var o=i.value;this.remove(o)}}catch(s){t={error:s}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new Ls,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},r.prototype.discard=function(e){var t=this,a=this._idToShortId.get(e);if(a==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(e,": it is not in the index"));this._idToShortId.delete(e),this._documentIds.delete(a),this._storedFields.delete(a),(this._fieldLength.get(a)||[]).forEach(function(n,i){t.removeFieldLength(a,i,t._documentCount,n)}),this._fieldLength.delete(a),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},r.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var e=this._options.autoVacuum,t=e.minDirtFactor,a=e.minDirtCount,n=e.batchSize,i=e.batchWait;this.conditionalVacuum({batchSize:n,batchWait:i},{minDirtCount:a,minDirtFactor:t})}},r.prototype.discardAll=function(e){var t,a,n=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var i=de(e),o=i.next();!o.done;o=i.next()){var s=o.value;this.discard(s)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(a=i.return)&&a.call(i)}finally{if(t)throw t.error}}}finally{this._options.autoVacuum=n}this.maybeAutoVacuum()},r.prototype.replace=function(e){var t=this._options,a=t.idField,n=t.extractField,i=n(e,a);this.discard(i),this.add(e)},r.prototype.vacuum=function(e){return e===void 0&&(e={}),this.conditionalVacuum(e)},r.prototype.conditionalVacuum=function(e,t){var a=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&t,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var n=a._enqueuedVacuumConditions;return a._enqueuedVacuumConditions=Hs,a.performVacuuming(e,n)}),this._enqueuedVacuum)):this.vacuumConditionsMet(t)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)},r.prototype.performVacuuming=function(e,t){return Xy(this,void 0,void 0,function(){var a,n,i,o,s,l,c,u,p,m,d,g,f,y,v,T,E,I,D,C,M,F,R,G,z;return Yy(this,function(O){switch(O.label){case 0:if(a=this._dirtCount,!this.vacuumConditionsMet(t))return[3,10];n=e.batchSize||Us.batchSize,i=e.batchWait||Us.batchWait,o=1,O.label=1;case 1:O.trys.push([1,7,8,9]),s=de(this._index),l=s.next(),O.label=2;case 2:if(l.done)return[3,6];c=Ue(l.value,2),u=c[0],p=c[1];try{for(m=(F=void 0,de(p)),d=m.next();!d.done;d=m.next()){g=Ue(d.value,2),f=g[0],y=g[1];try{for(v=(G=void 0,de(y)),T=v.next();!T.done;T=v.next())E=Ue(T.value,1),I=E[0],!this._documentIds.has(I)&&(y.size<=1?p.delete(f):y.delete(I))}catch(x){G={error:x}}finally{try{T&&!T.done&&(z=v.return)&&z.call(v)}finally{if(G)throw G.error}}}}catch(x){F={error:x}}finally{try{d&&!d.done&&(R=m.return)&&R.call(m)}finally{if(F)throw F.error}}return this._index.get(u).size===0&&this._index.delete(u),o%n!==0?[3,4]:[4,new Promise(function(x){return setTimeout(x,i)})];case 3:O.sent(),O.label=4;case 4:o+=1,O.label=5;case 5:return l=s.next(),[3,2];case 6:return[3,9];case 7:return D=O.sent(),C={error:D},[3,9];case 8:try{l&&!l.done&&(M=s.return)&&M.call(s)}finally{if(C)throw C.error}return[7];case 9:this._dirtCount-=a,O.label=10;case 10:return[4,null];case 11:return O.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},r.prototype.vacuumConditionsMet=function(e){if(e==null)return!0;var t=e.minDirtCount,a=e.minDirtFactor;return t=t||Gs.minDirtCount,a=a||Gs.minDirtFactor,this.dirtCount>=t&&this.dirtFactor>=a},Object.defineProperty(r.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),r.prototype.has=function(e){return this._idToShortId.has(e)},r.prototype.getStoredFields=function(e){var t=this._idToShortId.get(e);if(t!=null)return this._storedFields.get(t)},r.prototype.search=function(e,t){var a,n;t===void 0&&(t={});var i=this.executeQuery(e,t),o=[];try{for(var s=de(i),l=s.next();!l.done;l=s.next()){var c=Ue(l.value,2),u=c[0],p=c[1],m=p.score,d=p.terms,g=p.match,f=d.length||1,y={id:this._documentIds.get(u),score:m*f,terms:Object.keys(g),queryTerms:d,match:g};Object.assign(y,this._storedFields.get(u)),(t.filter==null||t.filter(y))&&o.push(y)}}catch(v){a={error:v}}finally{try{l&&!l.done&&(n=s.return)&&n.call(s)}finally{if(a)throw a.error}}return e===r.wildcard&&t.boostDocument==null&&this._options.searchOptions.boostDocument==null||o.sort(ju),o},r.prototype.autoSuggest=function(e,t){var a,n,i,o;t===void 0&&(t={}),t=De(De({},this._options.autoSuggestOptions),t);var s=new Map;try{for(var l=de(this.search(e,t)),c=l.next();!c.done;c=l.next()){var u=c.value,p=u.score,m=u.terms,d=m.join(" "),g=s.get(d);g!=null?(g.score+=p,g.count+=1):s.set(d,{score:p,terms:m,count:1})}}catch(D){a={error:D}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(a)throw a.error}}var f=[];try{for(var y=de(s),v=y.next();!v.done;v=y.next()){var T=Ue(v.value,2),g=T[0],E=T[1],p=E.score,m=E.terms,I=E.count;f.push({suggestion:g,terms:m,score:p/I})}}catch(D){i={error:D}}finally{try{v&&!v.done&&(o=y.return)&&o.call(y)}finally{if(i)throw i.error}}return f.sort(ju),f},Object.defineProperty(r.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),r.loadJSON=function(e,t){if(t==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(e),t)},r.getDefault=function(e){if(Bs.hasOwnProperty(e))return Fs(Bs,e);throw new Error('MiniSearch: unknown option "'.concat(e,'"'))},r.loadJS=function(e,t){var a,n,i,o,s,l,c=e.index,u=e.documentCount,p=e.nextId,m=e.documentIds,d=e.fieldIds,g=e.fieldLength,f=e.averageFieldLength,y=e.storedFields,v=e.dirtCount,T=e.serializationVersion;if(T!==1&&T!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var E=new r(t);E._documentCount=u,E._nextId=p,E._documentIds=yi(m),E._idToShortId=new Map,E._fieldIds=d,E._fieldLength=yi(g),E._avgFieldLength=f,E._storedFields=yi(y),E._dirtCount=v||0,E._index=new Ls;try{for(var I=de(E._documentIds),D=I.next();!D.done;D=I.next()){var C=Ue(D.value,2),M=C[0],F=C[1];E._idToShortId.set(F,M)}}catch(Z){a={error:Z}}finally{try{D&&!D.done&&(n=I.return)&&n.call(I)}finally{if(a)throw a.error}}try{for(var R=de(c),G=R.next();!G.done;G=R.next()){var z=Ue(G.value,2),O=z[0],x=z[1],A=new Map;try{for(var B=(s=void 0,de(Object.keys(x))),X=B.next();!X.done;X=B.next()){var K=X.value,Q=x[K];T===1&&(Q=Q.ds),A.set(parseInt(K,10),yi(Q))}}catch(Z){s={error:Z}}finally{try{X&&!X.done&&(l=B.return)&&l.call(B)}finally{if(s)throw s.error}}E._index.set(O,A)}}catch(Z){i={error:Z}}finally{try{G&&!G.done&&(o=R.return)&&o.call(R)}finally{if(i)throw i.error}}return E},r.prototype.executeQuery=function(e,t){var a=this;if(t===void 0&&(t={}),e===r.wildcard)return this.executeWildcardQuery(t);if(typeof e!="string"){var n=De(De(De({},t),e),{queries:void 0}),i=e.queries.map(function(y){return a.executeQuery(y,n)});return this.combineResults(i,n.combineWith)}var o=this._options,s=o.tokenize,l=o.processTerm,c=o.searchOptions,u=De(De({tokenize:s,processTerm:l},c),t),p=u.tokenize,m=u.processTerm,d=p(e).flatMap(function(y){return m(y)}).filter(function(y){return!!y}),g=d.map(ab(u)),f=g.map(function(y){return a.executeQuerySpec(y,u)});return this.combineResults(f,u.combineWith)},r.prototype.executeQuerySpec=function(e,t){var a,n,i,o,s=De(De({},this._options.searchOptions),t),l=(s.fields||this._options.fields).reduce(function(K,Q){var Z;return De(De({},K),(Z={},Z[Q]=Fs(s.boost,Q)||1,Z))},{}),c=s.boostDocument,u=s.weights,p=s.maxFuzzy,m=s.bm25,d=De(De({},Vu.weights),u),g=d.fuzzy,f=d.prefix,y=this._index.get(e.term),v=this.termResults(e.term,e.term,1,y,l,c,m),T,E;if(e.prefix&&(T=this._index.atPrefix(e.term)),e.fuzzy){var I=e.fuzzy===!0?.2:e.fuzzy,D=I<1?Math.min(p,Math.round(e.term.length*I)):I;D&&(E=this._index.fuzzyGet(e.term,D))}if(T)try{for(var C=de(T),M=C.next();!M.done;M=C.next()){var F=Ue(M.value,2),R=F[0],G=F[1],z=R.length-e.term.length;if(z){E?.delete(R);var O=f*R.length/(R.length+.3*z);this.termResults(e.term,R,O,G,l,c,m,v)}}}catch(K){a={error:K}}finally{try{M&&!M.done&&(n=C.return)&&n.call(C)}finally{if(a)throw a.error}}if(E)try{for(var x=de(E.keys()),A=x.next();!A.done;A=x.next()){var R=A.value,B=Ue(E.get(R),2),X=B[0],z=B[1];if(z){var O=g*R.length/(R.length+z);this.termResults(e.term,R,O,X,l,c,m,v)}}}catch(K){i={error:K}}finally{try{A&&!A.done&&(o=x.return)&&o.call(x)}finally{if(i)throw i.error}}return v},r.prototype.executeWildcardQuery=function(e){var t,a,n=new Map,i=De(De({},this._options.searchOptions),e);try{for(var o=de(this._documentIds),s=o.next();!s.done;s=o.next()){var l=Ue(s.value,2),c=l[0],u=l[1],p=i.boostDocument?i.boostDocument(u,"",this._storedFields.get(c)):1;n.set(c,{score:p,terms:[],match:{}})}}catch(m){t={error:m}}finally{try{s&&!s.done&&(a=o.return)&&a.call(o)}finally{if(t)throw t.error}}return n},r.prototype.combineResults=function(e,t){if(t===void 0&&(t=Ws),e.length===0)return new Map;var a=t.toLowerCase();return e.reduce(tb[a])||new Map},r.prototype.toJSON=function(){var e,t,a,n,i=[];try{for(var o=de(this._index),s=o.next();!s.done;s=o.next()){var l=Ue(s.value,2),c=l[0],u=l[1],p={};try{for(var m=(a=void 0,de(u)),d=m.next();!d.done;d=m.next()){var g=Ue(d.value,2),f=g[0],y=g[1];p[f]=Object.fromEntries(y)}}catch(v){a={error:v}}finally{try{d&&!d.done&&(n=m.return)&&n.call(m)}finally{if(a)throw a.error}}i.push([c,p])}}catch(v){e={error:v}}finally{try{s&&!s.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:i,serializationVersion:2}},r.prototype.termResults=function(e,t,a,n,i,o,s,l){var c,u,p,m,d;if(l===void 0&&(l=new Map),n==null)return l;try{for(var g=de(Object.keys(i)),f=g.next();!f.done;f=g.next()){var y=f.value,v=i[y],T=this._fieldIds[y],E=n.get(T);if(E!=null){var I=E.size,D=this._avgFieldLength[T];try{for(var C=(p=void 0,de(E.keys())),M=C.next();!M.done;M=C.next()){var F=M.value;if(!this._documentIds.has(F)){this.removeTerm(T,F,t),I-=1;continue}var R=o?o(this._documentIds.get(F),t,this._storedFields.get(F)):1;if(R){var G=E.get(F),z=this._fieldLength.get(F)[T],O=nb(G,I,this._documentCount,z,D,s),x=a*v*R*O,A=l.get(F);if(A){A.score+=x,ob(A.terms,e);var B=Fs(A.match,t);B?B.push(y):A.match[t]=[y]}else l.set(F,{score:x,terms:[e],match:(d={},d[t]=[y],d)})}}}catch(X){p={error:X}}finally{try{M&&!M.done&&(m=C.return)&&m.call(C)}finally{if(p)throw p.error}}}}}catch(X){c={error:X}}finally{try{f&&!f.done&&(u=g.return)&&u.call(g)}finally{if(c)throw c.error}}return l},r.prototype.addTerm=function(e,t,a){var n=this._index.fetch(a,qu),i=n.get(e);if(i==null)i=new Map,i.set(t,1),n.set(e,i);else{var o=i.get(t);i.set(t,(o||0)+1)}},r.prototype.removeTerm=function(e,t,a){if(!this._index.has(a)){this.warnDocumentChanged(t,e,a);return}var n=this._index.fetch(a,qu),i=n.get(e);i==null||i.get(t)==null?this.warnDocumentChanged(t,e,a):i.get(t)<=1?i.size<=1?n.delete(e):i.delete(t):i.set(t,i.get(t)-1),this._index.get(a).size===0&&this._index.delete(a)},r.prototype.warnDocumentChanged=function(e,t,a){var n,i;try{for(var o=de(Object.keys(this._fieldIds)),s=o.next();!s.done;s=o.next()){var l=s.value;if(this._fieldIds[l]===t){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(e),' has changed before removal: term "').concat(a,'" was not present in field "').concat(l,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(c){n={error:c}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}},r.prototype.addDocumentId=function(e){var t=this._nextId;return this._idToShortId.set(e,t),this._documentIds.set(t,e),this._documentCount+=1,this._nextId+=1,t},r.prototype.addFields=function(e){for(var t=0;t<e.length;t++)this._fieldIds[e[t]]=t},r.prototype.addFieldLength=function(e,t,a,n){var i=this._fieldLength.get(e);i==null&&this._fieldLength.set(e,i=[]),i[t]=n;var o=this._avgFieldLength[t]||0,s=o*a+n;this._avgFieldLength[t]=s/(a+1)},r.prototype.removeFieldLength=function(e,t,a,n){if(a===1){this._avgFieldLength[t]=0;return}var i=this._avgFieldLength[t]*a-n;this._avgFieldLength[t]=i/(a-1)},r.prototype.saveStoredFields=function(e,t){var a,n,i=this._options,o=i.storeFields,s=i.extractField;if(!(o==null||o.length===0)){var l=this._storedFields.get(e);l==null&&this._storedFields.set(e,l={});try{for(var c=de(o),u=c.next();!u.done;u=c.next()){var p=u.value,m=s(t,p);m!==void 0&&(l[p]=m)}}catch(d){a={error:d}}finally{try{u&&!u.done&&(n=c.return)&&n.call(c)}finally{if(a)throw a.error}}}},r.wildcard=Symbol("*"),r}(),Fs=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)?r[e]:void 0},tb=(ba={},ba[Ws]=function(r,e){var t,a;try{for(var n=de(e.keys()),i=n.next();!i.done;i=n.next()){var o=i.value,s=r.get(o);if(s==null)r.set(o,e.get(o));else{var l=e.get(o),c=l.score,u=l.terms,p=l.match;s.score=s.score+c,s.match=Object.assign(s.match,p),Wu(s.terms,u)}}}catch(m){t={error:m}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}return r},ba[Ju]=function(r,e){var t,a,n=new Map;try{for(var i=de(e.keys()),o=i.next();!o.done;o=i.next()){var s=o.value,l=r.get(s);if(l!=null){var c=e.get(s),u=c.score,p=c.terms,m=c.match;Wu(l.terms,p),n.set(s,{score:l.score+u,terms:l.terms,match:Object.assign(l.match,m)})}}}catch(d){t={error:d}}finally{try{o&&!o.done&&(a=i.return)&&a.call(i)}finally{if(t)throw t.error}}return n},ba[eb]=function(r,e){var t,a;try{for(var n=de(e.keys()),i=n.next();!i.done;i=n.next()){var o=i.value;r.delete(o)}}catch(s){t={error:s}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}return r},ba),rb={k:1.2,b:.7,d:.5},nb=function(r,e,t,a,n,i){var o=i.k,s=i.b,l=i.d,c=Math.log(1+(t-e+.5)/(e+.5));return c*(l+r*(o+1)/(r+o*(1-s+s*a/n)))},ab=function(r){return function(e,t,a){var n=typeof r.fuzzy=="function"?r.fuzzy(e,t,a):r.fuzzy||!1,i=typeof r.prefix=="function"?r.prefix(e,t,a):r.prefix===!0;return{term:e,fuzzy:n,prefix:i}}},Bs={idField:"id",extractField:function(r,e){return r[e]},tokenize:function(r){return r.split(sb)},processTerm:function(r){return r.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(r,e){typeof console?.[r]=="function"&&console[r](e)},autoVacuum:!0},Vu={combineWith:Ws,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:rb},ib={combineWith:Ju,prefix:function(r,e,t){return e===t.length-1}},Us={batchSize:1e3,batchWait:10},Hs={minDirtFactor:.1,minDirtCount:20},Gs=De(De({},Us),Hs),ob=function(r,e){r.includes(e)||r.push(e)},Wu=function(r,e){var t,a;try{for(var n=de(e),i=n.next();!i.done;i=n.next()){var o=i.value;r.includes(o)||r.push(o)}}catch(s){t={error:s}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}},ju=function(r,e){var t=r.score,a=e.score;return a-t},qu=function(){return new Map},yi=function(r){var e,t,a=new Map;try{for(var n=de(Object.keys(r)),i=n.next();!i.done;i=n.next()){var o=i.value;a.set(parseInt(o,10),r[o])}}catch(s){e={error:s}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return a},sb=/[\n\r -#%-*,-/:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]+/u;var ed=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(r,e)=>{let t=await e.knowledgeBase.search(r.query),a=e;a._lastKBsearch=r.query,a._nextRequestUseKBitems=t,e.submitAnalyticsEvent({type:"kb-search",query:r.query,results:t});let n=t.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",i=t.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${i}.`}}];var h={};Ss(h,{BRAND:()=>Nb,DIRTY:()=>qr,EMPTY_PATH:()=>db,INVALID:()=>ee,NEVER:()=>yv,OK:()=>ot,ParseStatus:()=>nt,Schema:()=>ue,ZodAny:()=>Ir,ZodArray:()=>fr,ZodBigInt:()=>$r,ZodBoolean:()=>Xr,ZodBranded:()=>_a,ZodCatch:()=>sn,ZodDate:()=>Yr,ZodDefault:()=>on,ZodDiscriminatedUnion:()=>Si,ZodEffects:()=>Ft,ZodEnum:()=>nn,ZodError:()=>yt,ZodFirstPartyTypeKind:()=>re,ZodFunction:()=>wi,ZodIntersection:()=>en,ZodIssueCode:()=>U,ZodLazy:()=>tn,ZodLiteral:()=>rn,ZodMap:()=>Wn,ZodNaN:()=>qn,ZodNativeEnum:()=>an,ZodNever:()=>jt,ZodNull:()=>Jr,ZodNullable:()=>rr,ZodNumber:()=>Kr,ZodObject:()=>bt,ZodOptional:()=>Lt,ZodParsedType:()=>j,ZodPipeline:()=>Sa,ZodPromise:()=>Rr,ZodReadonly:()=>ln,ZodRecord:()=>Ei,ZodSchema:()=>ue,ZodSet:()=>jn,ZodString:()=>Ar,ZodSymbol:()=>Hn,ZodTransformer:()=>Ft,ZodTuple:()=>tr,ZodType:()=>ue,ZodUndefined:()=>Zr,ZodUnion:()=>Qr,ZodUnknown:()=>gr,ZodVoid:()=>Vn,addIssueToContext:()=>W,any:()=>Hb,array:()=>qb,bigint:()=>Fb,boolean:()=>dd,coerce:()=>fv,custom:()=>ld,date:()=>Bb,datetimeRegex:()=>od,defaultErrorMap:()=>mr,discriminatedUnion:()=>Yb,effect:()=>lv,enum:()=>iv,function:()=>rv,getErrorMap:()=>Gn,getParsedType:()=>er,instanceof:()=>Lb,intersection:()=>Zb,isAborted:()=>vi,isAsync:()=>zn,isDirty:()=>_i,isValid:()=>xr,late:()=>Ob,lazy:()=>nv,literal:()=>av,makeIssue:()=>va,map:()=>ev,nan:()=>Mb,nativeEnum:()=>ov,never:()=>Wb,null:()=>Ub,nullable:()=>uv,number:()=>ud,object:()=>Kb,objectUtil:()=>js,oboolean:()=>gv,onumber:()=>hv,optional:()=>cv,ostring:()=>mv,pipeline:()=>pv,preprocess:()=>dv,promise:()=>sv,quotelessJson:()=>lb,record:()=>Qb,set:()=>tv,setErrorMap:()=>ub,strictObject:()=>$b,string:()=>cd,symbol:()=>Gb,transformer:()=>lv,tuple:()=>Jb,undefined:()=>zb,union:()=>Xb,unknown:()=>Vb,util:()=>pe,void:()=>jb});var pe;(function(r){r.assertEqual=n=>{};function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{let i={};for(let o of n)i[o]=o;return i},r.getValidEnumValues=n=>{let i=r.objectKeys(n).filter(s=>typeof n[n[s]]!="number"),o={};for(let s of i)o[s]=n[s];return r.objectValues(o)},r.objectValues=n=>r.objectKeys(n).map(function(i){return n[i]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let o in n)Object.prototype.hasOwnProperty.call(n,o)&&i.push(o);return i},r.find=(n,i)=>{for(let o of n)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function a(n,i=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=a,r.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(pe||(pe={}));var js;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(js||(js={}));var j=pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),er=r=>{switch(typeof r){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(r)?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(r)?j.array:r===null?j.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?j.promise:typeof Map<"u"&&r instanceof Map?j.map:typeof Set<"u"&&r instanceof Set?j.set:typeof Date<"u"&&r instanceof Date?j.date:j.object;default:return j.unknown}};var U=pe.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"]),lb=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),yt=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},a={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)a._errors.push(t(o));else{let s=a,l=0;for(;l<o.path.length;){let c=o.path[l];l===o.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(o))):s[c]=s[c]||{_errors:[]},s=s[c],l++}}};return n(this),a}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},a=[];for(let n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):a.push(e(n));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}};yt.create=r=>new yt(r);var cb=(r,e)=>{let t;switch(r.code){case U.invalid_type:r.received===j.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case U.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,pe.jsonStringifyReplacer)}`;break;case U.unrecognized_keys:t=`Unrecognized key(s) in object: ${pe.joinValues(r.keys,", ")}`;break;case U.invalid_union:t="Invalid input";break;case U.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${pe.joinValues(r.options)}`;break;case U.invalid_enum_value:t=`Invalid enum value. Expected ${pe.joinValues(r.options)}, received '${r.received}'`;break;case U.invalid_arguments:t="Invalid function arguments";break;case U.invalid_return_type:t="Invalid function return type";break;case U.invalid_date:t="Invalid date";break;case U.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:pe.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case U.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case U.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case U.custom:t="Invalid input";break;case U.invalid_intersection_types:t="Intersection results could not be merged";break;case U.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case U.not_finite:t="Number must be finite";break;default:t=e.defaultError,pe.assertNever(r)}return{message:t}},mr=cb;var td=mr;function ub(r){td=r}function Gn(){return td}var va=r=>{let{data:e,path:t,errorMaps:a,issueData:n}=r,i=[...t,...n.path||[]],o={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let s="",l=a.filter(c=>!!c).slice().reverse();for(let c of l)s=c(o,{data:e,defaultError:s}).message;return{...n,path:i,message:s}},db=[];function W(r,e){let t=Gn(),a=va({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===mr?void 0:mr].filter(n=>!!n)});r.common.issues.push(a)}var nt=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let a=[];for(let n of t){if(n.status==="aborted")return ee;n.status==="dirty"&&e.dirty(),a.push(n.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,t){let a=[];for(let n of t){let i=await n.key,o=await n.value;a.push({key:i,value:o})}return r.mergeObjectSync(e,a)}static mergeObjectSync(e,t){let a={};for(let n of t){let{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return ee;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(a[i.value]=o.value)}return{status:e.value,value:a}}},ee=Object.freeze({status:"aborted"}),qr=r=>({status:"dirty",value:r}),ot=r=>({status:"valid",value:r}),vi=r=>r.status==="aborted",_i=r=>r.status==="dirty",xr=r=>r.status==="valid",zn=r=>typeof Promise<"u"&&r instanceof Promise;var Y;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(Y||(Y={}));var Mt=class{constructor(e,t,a,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,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}},rd=(r,e)=>{if(xr(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new yt(r.common.issues);return this._error=t,this._error}}};function se(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:a,description:n}=r;if(e&&(t||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,s)=>{let{message:l}=r;return o.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??a??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:l??t??s.defaultError}},description:n}}var ue=class{get description(){return this._def.description}_getType(e){return er(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:er(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nt,ctx:{common:e.parent.common,data:e.data,parsedType:er(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(zn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){let a={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:er(e)},n=this._parseSync({data:e,path:a.path,parent:a});return rd(a,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:er(e)};if(!this["~standard"].async)try{let a=this._parseSync({data:e,path:[],parent:t});return xr(a)?{value:a.value}:{issues:t.common.issues}}catch(a){a?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(a=>xr(a)?{value:a.value}:{issues:t.common.issues})}async parseAsync(e,t){let a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){let a={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:er(e)},n=this._parse({data:e,path:a.path,parent:a}),i=await(zn(n)?n:Promise.resolve(n));return rd(a,i)}refine(e,t){let a=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,i)=>{let o=e(n),s=()=>i.addIssue({code:U.custom,...a(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(s(),!1)):o?!0:(s(),!1)})}refinement(e,t){return this._refinement((a,n)=>e(a)?!0:(n.addIssue(typeof t=="function"?t(a,n):t),!1))}_refinement(e){return new Ft({schema:this,typeName:re.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Lt.create(this,this._def)}nullable(){return rr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fr.create(this)}promise(){return Rr.create(this,this._def)}or(e){return Qr.create([this,e],this._def)}and(e){return en.create(this,e,this._def)}transform(e){return new Ft({...se(this._def),schema:this,typeName:re.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new on({...se(this._def),innerType:this,defaultValue:t,typeName:re.ZodDefault})}brand(){return new _a({typeName:re.ZodBranded,type:this,...se(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new sn({...se(this._def),innerType:this,catchValue:t,typeName:re.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Sa.create(this,e)}readonly(){return ln.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},pb=/^c[^\s-]{8,}$/i,mb=/^[0-9a-z]+$/,hb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gb=/^[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,fb=/^[a-z0-9_-]{21}$/i,yb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bb=/^[-+]?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)?)??$/,vb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_b="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qs,Sb=/^(?:(?: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])$/,Eb=/^(?:(?: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])$/,wb=/^(([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]))$/,Cb=/^(([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])$/,kb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Tb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ad="((\\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])))",xb=new RegExp(`^${ad}$`);function id(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Ab(r){return new RegExp(`^${id(r)}$`)}function od(r){let e=`${ad}T${id(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ib(r,e){return!!((e==="v4"||!e)&&Sb.test(r)||(e==="v6"||!e)&&wb.test(r))}function Rb(r,e){if(!yb.test(r))return!1;try{let[t]=r.split("."),a=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(a));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Pb(r,e){return!!((e==="v4"||!e)&&Eb.test(r)||(e==="v6"||!e)&&Cb.test(r))}var Ar=class r extends ue{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let i=this._getOrReturnCtx(e);return W(i,{code:U.invalid_type,expected:j.string,received:i.parsedType}),ee}let a=new nt,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),a.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),a.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,s=e.data.length<i.value;(o||s)&&(n=this._getOrReturnCtx(e,n),o?W(n,{code:U.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&W(n,{code:U.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),a.dirty())}else if(i.kind==="email")vb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"email",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="emoji")qs||(qs=new RegExp(_b,"u")),qs.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"emoji",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="uuid")gb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"uuid",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="nanoid")fb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"nanoid",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="cuid")pb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cuid",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="cuid2")mb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cuid2",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="ulid")hb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"ulid",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),W(n,{validation:"url",code:U.invalid_string,message:i.message}),a.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"regex",code:U.invalid_string,message:i.message}),a.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),a.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{startsWith:i.value},message:i.message}),a.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{endsWith:i.value},message:i.message}),a.dirty()):i.kind==="datetime"?od(i).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:"datetime",message:i.message}),a.dirty()):i.kind==="date"?xb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:"date",message:i.message}),a.dirty()):i.kind==="time"?Ab(i).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:"time",message:i.message}),a.dirty()):i.kind==="duration"?bb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"duration",code:U.invalid_string,message:i.message}),a.dirty()):i.kind==="ip"?Ib(e.data,i.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"ip",code:U.invalid_string,message:i.message}),a.dirty()):i.kind==="jwt"?Rb(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"jwt",code:U.invalid_string,message:i.message}),a.dirty()):i.kind==="cidr"?Pb(e.data,i.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cidr",code:U.invalid_string,message:i.message}),a.dirty()):i.kind==="base64"?kb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"base64",code:U.invalid_string,message:i.message}),a.dirty()):i.kind==="base64url"?Tb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"base64url",code:U.invalid_string,message:i.message}),a.dirty()):pe.assertNever(i);return{status:a.value,value:e.data}}_regex(e,t,a){return this.refinement(n=>e.test(n),{validation:t,code:U.invalid_string,...Y.errToObj(a)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Y.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Y.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Y.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Y.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Y.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Y.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Y.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Y.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Y.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Y.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Y.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Y.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Y.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Y.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Y.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Y.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Y.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Y.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Y.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Y.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Y.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Y.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Y.errToObj(t)})}nonempty(e){return this.min(1,Y.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ar.create=r=>new Ar({checks:[],typeName:re.ZodString,coerce:r?.coerce??!1,...se(r)});function Db(r,e){let t=(r.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=t>a?t:a,i=Number.parseInt(r.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return i%o/10**n}var Kr=class r extends ue{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==j.number){let i=this._getOrReturnCtx(e);return W(i,{code:U.invalid_type,expected:j.number,received:i.parsedType}),ee}let a,n=new nt;for(let i of this._def.checks)i.kind==="int"?pe.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),W(a,{code:U.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?Db(e.data,i.value)!==0&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),W(a,{code:U.not_finite,message:i.message}),n.dirty()):pe.assertNever(i);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Y.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Y.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Y.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Y.toString(t))}setLimit(e,t,a,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:Y.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Y.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Y.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Y.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Y.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Y.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Y.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Y.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Y.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Y.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&pe.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(t===null||a.value>t)&&(t=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Kr.create=r=>new Kr({checks:[],typeName:re.ZodNumber,coerce:r?.coerce||!1,...se(r)});var $r=class r extends ue{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==j.bigint)return this._getInvalidInput(e);let a,n=new nt;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):pe.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:j.bigint,received:t.parsedType}),ee}gte(e,t){return this.setLimit("min",e,!0,Y.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Y.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Y.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Y.toString(t))}setLimit(e,t,a,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:Y.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Y.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Y.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Y.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Y.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Y.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};$r.create=r=>new $r({checks:[],typeName:re.ZodBigInt,coerce:r?.coerce??!1,...se(r)});var Xr=class extends ue{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.boolean,received:a.parsedType}),ee}return ot(e.data)}};Xr.create=r=>new Xr({typeName:re.ZodBoolean,coerce:r?.coerce||!1,...se(r)});var Yr=class r extends ue{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let i=this._getOrReturnCtx(e);return W(i,{code:U.invalid_type,expected:j.date,received:i.parsedType}),ee}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return W(i,{code:U.invalid_date}),ee}let a=new nt,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),a.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),a.dirty()):pe.assertNever(i);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Y.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Y.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Yr.create=r=>new Yr({checks:[],coerce:r?.coerce||!1,typeName:re.ZodDate,...se(r)});var Hn=class extends ue{_parse(e){if(this._getType(e)!==j.symbol){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.symbol,received:a.parsedType}),ee}return ot(e.data)}};Hn.create=r=>new Hn({typeName:re.ZodSymbol,...se(r)});var Zr=class extends ue{_parse(e){if(this._getType(e)!==j.undefined){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.undefined,received:a.parsedType}),ee}return ot(e.data)}};Zr.create=r=>new Zr({typeName:re.ZodUndefined,...se(r)});var Jr=class extends ue{_parse(e){if(this._getType(e)!==j.null){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.null,received:a.parsedType}),ee}return ot(e.data)}};Jr.create=r=>new Jr({typeName:re.ZodNull,...se(r)});var Ir=class extends ue{constructor(){super(...arguments),this._any=!0}_parse(e){return ot(e.data)}};Ir.create=r=>new Ir({typeName:re.ZodAny,...se(r)});var gr=class extends ue{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ot(e.data)}};gr.create=r=>new gr({typeName:re.ZodUnknown,...se(r)});var jt=class extends ue{_parse(e){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:j.never,received:t.parsedType}),ee}};jt.create=r=>new jt({typeName:re.ZodNever,...se(r)});var Vn=class extends ue{_parse(e){if(this._getType(e)!==j.undefined){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.void,received:a.parsedType}),ee}return ot(e.data)}};Vn.create=r=>new Vn({typeName:re.ZodVoid,...se(r)});var fr=class r extends ue{_parse(e){let{ctx:t,status:a}=this._processInputParams(e),n=this._def;if(t.parsedType!==j.array)return W(t,{code:U.invalid_type,expected:j.array,received:t.parsedType}),ee;if(n.exactLength!==null){let o=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(o||s)&&(W(t,{code:o?U.too_big:U.too_small,minimum:s?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),a.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(W(t,{code:U.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),a.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(W(t,{code:U.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map((o,s)=>n.type._parseAsync(new Mt(t,o,t.path,s)))).then(o=>nt.mergeArray(a,o));let i=[...t.data].map((o,s)=>n.type._parseSync(new Mt(t,o,t.path,s)));return nt.mergeArray(a,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:Y.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:Y.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:Y.toString(t)}})}nonempty(e){return this.min(1,e)}};fr.create=(r,e)=>new fr({type:r,minLength:null,maxLength:null,exactLength:null,typeName:re.ZodArray,...se(e)});function Un(r){if(r instanceof bt){let e={};for(let t in r.shape){let a=r.shape[t];e[t]=Lt.create(Un(a))}return new bt({...r._def,shape:()=>e})}else return r instanceof fr?new fr({...r._def,type:Un(r.element)}):r instanceof Lt?Lt.create(Un(r.unwrap())):r instanceof rr?rr.create(Un(r.unwrap())):r instanceof tr?tr.create(r.items.map(e=>Un(e))):r}var bt=class r extends ue{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=pe.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==j.object){let c=this._getOrReturnCtx(e);return W(c,{code:U.invalid_type,expected:j.object,received:c.parsedType}),ee}let{status:a,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof jt&&this._def.unknownKeys==="strip"))for(let c in n.data)o.includes(c)||s.push(c);let l=[];for(let c of o){let u=i[c],p=n.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Mt(n,p,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof jt){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of s)l.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(c==="strict")s.length>0&&(W(n,{code:U.unrecognized_keys,keys:s}),a.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of s){let p=n.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Mt(n,p,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let p=await u.key,m=await u.value;c.push({key:p,value:m,alwaysSet:u.alwaysSet})}return c}).then(c=>nt.mergeObjectSync(a,c)):nt.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return Y.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,a)=>{let n=this._def.errorMap?.(t,a).message??a.defaultError;return t.code==="unrecognized_keys"?{message:Y.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:re.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let a of pe.objectKeys(e))e[a]&&this.shape[a]&&(t[a]=this.shape[a]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let a of pe.objectKeys(this.shape))e[a]||(t[a]=this.shape[a]);return new r({...this._def,shape:()=>t})}deepPartial(){return Un(this)}partial(e){let t={};for(let a of pe.objectKeys(this.shape)){let n=this.shape[a];e&&!e[a]?t[a]=n:t[a]=n.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let a of pe.objectKeys(this.shape))if(e&&!e[a])t[a]=this.shape[a];else{let i=this.shape[a];for(;i instanceof Lt;)i=i._def.innerType;t[a]=i}return new r({...this._def,shape:()=>t})}keyof(){return sd(pe.objectKeys(this.shape))}};bt.create=(r,e)=>new bt({shape:()=>r,unknownKeys:"strip",catchall:jt.create(),typeName:re.ZodObject,...se(e)});bt.strictCreate=(r,e)=>new bt({shape:()=>r,unknownKeys:"strict",catchall:jt.create(),typeName:re.ZodObject,...se(e)});bt.lazycreate=(r,e)=>new bt({shape:r,unknownKeys:"strip",catchall:jt.create(),typeName:re.ZodObject,...se(e)});var Qr=class extends ue{_parse(e){let{ctx:t}=this._processInputParams(e),a=this._def.options;function n(i){for(let s of i)if(s.result.status==="valid")return s.result;for(let s of i)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let o=i.map(s=>new yt(s.ctx.common.issues));return W(t,{code:U.invalid_union,unionErrors:o}),ee}if(t.common.async)return Promise.all(a.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let l of a){let c={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let s=o.map(l=>new yt(l));return W(t,{code:U.invalid_union,unionErrors:s}),ee}}get options(){return this._def.options}};Qr.create=(r,e)=>new Qr({options:r,typeName:re.ZodUnion,...se(e)});var hr=r=>r instanceof tn?hr(r.schema):r instanceof Ft?hr(r.innerType()):r instanceof rn?[r.value]:r instanceof nn?r.options:r instanceof an?pe.objectValues(r.enum):r instanceof on?hr(r._def.innerType):r instanceof Zr?[void 0]:r instanceof Jr?[null]:r instanceof Lt?[void 0,...hr(r.unwrap())]:r instanceof rr?[null,...hr(r.unwrap())]:r instanceof _a||r instanceof ln?hr(r.unwrap()):r instanceof sn?hr(r._def.innerType):[],Si=class r extends ue{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.object)return W(t,{code:U.invalid_type,expected:j.object,received:t.parsedType}),ee;let a=this.discriminator,n=t.data[a],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(W(t,{code:U.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),ee)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,a){let n=new Map;for(let i of t){let o=hr(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of o){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,i)}}return new r({typeName:re.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...se(a)})}};function Ks(r,e){let t=er(r),a=er(e);if(r===e)return{valid:!0,data:r};if(t===j.object&&a===j.object){let n=pe.objectKeys(e),i=pe.objectKeys(r).filter(s=>n.indexOf(s)!==-1),o={...r,...e};for(let s of i){let l=Ks(r[s],e[s]);if(!l.valid)return{valid:!1};o[s]=l.data}return{valid:!0,data:o}}else if(t===j.array&&a===j.array){if(r.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<r.length;i++){let o=r[i],s=e[i],l=Ks(o,s);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return t===j.date&&a===j.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var en=class extends ue{_parse(e){let{status:t,ctx:a}=this._processInputParams(e),n=(i,o)=>{if(vi(i)||vi(o))return ee;let s=Ks(i.value,o.value);return s.valid?((_i(i)||_i(o))&&t.dirty(),{status:t.value,value:s.data}):(W(a,{code:U.invalid_intersection_types}),ee)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([i,o])=>n(i,o)):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};en.create=(r,e,t)=>new en({left:r,right:e,typeName:re.ZodIntersection,...se(t)});var tr=class r extends ue{_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==j.array)return W(a,{code:U.invalid_type,expected:j.array,received:a.parsedType}),ee;if(a.data.length<this._def.items.length)return W(a,{code:U.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&a.data.length>this._def.items.length&&(W(a,{code:U.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...a.data].map((o,s)=>{let l=this._def.items[s]||this._def.rest;return l?l._parse(new Mt(a,o,a.path,s)):null}).filter(o=>!!o);return a.common.async?Promise.all(i).then(o=>nt.mergeArray(t,o)):nt.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};tr.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tr({items:r,typeName:re.ZodTuple,rest:null,...se(e)})};var Ei=class r extends ue{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==j.object)return W(a,{code:U.invalid_type,expected:j.object,received:a.parsedType}),ee;let n=[],i=this._def.keyType,o=this._def.valueType;for(let s in a.data)n.push({key:i._parse(new Mt(a,s,a.path,s)),value:o._parse(new Mt(a,a.data[s],a.path,s)),alwaysSet:s in a.data});return a.common.async?nt.mergeObjectAsync(t,n):nt.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,a){return t instanceof ue?new r({keyType:e,valueType:t,typeName:re.ZodRecord,...se(a)}):new r({keyType:Ar.create(),valueType:e,typeName:re.ZodRecord,...se(t)})}},Wn=class extends ue{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==j.map)return W(a,{code:U.invalid_type,expected:j.map,received:a.parsedType}),ee;let n=this._def.keyType,i=this._def.valueType,o=[...a.data.entries()].map(([s,l],c)=>({key:n._parse(new Mt(a,s,a.path,[c,"key"])),value:i._parse(new Mt(a,l,a.path,[c,"value"]))}));if(a.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of o){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return ee;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),s.set(c.value,u.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let l of o){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return ee;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),s.set(c.value,u.value)}return{status:t.value,value:s}}}};Wn.create=(r,e,t)=>new Wn({valueType:e,keyType:r,typeName:re.ZodMap,...se(t)});var jn=class r extends ue{_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==j.set)return W(a,{code:U.invalid_type,expected:j.set,received:a.parsedType}),ee;let n=this._def;n.minSize!==null&&a.data.size<n.minSize.value&&(W(a,{code:U.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&a.data.size>n.maxSize.value&&(W(a,{code:U.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let i=this._def.valueType;function o(l){let c=new Set;for(let u of l){if(u.status==="aborted")return ee;u.status==="dirty"&&t.dirty(),c.add(u.value)}return{status:t.value,value:c}}let s=[...a.data.values()].map((l,c)=>i._parse(new Mt(a,l,a.path,c)));return a.common.async?Promise.all(s).then(l=>o(l)):o(s)}min(e,t){return new r({...this._def,minSize:{value:e,message:Y.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:Y.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};jn.create=(r,e)=>new jn({valueType:r,minSize:null,maxSize:null,typeName:re.ZodSet,...se(e)});var wi=class r extends ue{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.function)return W(t,{code:U.invalid_type,expected:j.function,received:t.parsedType}),ee;function a(s,l){return va({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Gn(),mr].filter(c=>!!c),issueData:{code:U.invalid_arguments,argumentsError:l}})}function n(s,l){return va({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Gn(),mr].filter(c=>!!c),issueData:{code:U.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Rr){let s=this;return ot(async function(...l){let c=new yt([]),u=await s._def.args.parseAsync(l,i).catch(d=>{throw c.addIssue(a(l,d)),c}),p=await Reflect.apply(o,this,u);return await s._def.returns._def.type.parseAsync(p,i).catch(d=>{throw c.addIssue(n(p,d)),c})})}else{let s=this;return ot(function(...l){let c=s._def.args.safeParse(l,i);if(!c.success)throw new yt([a(l,c.error)]);let u=Reflect.apply(o,this,c.data),p=s._def.returns.safeParse(u,i);if(!p.success)throw new yt([n(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:tr.create(e).rest(gr.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,a){return new r({args:e||tr.create([]).rest(gr.create()),returns:t||gr.create(),typeName:re.ZodFunction,...se(a)})}},tn=class extends ue{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};tn.create=(r,e)=>new tn({getter:r,typeName:re.ZodLazy,...se(e)});var rn=class extends ue{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return W(t,{received:t.data,code:U.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}};rn.create=(r,e)=>new rn({value:r,typeName:re.ZodLiteral,...se(e)});function sd(r,e){return new nn({values:r,typeName:re.ZodEnum,...se(e)})}var nn=class r extends ue{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),a=this._def.values;return W(t,{expected:pe.joinValues(a),received:t.parsedType,code:U.invalid_type}),ee}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),a=this._def.values;return W(t,{received:t.data,code:U.invalid_enum_value,options:a}),ee}return ot(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(a=>!e.includes(a)),{...this._def,...t})}};nn.create=sd;var an=class extends ue{_parse(e){let t=pe.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==j.string&&a.parsedType!==j.number){let n=pe.objectValues(t);return W(a,{expected:pe.joinValues(n),received:a.parsedType,code:U.invalid_type}),ee}if(this._cache||(this._cache=new Set(pe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=pe.objectValues(t);return W(a,{received:a.data,code:U.invalid_enum_value,options:n}),ee}return ot(e.data)}get enum(){return this._def.values}};an.create=(r,e)=>new an({values:r,typeName:re.ZodNativeEnum,...se(e)});var Rr=class extends ue{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.promise&&t.common.async===!1)return W(t,{code:U.invalid_type,expected:j.promise,received:t.parsedType}),ee;let a=t.parsedType===j.promise?t.data:Promise.resolve(t.data);return ot(a.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Rr.create=(r,e)=>new Rr({type:r,typeName:re.ZodPromise,...se(e)});var Ft=class extends ue{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===re.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:a}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{W(a,o),o.fatal?t.abort():t.dirty()},get path(){return a.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let o=n.transform(a.data,i);if(a.common.async)return Promise.resolve(o).then(async s=>{if(t.value==="aborted")return ee;let l=await this._def.schema._parseAsync({data:s,path:a.path,parent:a});return l.status==="aborted"?ee:l.status==="dirty"?qr(l.value):t.value==="dirty"?qr(l.value):l});{if(t.value==="aborted")return ee;let s=this._def.schema._parseSync({data:o,path:a.path,parent:a});return s.status==="aborted"?ee:s.status==="dirty"?qr(s.value):t.value==="dirty"?qr(s.value):s}}if(n.type==="refinement"){let o=s=>{let l=n.refinement(s,i);if(a.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(a.common.async===!1){let s=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return s.status==="aborted"?ee:(s.status==="dirty"&&t.dirty(),o(s.value),{status:t.value,value:s.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(s=>s.status==="aborted"?ee:(s.status==="dirty"&&t.dirty(),o(s.value).then(()=>({status:t.value,value:s.value}))))}if(n.type==="transform")if(a.common.async===!1){let o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!xr(o))return ee;let s=n.transform(o.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>xr(o)?Promise.resolve(n.transform(o.value,i)).then(s=>({status:t.value,value:s})):ee);pe.assertNever(n)}};Ft.create=(r,e,t)=>new Ft({schema:r,typeName:re.ZodEffects,effect:e,...se(t)});Ft.createWithPreprocess=(r,e,t)=>new Ft({schema:e,effect:{type:"preprocess",transform:r},typeName:re.ZodEffects,...se(t)});var Lt=class extends ue{_parse(e){return this._getType(e)===j.undefined?ot(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Lt.create=(r,e)=>new Lt({innerType:r,typeName:re.ZodOptional,...se(e)});var rr=class extends ue{_parse(e){return this._getType(e)===j.null?ot(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rr.create=(r,e)=>new rr({innerType:r,typeName:re.ZodNullable,...se(e)});var on=class extends ue{_parse(e){let{ctx:t}=this._processInputParams(e),a=t.data;return t.parsedType===j.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};on.create=(r,e)=>new on({innerType:r,typeName:re.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...se(e)});var sn=class extends ue{_parse(e){let{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return zn(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new yt(a.common.issues)},input:a.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new yt(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};sn.create=(r,e)=>new sn({innerType:r,typeName:re.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...se(e)});var qn=class extends ue{_parse(e){if(this._getType(e)!==j.nan){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.nan,received:a.parsedType}),ee}return{status:"valid",value:e.data}}};qn.create=r=>new qn({typeName:re.ZodNaN,...se(r)});var Nb=Symbol("zod_brand"),_a=class extends ue{_parse(e){let{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}},Sa=class r extends ue{_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?ee:i.status==="dirty"?(t.dirty(),qr(i.value)):this._def.out._parseAsync({data:i.value,path:a.path,parent:a})})();{let n=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?ee:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:a.path,parent:a})}}static create(e,t){return new r({in:e,out:t,typeName:re.ZodPipeline})}},ln=class extends ue{_parse(e){let t=this._def.innerType._parse(e),a=n=>(xr(n)&&(n.value=Object.freeze(n.value)),n);return zn(t)?t.then(n=>a(n)):a(t)}unwrap(){return this._def.innerType}};ln.create=(r,e)=>new ln({innerType:r,typeName:re.ZodReadonly,...se(e)});function nd(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function ld(r,e={},t){return r?Ir.create().superRefine((a,n)=>{let i=r(a);if(i instanceof Promise)return i.then(o=>{if(!o){let s=nd(e,a),l=s.fatal??t??!0;n.addIssue({code:"custom",...s,fatal:l})}});if(!i){let o=nd(e,a),s=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:s})}}):Ir.create()}var Ob={object:bt.lazycreate},re;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(re||(re={}));var Lb=(r,e={message:`Input not instance of ${r.name}`})=>ld(t=>t instanceof r,e),cd=Ar.create,ud=Kr.create,Mb=qn.create,Fb=$r.create,dd=Xr.create,Bb=Yr.create,Gb=Hn.create,zb=Zr.create,Ub=Jr.create,Hb=Ir.create,Vb=gr.create,Wb=jt.create,jb=Vn.create,qb=fr.create,Kb=bt.create,$b=bt.strictCreate,Xb=Qr.create,Yb=Si.create,Zb=en.create,Jb=tr.create,Qb=Ei.create,ev=Wn.create,tv=jn.create,rv=wi.create,nv=tn.create,av=rn.create,iv=nn.create,ov=an.create,sv=Rr.create,lv=Ft.create,cv=Lt.create,uv=rr.create,dv=Ft.createWithPreprocess,pv=Sa.create,mv=()=>cd().optional(),hv=()=>ud().optional(),gv=()=>dd().optional(),fv={string:r=>Ar.create({...r,coerce:!0}),number:r=>Kr.create({...r,coerce:!0}),boolean:r=>Xr.create({...r,coerce:!0}),bigint:r=>$r.create({...r,coerce:!0}),date:r=>Yr.create({...r,coerce:!0})};var yv=ee;var Kn="2025-03-26",pd=[Kn,"2024-11-05","2024-10-07"],Ci="2.0",md=h.union([h.string(),h.number().int()]),hd=h.string(),bv=h.object({progressToken:h.optional(md)}).passthrough(),qt=h.object({_meta:h.optional(bv)}).passthrough(),kt=h.object({method:h.string(),params:h.optional(qt)}),Ea=h.object({_meta:h.optional(h.object({}).passthrough())}).passthrough(),nr=h.object({method:h.string(),params:h.optional(Ea)}),Kt=h.object({_meta:h.optional(h.object({}).passthrough())}).passthrough(),ki=h.union([h.string(),h.number().int()]),gd=h.object({jsonrpc:h.literal(Ci),id:ki}).merge(kt).strict(),Ti=r=>gd.safeParse(r).success,fd=h.object({jsonrpc:h.literal(Ci)}).merge(nr).strict(),yd=r=>fd.safeParse(r).success,bd=h.object({jsonrpc:h.literal(Ci),id:ki,result:Kt}).strict(),wa=r=>bd.safeParse(r).success,Bt;(function(r){r[r.ConnectionClosed=-32e3]="ConnectionClosed",r[r.RequestTimeout=-32001]="RequestTimeout",r[r.ParseError=-32700]="ParseError",r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError"})(Bt||(Bt={}));var vd=h.object({jsonrpc:h.literal(Ci),id:ki,error:h.object({code:h.number().int(),message:h.string(),data:h.optional(h.unknown())})}).strict(),_d=r=>vd.safeParse(r).success,$n=h.union([gd,fd,bd,vd]),cn=Kt.strict(),xi=nr.extend({method:h.literal("notifications/cancelled"),params:Ea.extend({requestId:ki,reason:h.string().optional()})}),Sd=h.object({name:h.string(),version:h.string()}).passthrough(),vv=h.object({experimental:h.optional(h.object({}).passthrough()),sampling:h.optional(h.object({}).passthrough()),roots:h.optional(h.object({listChanged:h.optional(h.boolean())}).passthrough())}).passthrough(),_v=kt.extend({method:h.literal("initialize"),params:qt.extend({protocolVersion:h.string(),capabilities:vv,clientInfo:Sd})});var Sv=h.object({experimental:h.optional(h.object({}).passthrough()),logging:h.optional(h.object({}).passthrough()),completions:h.optional(h.object({}).passthrough()),prompts:h.optional(h.object({listChanged:h.optional(h.boolean())}).passthrough()),resources:h.optional(h.object({subscribe:h.optional(h.boolean()),listChanged:h.optional(h.boolean())}).passthrough()),tools:h.optional(h.object({listChanged:h.optional(h.boolean())}).passthrough())}).passthrough(),$s=Kt.extend({protocolVersion:h.string(),capabilities:Sv,serverInfo:Sd,instructions:h.optional(h.string())}),Ed=nr.extend({method:h.literal("notifications/initialized")}),wd=r=>Ed.safeParse(r).success,Ai=kt.extend({method:h.literal("ping")}),Ev=h.object({progress:h.number(),total:h.optional(h.number()),message:h.optional(h.string())}).passthrough(),Ii=nr.extend({method:h.literal("notifications/progress"),params:Ea.merge(Ev).extend({progressToken:md})}),Ri=kt.extend({params:qt.extend({cursor:h.optional(hd)}).optional()}),Pi=Kt.extend({nextCursor:h.optional(hd)}),Cd=h.object({uri:h.string(),mimeType:h.optional(h.string())}).passthrough(),kd=Cd.extend({text:h.string()}),Td=Cd.extend({blob:h.string().base64()}),wv=h.object({uri:h.string(),name:h.string(),description:h.optional(h.string()),mimeType:h.optional(h.string())}).passthrough(),Cv=h.object({uriTemplate:h.string(),name:h.string(),description:h.optional(h.string()),mimeType:h.optional(h.string())}).passthrough(),kv=Ri.extend({method:h.literal("resources/list")}),Xs=Pi.extend({resources:h.array(wv)}),Tv=Ri.extend({method:h.literal("resources/templates/list")}),Ys=Pi.extend({resourceTemplates:h.array(Cv)}),xv=kt.extend({method:h.literal("resources/read"),params:qt.extend({uri:h.string()})}),Zs=Kt.extend({contents:h.array(h.union([kd,Td]))}),Av=nr.extend({method:h.literal("notifications/resources/list_changed")}),Iv=kt.extend({method:h.literal("resources/subscribe"),params:qt.extend({uri:h.string()})}),Rv=kt.extend({method:h.literal("resources/unsubscribe"),params:qt.extend({uri:h.string()})}),Pv=nr.extend({method:h.literal("notifications/resources/updated"),params:Ea.extend({uri:h.string()})}),Dv=h.object({name:h.string(),description:h.optional(h.string()),required:h.optional(h.boolean())}).passthrough(),Nv=h.object({name:h.string(),description:h.optional(h.string()),arguments:h.optional(h.array(Dv))}).passthrough(),Ov=Ri.extend({method:h.literal("prompts/list")}),Js=Pi.extend({prompts:h.array(Nv)}),Lv=kt.extend({method:h.literal("prompts/get"),params:qt.extend({name:h.string(),arguments:h.optional(h.record(h.string()))})}),Di=h.object({type:h.literal("text"),text:h.string()}).passthrough(),Ni=h.object({type:h.literal("image"),data:h.string().base64(),mimeType:h.string()}).passthrough(),Oi=h.object({type:h.literal("audio"),data:h.string().base64(),mimeType:h.string()}).passthrough(),xd=h.object({type:h.literal("resource"),resource:h.union([kd,Td])}).passthrough(),Mv=h.object({role:h.enum(["user","assistant"]),content:h.union([Di,Ni,Oi,xd])}).passthrough(),Qs=Kt.extend({description:h.optional(h.string()),messages:h.array(Mv)}),Fv=nr.extend({method:h.literal("notifications/prompts/list_changed")}),Bv=h.object({title:h.optional(h.string()),readOnlyHint:h.optional(h.boolean()),destructiveHint:h.optional(h.boolean()),idempotentHint:h.optional(h.boolean()),openWorldHint:h.optional(h.boolean())}).passthrough(),Gv=h.object({name:h.string(),description:h.optional(h.string()),inputSchema:h.object({type:h.literal("object"),properties:h.optional(h.object({}).passthrough()),required:h.optional(h.array(h.string()))}).passthrough(),outputSchema:h.optional(h.object({type:h.literal("object"),properties:h.optional(h.object({}).passthrough()),required:h.optional(h.array(h.string()))}).passthrough()),annotations:h.optional(Bv)}).passthrough(),zv=Ri.extend({method:h.literal("tools/list")}),el=Pi.extend({tools:h.array(Gv)}),Li=Kt.extend({content:h.array(h.union([Di,Ni,Oi,xd])).default([]),structuredContent:h.object({}).passthrough().optional(),isError:h.optional(h.boolean())}),mA=Li.or(Kt.extend({toolResult:h.unknown()})),Uv=kt.extend({method:h.literal("tools/call"),params:qt.extend({name:h.string(),arguments:h.optional(h.record(h.unknown()))})}),tl=nr.extend({method:h.literal("notifications/tools/list_changed")}),Ad=h.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Hv=kt.extend({method:h.literal("logging/setLevel"),params:qt.extend({level:Ad})}),rl=nr.extend({method:h.literal("notifications/message"),params:Ea.extend({level:Ad,logger:h.optional(h.string()),data:h.unknown()})}),Vv=h.object({name:h.string().optional()}).passthrough(),Wv=h.object({hints:h.optional(h.array(Vv)),costPriority:h.optional(h.number().min(0).max(1)),speedPriority:h.optional(h.number().min(0).max(1)),intelligencePriority:h.optional(h.number().min(0).max(1))}).passthrough(),jv=h.object({role:h.enum(["user","assistant"]),content:h.union([Di,Ni,Oi])}).passthrough(),qv=kt.extend({method:h.literal("sampling/createMessage"),params:qt.extend({messages:h.array(jv),systemPrompt:h.optional(h.string()),includeContext:h.optional(h.enum(["none","thisServer","allServers"])),temperature:h.optional(h.number()),maxTokens:h.number().int(),stopSequences:h.optional(h.array(h.string())),metadata:h.optional(h.object({}).passthrough()),modelPreferences:h.optional(Wv)})}),Kv=Kt.extend({model:h.string(),stopReason:h.optional(h.enum(["endTurn","stopSequence","maxTokens"]).or(h.string())),role:h.enum(["user","assistant"]),content:h.discriminatedUnion("type",[Di,Ni,Oi])}),$v=h.object({type:h.literal("ref/resource"),uri:h.string()}).passthrough(),Xv=h.object({type:h.literal("ref/prompt"),name:h.string()}).passthrough(),Yv=kt.extend({method:h.literal("completion/complete"),params:qt.extend({ref:h.union([Xv,$v]),argument:h.object({name:h.string(),value:h.string()}).passthrough()})}),nl=Kt.extend({completion:h.object({values:h.array(h.string()).max(100),total:h.optional(h.number().int()),hasMore:h.optional(h.boolean())}).passthrough()}),Zv=h.object({uri:h.string().startsWith("file://"),name:h.optional(h.string())}).passthrough(),Jv=kt.extend({method:h.literal("roots/list")}),Qv=Kt.extend({roots:h.array(Zv)}),e_=nr.extend({method:h.literal("notifications/roots/list_changed")}),hA=h.union([Ai,_v,Yv,Hv,Lv,Ov,kv,Tv,xv,Iv,Rv,Uv,zv]),gA=h.union([xi,Ii,Ed,e_]),fA=h.union([cn,Kv,Qv]),yA=h.union([Ai,qv,Jv]),bA=h.union([xi,Ii,rl,Pv,Av,tl,Fv]),vA=h.union([cn,$s,nl,Qs,Js,Xs,Ys,Zs,Li,el]),Gt=class extends Error{constructor(e,t,a){super(`MCP error ${e}: ${t}`),this.code=e,this.data=a,this.name="McpError"}};var t_=6e4,Mi=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this.setNotificationHandler(xi,t=>{let a=this._requestHandlerAbortControllers.get(t.params.requestId);a?.abort(t.params.reason)}),this.setNotificationHandler(Ii,t=>{this._onprogress(t)}),this.setRequestHandler(Ai,t=>({}))}_setupTimeout(e,t,a,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:a,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let a=Date.now()-t.startTime;if(t.maxTotalTimeout&&a>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Gt(Bt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:a});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=t=>{this._onerror(t)},this._transport.onmessage=(t,a)=>{wa(t)||_d(t)?this._onresponse(t):Ti(t)?this._onrequest(t,a):yd(t)?this._onnotification(t):this._onerror(new Error(`Unknown message type: ${JSON.stringify(t)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let a=new Gt(Bt.ConnectionClosed,"Connection closed");for(let n of t.values())n(a)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let a=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){var a,n,i,o;let s=(a=this._requestHandlers.get(e.method))!==null&&a!==void 0?a:this.fallbackRequestHandler;if(s===void 0){(n=this._transport)===null||n===void 0||n.send({jsonrpc:"2.0",id:e.id,error:{code:Bt.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let c={signal:l.signal,sessionId:(i=this._transport)===null||i===void 0?void 0:i.sessionId,_meta:(o=e.params)===null||o===void 0?void 0:o._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,p,m)=>this.request(u,p,{...m,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id};Promise.resolve().then(()=>s(e,c)).then(u=>{var p;if(!l.signal.aborted)return(p=this._transport)===null||p===void 0?void 0:p.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var p,m;if(!l.signal.aborted)return(p=this._transport)===null||p===void 0?void 0:p.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Bt.InternalError,message:(m=u.message)!==null&&m!==void 0?m:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...a}=e.params,n=Number(t),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){o(l);return}i(a)}_onresponse(e){let t=Number(e.id),a=this._responseHandlers.get(t);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),wa(e))a(e);else{let n=new Gt(e.error.code,e.error.message,e.error.data);a(n)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,a){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}=a??{};return new Promise((s,l)=>{var c,u,p,m,d,g;if(!this._transport){l(new Error("Not connected"));return}((c=this._options)===null||c===void 0?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(u=a?.signal)===null||u===void 0||u.throwIfAborted();let f=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:f};a?.onprogress&&(this._progressHandlers.set(f,a.onprogress),y.params={...e.params,_meta:{...((p=e.params)===null||p===void 0?void 0:p._meta)||{},progressToken:f}});let v=I=>{var D;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),(D=this._transport)===null||D===void 0||D.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(I)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}).catch(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`))),l(I)};this._responseHandlers.set(f,I=>{var D;if(!(!((D=a?.signal)===null||D===void 0)&&D.aborted)){if(I instanceof Error)return l(I);try{let C=t.parse(I.result);s(C)}catch(C){l(C)}}}),(m=a?.signal)===null||m===void 0||m.addEventListener("abort",()=>{var I;v((I=a?.signal)===null||I===void 0?void 0:I.reason)});let T=(d=a?.timeout)!==null&&d!==void 0?d:t_,E=()=>v(new Gt(Bt.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(f,T,a?.maxTotalTimeout,E,(g=a?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(y,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}).catch(I=>{this._cleanupTimeout(f),l(I)})})}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let a={...e,jsonrpc:"2.0"};await this._transport.send(a,t)}setRequestHandler(e,t){let a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(n,i)=>Promise.resolve(t(e.parse(n),i)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(t(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Id(r,e){return Object.entries(e).reduce((t,[a,n])=>(n&&typeof n=="object"?t[a]=t[a]?{...t[a],...n}:n:t[a]=n,t),{...r})}var Pm=Es(Rm(),1),ka=class extends Mi{constructor(e,t){var a;super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=t?.capabilities)!==null&&a!==void 0?a:{},this._ajv=new Pm.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Id(this._capabilities,e)}assertCapability(e,t){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[e]))throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let a=await this.request({method:"initialize",params:{protocolVersion:Kn,capabilities:this._capabilities,clientInfo:this._clientInfo}},$s,t);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!pd.includes(a.protocolVersion))throw new Error(`Server's protocol version is not supported: ${a.protocolVersion}`);this._serverCapabilities=a.capabilities,this._serverVersion=a.serverInfo,this._instructions=a.instructions,await this.notification({method:"notifications/initialized"})}catch(a){throw this.close(),a}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var t,a,n,i,o;switch(e){case"logging/setLevel":if(!(!((t=this._serverCapabilities)===null||t===void 0)&&t.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var t;switch(e){case"notifications/roots/list_changed":if(!(!((t=this._capabilities.roots)===null||t===void 0)&&t.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},cn,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},nl,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},cn,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Qs,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},Js,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},Xs,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},Ys,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},Zs,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},cn,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},cn,t)}async callTool(e,t=Li,a){let n=await this.request({method:"tools/call",params:e},t,a),i=this.getToolOutputValidator(e.name);if(i){if(!n.structuredContent&&!n.isError)throw new Gt(Bt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{if(!i(n.structuredContent))throw new Gt(Bt.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(i.errors)}`)}catch(o){throw o instanceof Gt?o:new Gt(Bt.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return n}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let t of e)if(t.outputSchema)try{let a=this._ajv.compile(t.outputSchema);this._cachedToolOutputValidators.set(t.name,a)}catch(a){console.warn(`Failed to compile output schema for tool ${t.name}: ${a}`)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let a=await this.request({method:"tools/list",params:e},el,t);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Al;Al=globalThis.crypto;async function OS(r){return(await Al).getRandomValues(new Uint8Array(r))}async function LS(r){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",t="",a=await OS(r);for(let n=0;n<r;n++){let i=a[n]%e.length;t+=e[i]}return t}async function MS(r){return await LS(r)}async function FS(r){let e=await(await Al).subtle.digest("SHA-256",new TextEncoder().encode(r));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Il(r){if(r||(r=43),r<43||r>128)throw`Expected a length between 43 and 128. Received ${r}.`;let e=await MS(r),t=await FS(e);return{code_verifier:e,code_challenge:t}}var Dm=h.object({resource:h.string().url(),authorization_servers:h.array(h.string().url()).optional(),jwks_uri:h.string().url().optional(),scopes_supported:h.array(h.string()).optional(),bearer_methods_supported:h.array(h.string()).optional(),resource_signing_alg_values_supported:h.array(h.string()).optional(),resource_name:h.string().optional(),resource_documentation:h.string().optional(),resource_policy_uri:h.string().url().optional(),resource_tos_uri:h.string().url().optional(),tls_client_certificate_bound_access_tokens:h.boolean().optional(),authorization_details_types_supported:h.array(h.string()).optional(),dpop_signing_alg_values_supported:h.array(h.string()).optional(),dpop_bound_access_tokens_required:h.boolean().optional()}).passthrough(),Nm=h.object({issuer:h.string(),authorization_endpoint:h.string(),token_endpoint:h.string(),registration_endpoint:h.string().optional(),scopes_supported:h.array(h.string()).optional(),response_types_supported:h.array(h.string()),response_modes_supported:h.array(h.string()).optional(),grant_types_supported:h.array(h.string()).optional(),token_endpoint_auth_methods_supported:h.array(h.string()).optional(),token_endpoint_auth_signing_alg_values_supported:h.array(h.string()).optional(),service_documentation:h.string().optional(),revocation_endpoint:h.string().optional(),revocation_endpoint_auth_methods_supported:h.array(h.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:h.array(h.string()).optional(),introspection_endpoint:h.string().optional(),introspection_endpoint_auth_methods_supported:h.array(h.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:h.array(h.string()).optional(),code_challenge_methods_supported:h.array(h.string()).optional()}).passthrough(),Rl=h.object({access_token:h.string(),token_type:h.string(),expires_in:h.number().optional(),scope:h.string().optional(),refresh_token:h.string().optional()}).strip(),vI=h.object({error:h.string(),error_description:h.string().optional(),error_uri:h.string().optional()}),BS=h.object({redirect_uris:h.array(h.string()).refine(r=>r.every(e=>URL.canParse(e)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:h.string().optional(),grant_types:h.array(h.string()).optional(),response_types:h.array(h.string()).optional(),client_name:h.string().optional(),client_uri:h.string().optional(),logo_uri:h.string().optional(),scope:h.string().optional(),contacts:h.array(h.string()).optional(),tos_uri:h.string().optional(),policy_uri:h.string().optional(),jwks_uri:h.string().optional(),jwks:h.any().optional(),software_id:h.string().optional(),software_version:h.string().optional()}).strip(),GS=h.object({client_id:h.string(),client_secret:h.string().optional(),client_id_issued_at:h.number().optional(),client_secret_expires_at:h.number().optional()}).strip(),Om=BS.merge(GS),_I=h.object({error:h.string(),error_description:h.string().optional()}).strip(),SI=h.object({token:h.string(),token_type_hint:h.string().optional()}).strip();var vt=class extends Error{constructor(e){super(e??"Unauthorized")}};async function Or(r,{serverUrl:e,authorizationCode:t,scope:a,resourceMetadataUrl:n}){let i=e;try{let m=await zS(n||e);m.authorization_servers&&m.authorization_servers.length>0&&(i=m.authorization_servers[0])}catch(m){console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server",m)}let o=await US(i),s=await Promise.resolve(r.clientInformation());if(!s){if(t!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!r.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let m=await jS(i,{metadata:o,clientMetadata:r.clientMetadata});await r.saveClientInformation(m),s=m}if(t!==void 0){let m=await r.codeVerifier(),d=await VS(i,{metadata:o,clientInformation:s,authorizationCode:t,codeVerifier:m,redirectUri:r.redirectUrl});return await r.saveTokens(d),"AUTHORIZED"}let l=await r.tokens();if(l?.refresh_token)try{let m=await WS(i,{metadata:o,clientInformation:s,refreshToken:l.refresh_token});return await r.saveTokens(m),"AUTHORIZED"}catch(m){console.error("Could not refresh OAuth tokens:",m)}let c=r.state?await r.state():void 0,{authorizationUrl:u,codeVerifier:p}=await HS(i,{metadata:o,clientInformation:s,state:c,redirectUrl:r.redirectUrl,scope:a||r.clientMetadata.scope});return await r.saveCodeVerifier(p),await r.redirectToAuthorization(u),"REDIRECT"}function to(r){let e=r.headers.get("WWW-Authenticate");if(!e)return;let[t,a]=e.split(" ");if(t.toLowerCase()!=="bearer"||!a){console.log("Invalid WWW-Authenticate header format, expected 'Bearer'");return}let i=/resource_metadata="([^"]*)"/.exec(e);if(i)try{return new URL(i[1])}catch{console.log("Invalid resource metadata url: ",i[1]);return}}async function zS(r,e){var t;let a;e?.resourceMetadataUrl?a=new URL(e?.resourceMetadataUrl):a=new URL("/.well-known/oauth-protected-resource",r);let n;try{n=await fetch(a,{headers:{"MCP-Protocol-Version":(t=e?.protocolVersion)!==null&&t!==void 0?t:Kn}})}catch(i){if(i instanceof TypeError)n=await fetch(a);else throw i}if(n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Dm.parse(await n.json())}async function US(r,e){var t;let a=new URL("/.well-known/oauth-authorization-server",r),n;try{n=await fetch(a,{headers:{"MCP-Protocol-Version":(t=e?.protocolVersion)!==null&&t!==void 0?t:Kn}})}catch(i){if(i instanceof TypeError)n=await fetch(a);else throw i}if(n.status!==404){if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth metadata`);return Nm.parse(await n.json())}}async function HS(r,{metadata:e,clientInformation:t,redirectUrl:a,scope:n,state:i}){let o="code",s="S256",l;if(e){if(l=new URL(e.authorization_endpoint),!e.response_types_supported.includes(o))throw new Error(`Incompatible auth server: does not support response type ${o}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(s))throw new Error(`Incompatible auth server: does not support code challenge method ${s}`)}else l=new URL("/authorize",r);let c=await Il(),u=c.code_verifier,p=c.code_challenge;return l.searchParams.set("response_type",o),l.searchParams.set("client_id",t.client_id),l.searchParams.set("code_challenge",p),l.searchParams.set("code_challenge_method",s),l.searchParams.set("redirect_uri",String(a)),i&&l.searchParams.set("state",i),n&&l.searchParams.set("scope",n),{authorizationUrl:l,codeVerifier:u}}async function VS(r,{metadata:e,clientInformation:t,authorizationCode:a,codeVerifier:n,redirectUri:i}){let o="authorization_code",s;if(e){if(s=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(o))throw new Error(`Incompatible auth server: does not support grant type ${o}`)}else s=new URL("/token",r);let l=new URLSearchParams({grant_type:o,client_id:t.client_id,code:a,code_verifier:n,redirect_uri:String(i)});t.client_secret&&l.set("client_secret",t.client_secret);let c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return Rl.parse(await c.json())}async function WS(r,{metadata:e,clientInformation:t,refreshToken:a}){let n="refresh_token",i;if(e){if(i=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(n))throw new Error(`Incompatible auth server: does not support grant type ${n}`)}else i=new URL("/token",r);let o=new URLSearchParams({grant_type:n,client_id:t.client_id,refresh_token:a});t.client_secret&&o.set("client_secret",t.client_secret);let s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o});if(!s.ok)throw new Error(`Token refresh failed: HTTP ${s.status}`);return Rl.parse({refresh_token:a,...await s.json()})}async function jS(r,{metadata:e,clientMetadata:t}){let a;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");a=new URL(e.registration_endpoint)}else a=new URL("/register",r);let n=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Dynamic client registration failed: HTTP ${n.status}`);return Om.parse(await n.json())}var ro=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Pl(r){}function no(r){if(typeof r=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=Pl,onError:t=Pl,onRetry:a=Pl,onComment:n}=r,i="",o=!0,s,l="",c="";function u(f){let y=o?f.replace(/^\xEF\xBB\xBF/,""):f,[v,T]=qS(`${i}${y}`);for(let E of v)p(E);i=T,o=!1}function p(f){if(f===""){d();return}if(f.startsWith(":")){n&&n(f.slice(f.startsWith(": ")?2:1));return}let y=f.indexOf(":");if(y!==-1){let v=f.slice(0,y),T=f[y+1]===" "?2:1,E=f.slice(y+T);m(v,E,f);return}m(f,"",f)}function m(f,y,v){switch(f){case"event":c=y;break;case"data":l=`${l}${y}
|
|
3254
|
+
`),e.createGroup("actions").setItemPadding(25),e.createGroup("messages").setItemPadding(10),e})();this.config={...this.config,...e},this.tokenWindow.size=this.config.maxTokens||4096}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(e){let t={role:"user",content:e};this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(t),customData:t}),await this.processMessages();let n=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return n?.role=="assistant"&&n.content||""}addAssistantMessage(e){let t={role:"assistant",content:e};this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(t),customData:t})}addUserMessage(e){let t={role:"user",content:e};this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(t),customData:t})}getMessages(){return this.messageGroup.items.map(e=>e.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),Tr.debugEnabled&&Tr.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(a=>a.customData),messages:this.messageGroup.items.map(a=>a.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let t=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(t?.role=="user"||t?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(t?.role=="assistant"&&t?.tool_calls?.length){for(let a of t.tool_calls)await this.processToolCall(a);await this.processMessages()}}async trimMessages(){for(this.tokenWindow.removeOverflow();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendToAPI(e){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let t=0;for(let l=this.messageGroup.items.length-1;l>=0;l--){let c=this.messageGroup.items[l].customData;if(c.role=="assistant"&&c.tool_calls){if(t+=1,t>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(c.role=="user")break}Tr.debugEnabled&&Tr.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(l=>l.customData),messages:this.messageGroup.items.map(l=>l.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let a={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(l=>l.customData)]};for(let l of this.toolGroup.getAll()){let c=l.customData;c.description&&c.description.length>1024&&Tr.warn(`Tool description for "${c.name}" is too long, it will be truncated.`);let u={type:"function",function:{name:c.name,description:(c.description||"").substring(0,1024),parameters:c.params}};a.tools.push(u)}a.user||delete a.user,a.tools.length||delete a.tools;let n={};if(n["Content-Type"]="application/json",this.config.apiKey&&(n.Authorization=`Bearer ${this.config.apiKey}`),e)return a;let i=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:n,body:JSON.stringify(a)});if(!i.ok){let l=`${i.status} ${i.statusText}`;try{let u=await i.json();l=u.errorText||u.error?.message||u.error||l}catch{}let c=new Error(l);throw c.code=i.status,c}let o=null,s=null;if(this.config.stream)for await(let l of uu(i.body)){if(l.data=="[DONE]")break;if(!l.data)continue;let c=JSON.parse(l.data);if(s){for(let u in c.choices[0].delta)if(typeof c.choices[0].delta[u]=="string"){if(u=="role"&&s[u]==c.choices[0].delta[u])continue;s[u]=(s[u]||"")+c.choices[0].delta[u]}for(let u of c.choices[0].delta.tool_calls||[]){if(s.tool_calls||(s.tool_calls=[]),!s.tool_calls[u.index]){s.tool_calls[u.index]=u;continue}let p=s.tool_calls[u.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(u.function?.name||""),p.function.arguments=(p.function.arguments||"")+(u.function?.arguments||"")}}else s={chunkID:c.id,...c.choices[0].delta};s?.content&&!s.content.startsWith("{")&&this.config.onAIMessage?.(s.content,!0)}else o=await i.json(),this.stats.tokensUsed+=o.usage?.total_tokens||0,Tr.debug(`Used ${o.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),s=o.choices?.[0]?.message;if(s||(Tr.warn("No response block in API response."),s={role:"assistant",content:""}),s.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(s),this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(s),customData:s}),s.content&&this.config.onAIMessage?.(s.content,!1)}processIncomingMessage(e){}registerTool(e){this.toolGroup.add({id:e.name,cannotRemove:!e.canRemove,content:JSON.stringify(e),customData:e})}async processToolCall(e){try{let a=this.toolGroup.items.find(s=>s.id==e.function.name)?.customData;if(!a)throw new Error(`Tool "${e.function.name}" not found.`);let n=JSON.parse(e.function.arguments);this.config.onAIToolStart?.(e.function.name,n);let i=await a.callback(n);typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success");let o={role:"tool",content:i,tool_call_id:e.id};this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(o),customData:o})}catch(t){Tr.warn(`Unable to process tool call for "${e?.function?.name}"`,t);let a={role:"tool",content:`Error: ${t.message}`,tool_call_id:e.id};this.messageGroup.add({id:"msg-"+Fn++,content:JSON.stringify(a),customData:a})}}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}};var De=function(){return De=Object.assign||function(e){for(var t,a=1,n=arguments.length;a<n;a++){t=arguments[a];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},De.apply(this,arguments)};function Xy(r,e,t,a){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function s(u){try{c(a.next(u))}catch(p){o(p)}}function l(u){try{c(a.throw(u))}catch(p){o(p)}}function c(u){u.done?i(u.value):n(u.value).then(s,l)}c((a=a.apply(r,e||[])).next())})}function Yy(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},a,n,i,o;return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function s(c){return function(u){return l([c,u])}}function l(c){if(a)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(t=0)),t;)try{if(a=1,n&&(i=c[0]&2?n.return:c[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,c[1])).done)return i;switch(n=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,n=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t)}catch(u){c=[6,u],n=0}finally{a=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function de(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],a=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&a>=r.length&&(r=void 0),{value:r&&r[a++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ue(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var a=t.call(r),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(s){o={error:s}}finally{try{n&&!n.done&&(t=a.return)&&t.call(a)}finally{if(o)throw o.error}}return i}var Zy="ENTRIES",Ku="KEYS",$u="VALUES",rt="",Os=function(){function r(e,t){var a=e._tree,n=Array.from(a.keys());this.set=e,this._type=t,this._path=n.length>0?[{node:a,keys:n}]:[]}return r.prototype.next=function(){var e=this.dive();return this.backtrack(),e},r.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var e=Bn(this._path),t=e.node,a=e.keys;if(Bn(a)===rt)return{done:!1,value:this.result()};var n=t.get(Bn(a));return this._path.push({node:n,keys:Array.from(n.keys())}),this.dive()},r.prototype.backtrack=function(){if(this._path.length!==0){var e=Bn(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}},r.prototype.key=function(){return this.set._prefix+this._path.map(function(e){var t=e.keys;return Bn(t)}).filter(function(e){return e!==rt}).join("")},r.prototype.value=function(){return Bn(this._path).node.get(rt)},r.prototype.result=function(){switch(this._type){case $u:return this.value();case Ku:return this.key();default:return[this.key(),this.value()]}},r.prototype[Symbol.iterator]=function(){return this},r}(),Bn=function(r){return r[r.length-1]},Jy=function(r,e,t){var a=new Map;if(e===void 0)return a;for(var n=e.length+1,i=n+t,o=new Uint8Array(i*n).fill(t+1),s=0;s<n;++s)o[s]=s;for(var l=1;l<i;++l)o[l*n]=l;return Xu(r,e,t,a,o,1,n,""),a},Xu=function(r,e,t,a,n,i,o,s){var l,c,u=i*o;try{e:for(var p=de(r.keys()),m=p.next();!m.done;m=p.next()){var d=m.value;if(d===rt){var g=n[u-1];g<=t&&a.set(s,[r.get(d),g])}else{for(var f=i,y=0;y<d.length;++y,++f){for(var v=d[y],T=o*f,E=T-o,I=n[T],D=Math.max(0,f-t-1),C=Math.min(o-1,f+t),M=D;M<C;++M){var F=v!==e[M],R=n[E+M]+ +F,G=n[E+M+1]+1,z=n[T+M]+1,O=n[T+M+1]=Math.min(R,G,z);O<I&&(I=O)}if(I>t)continue e}Xu(r.get(d),e,t,a,n,f,o,s+d)}}}catch(x){l={error:x}}finally{try{m&&!m.done&&(c=p.return)&&c.call(p)}finally{if(l)throw l.error}}},Ls=function(){function r(e,t){e===void 0&&(e=new Map),t===void 0&&(t=""),this._size=void 0,this._tree=e,this._prefix=t}return r.prototype.atPrefix=function(e){var t,a;if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");var n=Ue(bi(this._tree,e.slice(this._prefix.length)),2),i=n[0],o=n[1];if(i===void 0){var s=Ue(Vs(o),2),l=s[0],c=s[1];try{for(var u=de(l.keys()),p=u.next();!p.done;p=u.next()){var m=p.value;if(m!==rt&&m.startsWith(c)){var d=new Map;return d.set(m.slice(c.length),l.get(m)),new r(d,e)}}}catch(g){t={error:g}}finally{try{p&&!p.done&&(a=u.return)&&a.call(u)}finally{if(t)throw t.error}}}return new r(i,e)},r.prototype.clear=function(){this._size=void 0,this._tree.clear()},r.prototype.delete=function(e){return this._size=void 0,Qy(this._tree,e)},r.prototype.entries=function(){return new Os(this,Zy)},r.prototype.forEach=function(e){var t,a;try{for(var n=de(this),i=n.next();!i.done;i=n.next()){var o=Ue(i.value,2),s=o[0],l=o[1];e(s,l,this)}}catch(c){t={error:c}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}},r.prototype.fuzzyGet=function(e,t){return Jy(this._tree,e,t)},r.prototype.get=function(e){var t=zs(this._tree,e);return t!==void 0?t.get(rt):void 0},r.prototype.has=function(e){var t=zs(this._tree,e);return t!==void 0&&t.has(rt)},r.prototype.keys=function(){return new Os(this,Ku)},r.prototype.set=function(e,t){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var a=Ms(this._tree,e);return a.set(rt,t),this},Object.defineProperty(r.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var e=this.entries();!e.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),r.prototype.update=function(e,t){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var a=Ms(this._tree,e);return a.set(rt,t(a.get(rt))),this},r.prototype.fetch=function(e,t){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var a=Ms(this._tree,e),n=a.get(rt);return n===void 0&&a.set(rt,n=t()),n},r.prototype.values=function(){return new Os(this,$u)},r.prototype[Symbol.iterator]=function(){return this.entries()},r.from=function(e){var t,a,n=new r;try{for(var i=de(e),o=i.next();!o.done;o=i.next()){var s=Ue(o.value,2),l=s[0],c=s[1];n.set(l,c)}}catch(u){t={error:u}}finally{try{o&&!o.done&&(a=i.return)&&a.call(i)}finally{if(t)throw t.error}}return n},r.fromObject=function(e){return r.from(Object.entries(e))},r}(),bi=function(r,e,t){var a,n;if(t===void 0&&(t=[]),e.length===0||r==null)return[r,t];try{for(var i=de(r.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;if(s!==rt&&e.startsWith(s))return t.push([r,s]),bi(r.get(s),e.slice(s.length),t)}}catch(l){a={error:l}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return t.push([r,e]),bi(void 0,"",t)},zs=function(r,e){var t,a;if(e.length===0||r==null)return r;try{for(var n=de(r.keys()),i=n.next();!i.done;i=n.next()){var o=i.value;if(o!==rt&&e.startsWith(o))return zs(r.get(o),e.slice(o.length))}}catch(s){t={error:s}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}},Ms=function(r,e){var t,a,n=e.length;e:for(var i=0;r&&i<n;){try{for(var o=(t=void 0,de(r.keys())),s=o.next();!s.done;s=o.next()){var l=s.value;if(l!==rt&&e[i]===l[0]){for(var c=Math.min(n-i,l.length),u=1;u<c&&e[i+u]===l[u];)++u;var p=r.get(l);if(u===l.length)r=p;else{var m=new Map;m.set(l.slice(u),p),r.set(e.slice(i,i+u),m),r.delete(l),r=m}i+=u;continue e}}}catch(g){t={error:g}}finally{try{s&&!s.done&&(a=o.return)&&a.call(o)}finally{if(t)throw t.error}}var d=new Map;return r.set(e.slice(i),d),d}return r},Qy=function(r,e){var t=Ue(bi(r,e),2),a=t[0],n=t[1];if(a!==void 0){if(a.delete(rt),a.size===0)Yu(n);else if(a.size===1){var i=Ue(a.entries().next().value,2),o=i[0],s=i[1];Zu(n,o,s)}}},Yu=function(r){if(r.length!==0){var e=Ue(Vs(r),2),t=e[0],a=e[1];if(t.delete(a),t.size===0)Yu(r.slice(0,-1));else if(t.size===1){var n=Ue(t.entries().next().value,2),i=n[0],o=n[1];i!==rt&&Zu(r.slice(0,-1),i,o)}}},Zu=function(r,e,t){if(r.length!==0){var a=Ue(Vs(r),2),n=a[0],i=a[1];n.set(i+e,t),n.delete(i)}},Vs=function(r){return r[r.length-1]},ba,Ws="or",Ju="and",eb="and_not",Qu=function(){function r(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var t=e.autoVacuum==null||e.autoVacuum===!0?Gs:e.autoVacuum;this._options=De(De(De({},Bs),e),{autoVacuum:t,searchOptions:De(De({},Vu),e.searchOptions||{}),autoSuggestOptions:De(De({},ib),e.autoSuggestOptions||{})}),this._index=new Ls,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Hs,this.addFields(this._options.fields)}return r.prototype.add=function(e){var t,a,n,i,o,s,l=this._options,c=l.extractField,u=l.tokenize,p=l.processTerm,m=l.fields,d=l.idField,g=c(e,d);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(d,'"'));if(this._idToShortId.has(g))throw new Error("MiniSearch: duplicate ID ".concat(g));var f=this.addDocumentId(g);this.saveStoredFields(f,e);try{for(var y=de(m),v=y.next();!v.done;v=y.next()){var T=v.value,E=c(e,T);if(E!=null){var I=u(E.toString(),T),D=this._fieldIds[T],C=new Set(I).size;this.addFieldLength(f,D,this._documentCount-1,C);try{for(var M=(n=void 0,de(I)),F=M.next();!F.done;F=M.next()){var R=F.value,G=p(R,T);if(Array.isArray(G))try{for(var z=(o=void 0,de(G)),O=z.next();!O.done;O=z.next()){var x=O.value;this.addTerm(D,f,x)}}catch(A){o={error:A}}finally{try{O&&!O.done&&(s=z.return)&&s.call(z)}finally{if(o)throw o.error}}else G&&this.addTerm(D,f,G)}}catch(A){n={error:A}}finally{try{F&&!F.done&&(i=M.return)&&i.call(M)}finally{if(n)throw n.error}}}}}catch(A){t={error:A}}finally{try{v&&!v.done&&(a=y.return)&&a.call(y)}finally{if(t)throw t.error}}},r.prototype.addAll=function(e){var t,a;try{for(var n=de(e),i=n.next();!i.done;i=n.next()){var o=i.value;this.add(o)}}catch(s){t={error:s}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}},r.prototype.addAllAsync=function(e,t){var a=this;t===void 0&&(t={});var n=t.chunkSize,i=n===void 0?10:n,o={chunk:[],promise:Promise.resolve()},s=e.reduce(function(u,p,m){var d=u.chunk,g=u.promise;return d.push(p),(m+1)%i===0?{chunk:[],promise:g.then(function(){return new Promise(function(f){return setTimeout(f,0)})}).then(function(){return a.addAll(d)})}:{chunk:d,promise:g}},o),l=s.chunk,c=s.promise;return c.then(function(){return a.addAll(l)})},r.prototype.remove=function(e){var t,a,n,i,o,s,l=this._options,c=l.tokenize,u=l.processTerm,p=l.extractField,m=l.fields,d=l.idField,g=p(e,d);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(d,'"'));var f=this._idToShortId.get(g);if(f==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(g,": it is not in the index"));try{for(var y=de(m),v=y.next();!v.done;v=y.next()){var T=v.value,E=p(e,T);if(E!=null){var I=c(E.toString(),T),D=this._fieldIds[T],C=new Set(I).size;this.removeFieldLength(f,D,this._documentCount,C);try{for(var M=(n=void 0,de(I)),F=M.next();!F.done;F=M.next()){var R=F.value,G=u(R,T);if(Array.isArray(G))try{for(var z=(o=void 0,de(G)),O=z.next();!O.done;O=z.next()){var x=O.value;this.removeTerm(D,f,x)}}catch(A){o={error:A}}finally{try{O&&!O.done&&(s=z.return)&&s.call(z)}finally{if(o)throw o.error}}else G&&this.removeTerm(D,f,G)}}catch(A){n={error:A}}finally{try{F&&!F.done&&(i=M.return)&&i.call(M)}finally{if(n)throw n.error}}}}}catch(A){t={error:A}}finally{try{v&&!v.done&&(a=y.return)&&a.call(y)}finally{if(t)throw t.error}}this._storedFields.delete(f),this._documentIds.delete(f),this._idToShortId.delete(g),this._fieldLength.delete(f),this._documentCount-=1},r.prototype.removeAll=function(e){var t,a;if(e)try{for(var n=de(e),i=n.next();!i.done;i=n.next()){var o=i.value;this.remove(o)}}catch(s){t={error:s}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new Ls,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},r.prototype.discard=function(e){var t=this,a=this._idToShortId.get(e);if(a==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(e,": it is not in the index"));this._idToShortId.delete(e),this._documentIds.delete(a),this._storedFields.delete(a),(this._fieldLength.get(a)||[]).forEach(function(n,i){t.removeFieldLength(a,i,t._documentCount,n)}),this._fieldLength.delete(a),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},r.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var e=this._options.autoVacuum,t=e.minDirtFactor,a=e.minDirtCount,n=e.batchSize,i=e.batchWait;this.conditionalVacuum({batchSize:n,batchWait:i},{minDirtCount:a,minDirtFactor:t})}},r.prototype.discardAll=function(e){var t,a,n=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var i=de(e),o=i.next();!o.done;o=i.next()){var s=o.value;this.discard(s)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(a=i.return)&&a.call(i)}finally{if(t)throw t.error}}}finally{this._options.autoVacuum=n}this.maybeAutoVacuum()},r.prototype.replace=function(e){var t=this._options,a=t.idField,n=t.extractField,i=n(e,a);this.discard(i),this.add(e)},r.prototype.vacuum=function(e){return e===void 0&&(e={}),this.conditionalVacuum(e)},r.prototype.conditionalVacuum=function(e,t){var a=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&t,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var n=a._enqueuedVacuumConditions;return a._enqueuedVacuumConditions=Hs,a.performVacuuming(e,n)}),this._enqueuedVacuum)):this.vacuumConditionsMet(t)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)},r.prototype.performVacuuming=function(e,t){return Xy(this,void 0,void 0,function(){var a,n,i,o,s,l,c,u,p,m,d,g,f,y,v,T,E,I,D,C,M,F,R,G,z;return Yy(this,function(O){switch(O.label){case 0:if(a=this._dirtCount,!this.vacuumConditionsMet(t))return[3,10];n=e.batchSize||Us.batchSize,i=e.batchWait||Us.batchWait,o=1,O.label=1;case 1:O.trys.push([1,7,8,9]),s=de(this._index),l=s.next(),O.label=2;case 2:if(l.done)return[3,6];c=Ue(l.value,2),u=c[0],p=c[1];try{for(m=(F=void 0,de(p)),d=m.next();!d.done;d=m.next()){g=Ue(d.value,2),f=g[0],y=g[1];try{for(v=(G=void 0,de(y)),T=v.next();!T.done;T=v.next())E=Ue(T.value,1),I=E[0],!this._documentIds.has(I)&&(y.size<=1?p.delete(f):y.delete(I))}catch(x){G={error:x}}finally{try{T&&!T.done&&(z=v.return)&&z.call(v)}finally{if(G)throw G.error}}}}catch(x){F={error:x}}finally{try{d&&!d.done&&(R=m.return)&&R.call(m)}finally{if(F)throw F.error}}return this._index.get(u).size===0&&this._index.delete(u),o%n!==0?[3,4]:[4,new Promise(function(x){return setTimeout(x,i)})];case 3:O.sent(),O.label=4;case 4:o+=1,O.label=5;case 5:return l=s.next(),[3,2];case 6:return[3,9];case 7:return D=O.sent(),C={error:D},[3,9];case 8:try{l&&!l.done&&(M=s.return)&&M.call(s)}finally{if(C)throw C.error}return[7];case 9:this._dirtCount-=a,O.label=10;case 10:return[4,null];case 11:return O.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},r.prototype.vacuumConditionsMet=function(e){if(e==null)return!0;var t=e.minDirtCount,a=e.minDirtFactor;return t=t||Gs.minDirtCount,a=a||Gs.minDirtFactor,this.dirtCount>=t&&this.dirtFactor>=a},Object.defineProperty(r.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),r.prototype.has=function(e){return this._idToShortId.has(e)},r.prototype.getStoredFields=function(e){var t=this._idToShortId.get(e);if(t!=null)return this._storedFields.get(t)},r.prototype.search=function(e,t){var a,n;t===void 0&&(t={});var i=this.executeQuery(e,t),o=[];try{for(var s=de(i),l=s.next();!l.done;l=s.next()){var c=Ue(l.value,2),u=c[0],p=c[1],m=p.score,d=p.terms,g=p.match,f=d.length||1,y={id:this._documentIds.get(u),score:m*f,terms:Object.keys(g),queryTerms:d,match:g};Object.assign(y,this._storedFields.get(u)),(t.filter==null||t.filter(y))&&o.push(y)}}catch(v){a={error:v}}finally{try{l&&!l.done&&(n=s.return)&&n.call(s)}finally{if(a)throw a.error}}return e===r.wildcard&&t.boostDocument==null&&this._options.searchOptions.boostDocument==null||o.sort(ju),o},r.prototype.autoSuggest=function(e,t){var a,n,i,o;t===void 0&&(t={}),t=De(De({},this._options.autoSuggestOptions),t);var s=new Map;try{for(var l=de(this.search(e,t)),c=l.next();!c.done;c=l.next()){var u=c.value,p=u.score,m=u.terms,d=m.join(" "),g=s.get(d);g!=null?(g.score+=p,g.count+=1):s.set(d,{score:p,terms:m,count:1})}}catch(D){a={error:D}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(a)throw a.error}}var f=[];try{for(var y=de(s),v=y.next();!v.done;v=y.next()){var T=Ue(v.value,2),g=T[0],E=T[1],p=E.score,m=E.terms,I=E.count;f.push({suggestion:g,terms:m,score:p/I})}}catch(D){i={error:D}}finally{try{v&&!v.done&&(o=y.return)&&o.call(y)}finally{if(i)throw i.error}}return f.sort(ju),f},Object.defineProperty(r.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),r.loadJSON=function(e,t){if(t==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(e),t)},r.getDefault=function(e){if(Bs.hasOwnProperty(e))return Fs(Bs,e);throw new Error('MiniSearch: unknown option "'.concat(e,'"'))},r.loadJS=function(e,t){var a,n,i,o,s,l,c=e.index,u=e.documentCount,p=e.nextId,m=e.documentIds,d=e.fieldIds,g=e.fieldLength,f=e.averageFieldLength,y=e.storedFields,v=e.dirtCount,T=e.serializationVersion;if(T!==1&&T!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var E=new r(t);E._documentCount=u,E._nextId=p,E._documentIds=yi(m),E._idToShortId=new Map,E._fieldIds=d,E._fieldLength=yi(g),E._avgFieldLength=f,E._storedFields=yi(y),E._dirtCount=v||0,E._index=new Ls;try{for(var I=de(E._documentIds),D=I.next();!D.done;D=I.next()){var C=Ue(D.value,2),M=C[0],F=C[1];E._idToShortId.set(F,M)}}catch(Z){a={error:Z}}finally{try{D&&!D.done&&(n=I.return)&&n.call(I)}finally{if(a)throw a.error}}try{for(var R=de(c),G=R.next();!G.done;G=R.next()){var z=Ue(G.value,2),O=z[0],x=z[1],A=new Map;try{for(var B=(s=void 0,de(Object.keys(x))),X=B.next();!X.done;X=B.next()){var K=X.value,Q=x[K];T===1&&(Q=Q.ds),A.set(parseInt(K,10),yi(Q))}}catch(Z){s={error:Z}}finally{try{X&&!X.done&&(l=B.return)&&l.call(B)}finally{if(s)throw s.error}}E._index.set(O,A)}}catch(Z){i={error:Z}}finally{try{G&&!G.done&&(o=R.return)&&o.call(R)}finally{if(i)throw i.error}}return E},r.prototype.executeQuery=function(e,t){var a=this;if(t===void 0&&(t={}),e===r.wildcard)return this.executeWildcardQuery(t);if(typeof e!="string"){var n=De(De(De({},t),e),{queries:void 0}),i=e.queries.map(function(y){return a.executeQuery(y,n)});return this.combineResults(i,n.combineWith)}var o=this._options,s=o.tokenize,l=o.processTerm,c=o.searchOptions,u=De(De({tokenize:s,processTerm:l},c),t),p=u.tokenize,m=u.processTerm,d=p(e).flatMap(function(y){return m(y)}).filter(function(y){return!!y}),g=d.map(ab(u)),f=g.map(function(y){return a.executeQuerySpec(y,u)});return this.combineResults(f,u.combineWith)},r.prototype.executeQuerySpec=function(e,t){var a,n,i,o,s=De(De({},this._options.searchOptions),t),l=(s.fields||this._options.fields).reduce(function(K,Q){var Z;return De(De({},K),(Z={},Z[Q]=Fs(s.boost,Q)||1,Z))},{}),c=s.boostDocument,u=s.weights,p=s.maxFuzzy,m=s.bm25,d=De(De({},Vu.weights),u),g=d.fuzzy,f=d.prefix,y=this._index.get(e.term),v=this.termResults(e.term,e.term,1,y,l,c,m),T,E;if(e.prefix&&(T=this._index.atPrefix(e.term)),e.fuzzy){var I=e.fuzzy===!0?.2:e.fuzzy,D=I<1?Math.min(p,Math.round(e.term.length*I)):I;D&&(E=this._index.fuzzyGet(e.term,D))}if(T)try{for(var C=de(T),M=C.next();!M.done;M=C.next()){var F=Ue(M.value,2),R=F[0],G=F[1],z=R.length-e.term.length;if(z){E?.delete(R);var O=f*R.length/(R.length+.3*z);this.termResults(e.term,R,O,G,l,c,m,v)}}}catch(K){a={error:K}}finally{try{M&&!M.done&&(n=C.return)&&n.call(C)}finally{if(a)throw a.error}}if(E)try{for(var x=de(E.keys()),A=x.next();!A.done;A=x.next()){var R=A.value,B=Ue(E.get(R),2),X=B[0],z=B[1];if(z){var O=g*R.length/(R.length+z);this.termResults(e.term,R,O,X,l,c,m,v)}}}catch(K){i={error:K}}finally{try{A&&!A.done&&(o=x.return)&&o.call(x)}finally{if(i)throw i.error}}return v},r.prototype.executeWildcardQuery=function(e){var t,a,n=new Map,i=De(De({},this._options.searchOptions),e);try{for(var o=de(this._documentIds),s=o.next();!s.done;s=o.next()){var l=Ue(s.value,2),c=l[0],u=l[1],p=i.boostDocument?i.boostDocument(u,"",this._storedFields.get(c)):1;n.set(c,{score:p,terms:[],match:{}})}}catch(m){t={error:m}}finally{try{s&&!s.done&&(a=o.return)&&a.call(o)}finally{if(t)throw t.error}}return n},r.prototype.combineResults=function(e,t){if(t===void 0&&(t=Ws),e.length===0)return new Map;var a=t.toLowerCase();return e.reduce(tb[a])||new Map},r.prototype.toJSON=function(){var e,t,a,n,i=[];try{for(var o=de(this._index),s=o.next();!s.done;s=o.next()){var l=Ue(s.value,2),c=l[0],u=l[1],p={};try{for(var m=(a=void 0,de(u)),d=m.next();!d.done;d=m.next()){var g=Ue(d.value,2),f=g[0],y=g[1];p[f]=Object.fromEntries(y)}}catch(v){a={error:v}}finally{try{d&&!d.done&&(n=m.return)&&n.call(m)}finally{if(a)throw a.error}}i.push([c,p])}}catch(v){e={error:v}}finally{try{s&&!s.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:i,serializationVersion:2}},r.prototype.termResults=function(e,t,a,n,i,o,s,l){var c,u,p,m,d;if(l===void 0&&(l=new Map),n==null)return l;try{for(var g=de(Object.keys(i)),f=g.next();!f.done;f=g.next()){var y=f.value,v=i[y],T=this._fieldIds[y],E=n.get(T);if(E!=null){var I=E.size,D=this._avgFieldLength[T];try{for(var C=(p=void 0,de(E.keys())),M=C.next();!M.done;M=C.next()){var F=M.value;if(!this._documentIds.has(F)){this.removeTerm(T,F,t),I-=1;continue}var R=o?o(this._documentIds.get(F),t,this._storedFields.get(F)):1;if(R){var G=E.get(F),z=this._fieldLength.get(F)[T],O=nb(G,I,this._documentCount,z,D,s),x=a*v*R*O,A=l.get(F);if(A){A.score+=x,ob(A.terms,e);var B=Fs(A.match,t);B?B.push(y):A.match[t]=[y]}else l.set(F,{score:x,terms:[e],match:(d={},d[t]=[y],d)})}}}catch(X){p={error:X}}finally{try{M&&!M.done&&(m=C.return)&&m.call(C)}finally{if(p)throw p.error}}}}}catch(X){c={error:X}}finally{try{f&&!f.done&&(u=g.return)&&u.call(g)}finally{if(c)throw c.error}}return l},r.prototype.addTerm=function(e,t,a){var n=this._index.fetch(a,qu),i=n.get(e);if(i==null)i=new Map,i.set(t,1),n.set(e,i);else{var o=i.get(t);i.set(t,(o||0)+1)}},r.prototype.removeTerm=function(e,t,a){if(!this._index.has(a)){this.warnDocumentChanged(t,e,a);return}var n=this._index.fetch(a,qu),i=n.get(e);i==null||i.get(t)==null?this.warnDocumentChanged(t,e,a):i.get(t)<=1?i.size<=1?n.delete(e):i.delete(t):i.set(t,i.get(t)-1),this._index.get(a).size===0&&this._index.delete(a)},r.prototype.warnDocumentChanged=function(e,t,a){var n,i;try{for(var o=de(Object.keys(this._fieldIds)),s=o.next();!s.done;s=o.next()){var l=s.value;if(this._fieldIds[l]===t){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(e),' has changed before removal: term "').concat(a,'" was not present in field "').concat(l,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(c){n={error:c}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}},r.prototype.addDocumentId=function(e){var t=this._nextId;return this._idToShortId.set(e,t),this._documentIds.set(t,e),this._documentCount+=1,this._nextId+=1,t},r.prototype.addFields=function(e){for(var t=0;t<e.length;t++)this._fieldIds[e[t]]=t},r.prototype.addFieldLength=function(e,t,a,n){var i=this._fieldLength.get(e);i==null&&this._fieldLength.set(e,i=[]),i[t]=n;var o=this._avgFieldLength[t]||0,s=o*a+n;this._avgFieldLength[t]=s/(a+1)},r.prototype.removeFieldLength=function(e,t,a,n){if(a===1){this._avgFieldLength[t]=0;return}var i=this._avgFieldLength[t]*a-n;this._avgFieldLength[t]=i/(a-1)},r.prototype.saveStoredFields=function(e,t){var a,n,i=this._options,o=i.storeFields,s=i.extractField;if(!(o==null||o.length===0)){var l=this._storedFields.get(e);l==null&&this._storedFields.set(e,l={});try{for(var c=de(o),u=c.next();!u.done;u=c.next()){var p=u.value,m=s(t,p);m!==void 0&&(l[p]=m)}}catch(d){a={error:d}}finally{try{u&&!u.done&&(n=c.return)&&n.call(c)}finally{if(a)throw a.error}}}},r.wildcard=Symbol("*"),r}(),Fs=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)?r[e]:void 0},tb=(ba={},ba[Ws]=function(r,e){var t,a;try{for(var n=de(e.keys()),i=n.next();!i.done;i=n.next()){var o=i.value,s=r.get(o);if(s==null)r.set(o,e.get(o));else{var l=e.get(o),c=l.score,u=l.terms,p=l.match;s.score=s.score+c,s.match=Object.assign(s.match,p),Wu(s.terms,u)}}}catch(m){t={error:m}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}return r},ba[Ju]=function(r,e){var t,a,n=new Map;try{for(var i=de(e.keys()),o=i.next();!o.done;o=i.next()){var s=o.value,l=r.get(s);if(l!=null){var c=e.get(s),u=c.score,p=c.terms,m=c.match;Wu(l.terms,p),n.set(s,{score:l.score+u,terms:l.terms,match:Object.assign(l.match,m)})}}}catch(d){t={error:d}}finally{try{o&&!o.done&&(a=i.return)&&a.call(i)}finally{if(t)throw t.error}}return n},ba[eb]=function(r,e){var t,a;try{for(var n=de(e.keys()),i=n.next();!i.done;i=n.next()){var o=i.value;r.delete(o)}}catch(s){t={error:s}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}return r},ba),rb={k:1.2,b:.7,d:.5},nb=function(r,e,t,a,n,i){var o=i.k,s=i.b,l=i.d,c=Math.log(1+(t-e+.5)/(e+.5));return c*(l+r*(o+1)/(r+o*(1-s+s*a/n)))},ab=function(r){return function(e,t,a){var n=typeof r.fuzzy=="function"?r.fuzzy(e,t,a):r.fuzzy||!1,i=typeof r.prefix=="function"?r.prefix(e,t,a):r.prefix===!0;return{term:e,fuzzy:n,prefix:i}}},Bs={idField:"id",extractField:function(r,e){return r[e]},tokenize:function(r){return r.split(sb)},processTerm:function(r){return r.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(r,e){typeof console?.[r]=="function"&&console[r](e)},autoVacuum:!0},Vu={combineWith:Ws,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:rb},ib={combineWith:Ju,prefix:function(r,e,t){return e===t.length-1}},Us={batchSize:1e3,batchWait:10},Hs={minDirtFactor:.1,minDirtCount:20},Gs=De(De({},Us),Hs),ob=function(r,e){r.includes(e)||r.push(e)},Wu=function(r,e){var t,a;try{for(var n=de(e),i=n.next();!i.done;i=n.next()){var o=i.value;r.includes(o)||r.push(o)}}catch(s){t={error:s}}finally{try{i&&!i.done&&(a=n.return)&&a.call(n)}finally{if(t)throw t.error}}},ju=function(r,e){var t=r.score,a=e.score;return a-t},qu=function(){return new Map},yi=function(r){var e,t,a=new Map;try{for(var n=de(Object.keys(r)),i=n.next();!i.done;i=n.next()){var o=i.value;a.set(parseInt(o,10),r[o])}}catch(s){e={error:s}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return a},sb=/[\n\r -#%-*,-/:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]+/u;var ed=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(r,e)=>{let t=await e.knowledgeBase.search(r.query),a=e;a._lastKBsearch=r.query,a._nextRequestUseKBitems=t,e.submitAnalyticsEvent({type:"kb-search",query:r.query,results:t});let n=t.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",i=t.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${i}.`}}];var h={};Ss(h,{BRAND:()=>Nb,DIRTY:()=>qr,EMPTY_PATH:()=>db,INVALID:()=>ee,NEVER:()=>yv,OK:()=>ot,ParseStatus:()=>nt,Schema:()=>ue,ZodAny:()=>Ir,ZodArray:()=>fr,ZodBigInt:()=>$r,ZodBoolean:()=>Xr,ZodBranded:()=>_a,ZodCatch:()=>sn,ZodDate:()=>Yr,ZodDefault:()=>on,ZodDiscriminatedUnion:()=>Si,ZodEffects:()=>Ft,ZodEnum:()=>nn,ZodError:()=>yt,ZodFirstPartyTypeKind:()=>re,ZodFunction:()=>wi,ZodIntersection:()=>en,ZodIssueCode:()=>U,ZodLazy:()=>tn,ZodLiteral:()=>rn,ZodMap:()=>Wn,ZodNaN:()=>qn,ZodNativeEnum:()=>an,ZodNever:()=>jt,ZodNull:()=>Jr,ZodNullable:()=>rr,ZodNumber:()=>Kr,ZodObject:()=>bt,ZodOptional:()=>Lt,ZodParsedType:()=>j,ZodPipeline:()=>Sa,ZodPromise:()=>Rr,ZodReadonly:()=>ln,ZodRecord:()=>Ei,ZodSchema:()=>ue,ZodSet:()=>jn,ZodString:()=>Ar,ZodSymbol:()=>Hn,ZodTransformer:()=>Ft,ZodTuple:()=>tr,ZodType:()=>ue,ZodUndefined:()=>Zr,ZodUnion:()=>Qr,ZodUnknown:()=>gr,ZodVoid:()=>Vn,addIssueToContext:()=>W,any:()=>Hb,array:()=>qb,bigint:()=>Fb,boolean:()=>dd,coerce:()=>fv,custom:()=>ld,date:()=>Bb,datetimeRegex:()=>od,defaultErrorMap:()=>mr,discriminatedUnion:()=>Yb,effect:()=>lv,enum:()=>iv,function:()=>rv,getErrorMap:()=>Gn,getParsedType:()=>er,instanceof:()=>Lb,intersection:()=>Zb,isAborted:()=>vi,isAsync:()=>zn,isDirty:()=>_i,isValid:()=>xr,late:()=>Ob,lazy:()=>nv,literal:()=>av,makeIssue:()=>va,map:()=>ev,nan:()=>Mb,nativeEnum:()=>ov,never:()=>Wb,null:()=>Ub,nullable:()=>uv,number:()=>ud,object:()=>Kb,objectUtil:()=>js,oboolean:()=>gv,onumber:()=>hv,optional:()=>cv,ostring:()=>mv,pipeline:()=>pv,preprocess:()=>dv,promise:()=>sv,quotelessJson:()=>lb,record:()=>Qb,set:()=>tv,setErrorMap:()=>ub,strictObject:()=>$b,string:()=>cd,symbol:()=>Gb,transformer:()=>lv,tuple:()=>Jb,undefined:()=>zb,union:()=>Xb,unknown:()=>Vb,util:()=>pe,void:()=>jb});var pe;(function(r){r.assertEqual=n=>{};function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{let i={};for(let o of n)i[o]=o;return i},r.getValidEnumValues=n=>{let i=r.objectKeys(n).filter(s=>typeof n[n[s]]!="number"),o={};for(let s of i)o[s]=n[s];return r.objectValues(o)},r.objectValues=n=>r.objectKeys(n).map(function(i){return n[i]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let o in n)Object.prototype.hasOwnProperty.call(n,o)&&i.push(o);return i},r.find=(n,i)=>{for(let o of n)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function a(n,i=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=a,r.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(pe||(pe={}));var js;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(js||(js={}));var j=pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),er=r=>{switch(typeof r){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(r)?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(r)?j.array:r===null?j.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?j.promise:typeof Map<"u"&&r instanceof Map?j.map:typeof Set<"u"&&r instanceof Set?j.set:typeof Date<"u"&&r instanceof Date?j.date:j.object;default:return j.unknown}};var U=pe.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"]),lb=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),yt=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},a={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)a._errors.push(t(o));else{let s=a,l=0;for(;l<o.path.length;){let c=o.path[l];l===o.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(o))):s[c]=s[c]||{_errors:[]},s=s[c],l++}}};return n(this),a}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},a=[];for(let n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):a.push(e(n));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}};yt.create=r=>new yt(r);var cb=(r,e)=>{let t;switch(r.code){case U.invalid_type:r.received===j.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case U.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,pe.jsonStringifyReplacer)}`;break;case U.unrecognized_keys:t=`Unrecognized key(s) in object: ${pe.joinValues(r.keys,", ")}`;break;case U.invalid_union:t="Invalid input";break;case U.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${pe.joinValues(r.options)}`;break;case U.invalid_enum_value:t=`Invalid enum value. Expected ${pe.joinValues(r.options)}, received '${r.received}'`;break;case U.invalid_arguments:t="Invalid function arguments";break;case U.invalid_return_type:t="Invalid function return type";break;case U.invalid_date:t="Invalid date";break;case U.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:pe.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case U.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case U.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case U.custom:t="Invalid input";break;case U.invalid_intersection_types:t="Intersection results could not be merged";break;case U.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case U.not_finite:t="Number must be finite";break;default:t=e.defaultError,pe.assertNever(r)}return{message:t}},mr=cb;var td=mr;function ub(r){td=r}function Gn(){return td}var va=r=>{let{data:e,path:t,errorMaps:a,issueData:n}=r,i=[...t,...n.path||[]],o={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let s="",l=a.filter(c=>!!c).slice().reverse();for(let c of l)s=c(o,{data:e,defaultError:s}).message;return{...n,path:i,message:s}},db=[];function W(r,e){let t=Gn(),a=va({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===mr?void 0:mr].filter(n=>!!n)});r.common.issues.push(a)}var nt=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let a=[];for(let n of t){if(n.status==="aborted")return ee;n.status==="dirty"&&e.dirty(),a.push(n.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,t){let a=[];for(let n of t){let i=await n.key,o=await n.value;a.push({key:i,value:o})}return r.mergeObjectSync(e,a)}static mergeObjectSync(e,t){let a={};for(let n of t){let{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return ee;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(a[i.value]=o.value)}return{status:e.value,value:a}}},ee=Object.freeze({status:"aborted"}),qr=r=>({status:"dirty",value:r}),ot=r=>({status:"valid",value:r}),vi=r=>r.status==="aborted",_i=r=>r.status==="dirty",xr=r=>r.status==="valid",zn=r=>typeof Promise<"u"&&r instanceof Promise;var Y;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(Y||(Y={}));var Mt=class{constructor(e,t,a,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,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}},rd=(r,e)=>{if(xr(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new yt(r.common.issues);return this._error=t,this._error}}};function se(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:a,description:n}=r;if(e&&(t||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,s)=>{let{message:l}=r;return o.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??a??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:l??t??s.defaultError}},description:n}}var ue=class{get description(){return this._def.description}_getType(e){return er(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:er(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nt,ctx:{common:e.parent.common,data:e.data,parsedType:er(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(zn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){let a={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:er(e)},n=this._parseSync({data:e,path:a.path,parent:a});return rd(a,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:er(e)};if(!this["~standard"].async)try{let a=this._parseSync({data:e,path:[],parent:t});return xr(a)?{value:a.value}:{issues:t.common.issues}}catch(a){a?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(a=>xr(a)?{value:a.value}:{issues:t.common.issues})}async parseAsync(e,t){let a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){let a={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:er(e)},n=this._parse({data:e,path:a.path,parent:a}),i=await(zn(n)?n:Promise.resolve(n));return rd(a,i)}refine(e,t){let a=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,i)=>{let o=e(n),s=()=>i.addIssue({code:U.custom,...a(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(s(),!1)):o?!0:(s(),!1)})}refinement(e,t){return this._refinement((a,n)=>e(a)?!0:(n.addIssue(typeof t=="function"?t(a,n):t),!1))}_refinement(e){return new Ft({schema:this,typeName:re.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Lt.create(this,this._def)}nullable(){return rr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fr.create(this)}promise(){return Rr.create(this,this._def)}or(e){return Qr.create([this,e],this._def)}and(e){return en.create(this,e,this._def)}transform(e){return new Ft({...se(this._def),schema:this,typeName:re.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new on({...se(this._def),innerType:this,defaultValue:t,typeName:re.ZodDefault})}brand(){return new _a({typeName:re.ZodBranded,type:this,...se(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new sn({...se(this._def),innerType:this,catchValue:t,typeName:re.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Sa.create(this,e)}readonly(){return ln.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},pb=/^c[^\s-]{8,}$/i,mb=/^[0-9a-z]+$/,hb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gb=/^[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,fb=/^[a-z0-9_-]{21}$/i,yb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bb=/^[-+]?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)?)??$/,vb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_b="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qs,Sb=/^(?:(?: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])$/,Eb=/^(?:(?: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])$/,wb=/^(([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]))$/,Cb=/^(([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])$/,kb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Tb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ad="((\\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])))",xb=new RegExp(`^${ad}$`);function id(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Ab(r){return new RegExp(`^${id(r)}$`)}function od(r){let e=`${ad}T${id(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ib(r,e){return!!((e==="v4"||!e)&&Sb.test(r)||(e==="v6"||!e)&&wb.test(r))}function Rb(r,e){if(!yb.test(r))return!1;try{let[t]=r.split("."),a=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(a));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Pb(r,e){return!!((e==="v4"||!e)&&Eb.test(r)||(e==="v6"||!e)&&Cb.test(r))}var Ar=class r extends ue{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let i=this._getOrReturnCtx(e);return W(i,{code:U.invalid_type,expected:j.string,received:i.parsedType}),ee}let a=new nt,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),a.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),a.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,s=e.data.length<i.value;(o||s)&&(n=this._getOrReturnCtx(e,n),o?W(n,{code:U.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&W(n,{code:U.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),a.dirty())}else if(i.kind==="email")vb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"email",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="emoji")qs||(qs=new RegExp(_b,"u")),qs.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"emoji",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="uuid")gb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"uuid",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="nanoid")fb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"nanoid",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="cuid")pb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cuid",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="cuid2")mb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cuid2",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="ulid")hb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"ulid",code:U.invalid_string,message:i.message}),a.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),W(n,{validation:"url",code:U.invalid_string,message:i.message}),a.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"regex",code:U.invalid_string,message:i.message}),a.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),a.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{startsWith:i.value},message:i.message}),a.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{endsWith:i.value},message:i.message}),a.dirty()):i.kind==="datetime"?od(i).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:"datetime",message:i.message}),a.dirty()):i.kind==="date"?xb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:"date",message:i.message}),a.dirty()):i.kind==="time"?Ab(i).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:"time",message:i.message}),a.dirty()):i.kind==="duration"?bb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"duration",code:U.invalid_string,message:i.message}),a.dirty()):i.kind==="ip"?Ib(e.data,i.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"ip",code:U.invalid_string,message:i.message}),a.dirty()):i.kind==="jwt"?Rb(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"jwt",code:U.invalid_string,message:i.message}),a.dirty()):i.kind==="cidr"?Pb(e.data,i.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cidr",code:U.invalid_string,message:i.message}),a.dirty()):i.kind==="base64"?kb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"base64",code:U.invalid_string,message:i.message}),a.dirty()):i.kind==="base64url"?Tb.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"base64url",code:U.invalid_string,message:i.message}),a.dirty()):pe.assertNever(i);return{status:a.value,value:e.data}}_regex(e,t,a){return this.refinement(n=>e.test(n),{validation:t,code:U.invalid_string,...Y.errToObj(a)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Y.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Y.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Y.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Y.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Y.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Y.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Y.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Y.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Y.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Y.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Y.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Y.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Y.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Y.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Y.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Y.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Y.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Y.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Y.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Y.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Y.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Y.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Y.errToObj(t)})}nonempty(e){return this.min(1,Y.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ar.create=r=>new Ar({checks:[],typeName:re.ZodString,coerce:r?.coerce??!1,...se(r)});function Db(r,e){let t=(r.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=t>a?t:a,i=Number.parseInt(r.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return i%o/10**n}var Kr=class r extends ue{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==j.number){let i=this._getOrReturnCtx(e);return W(i,{code:U.invalid_type,expected:j.number,received:i.parsedType}),ee}let a,n=new nt;for(let i of this._def.checks)i.kind==="int"?pe.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),W(a,{code:U.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?Db(e.data,i.value)!==0&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),W(a,{code:U.not_finite,message:i.message}),n.dirty()):pe.assertNever(i);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Y.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Y.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Y.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Y.toString(t))}setLimit(e,t,a,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:Y.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Y.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Y.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Y.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Y.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Y.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Y.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Y.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Y.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Y.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&pe.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(t===null||a.value>t)&&(t=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Kr.create=r=>new Kr({checks:[],typeName:re.ZodNumber,coerce:r?.coerce||!1,...se(r)});var $r=class r extends ue{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==j.bigint)return this._getInvalidInput(e);let a,n=new nt;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),W(a,{code:U.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):pe.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:j.bigint,received:t.parsedType}),ee}gte(e,t){return this.setLimit("min",e,!0,Y.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Y.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Y.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Y.toString(t))}setLimit(e,t,a,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:Y.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Y.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Y.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Y.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Y.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Y.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};$r.create=r=>new $r({checks:[],typeName:re.ZodBigInt,coerce:r?.coerce??!1,...se(r)});var Xr=class extends ue{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.boolean,received:a.parsedType}),ee}return ot(e.data)}};Xr.create=r=>new Xr({typeName:re.ZodBoolean,coerce:r?.coerce||!1,...se(r)});var Yr=class r extends ue{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let i=this._getOrReturnCtx(e);return W(i,{code:U.invalid_type,expected:j.date,received:i.parsedType}),ee}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return W(i,{code:U.invalid_date}),ee}let a=new nt,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),a.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),a.dirty()):pe.assertNever(i);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Y.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Y.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Yr.create=r=>new Yr({checks:[],coerce:r?.coerce||!1,typeName:re.ZodDate,...se(r)});var Hn=class extends ue{_parse(e){if(this._getType(e)!==j.symbol){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.symbol,received:a.parsedType}),ee}return ot(e.data)}};Hn.create=r=>new Hn({typeName:re.ZodSymbol,...se(r)});var Zr=class extends ue{_parse(e){if(this._getType(e)!==j.undefined){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.undefined,received:a.parsedType}),ee}return ot(e.data)}};Zr.create=r=>new Zr({typeName:re.ZodUndefined,...se(r)});var Jr=class extends ue{_parse(e){if(this._getType(e)!==j.null){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.null,received:a.parsedType}),ee}return ot(e.data)}};Jr.create=r=>new Jr({typeName:re.ZodNull,...se(r)});var Ir=class extends ue{constructor(){super(...arguments),this._any=!0}_parse(e){return ot(e.data)}};Ir.create=r=>new Ir({typeName:re.ZodAny,...se(r)});var gr=class extends ue{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ot(e.data)}};gr.create=r=>new gr({typeName:re.ZodUnknown,...se(r)});var jt=class extends ue{_parse(e){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:j.never,received:t.parsedType}),ee}};jt.create=r=>new jt({typeName:re.ZodNever,...se(r)});var Vn=class extends ue{_parse(e){if(this._getType(e)!==j.undefined){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.void,received:a.parsedType}),ee}return ot(e.data)}};Vn.create=r=>new Vn({typeName:re.ZodVoid,...se(r)});var fr=class r extends ue{_parse(e){let{ctx:t,status:a}=this._processInputParams(e),n=this._def;if(t.parsedType!==j.array)return W(t,{code:U.invalid_type,expected:j.array,received:t.parsedType}),ee;if(n.exactLength!==null){let o=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(o||s)&&(W(t,{code:o?U.too_big:U.too_small,minimum:s?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),a.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(W(t,{code:U.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),a.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(W(t,{code:U.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map((o,s)=>n.type._parseAsync(new Mt(t,o,t.path,s)))).then(o=>nt.mergeArray(a,o));let i=[...t.data].map((o,s)=>n.type._parseSync(new Mt(t,o,t.path,s)));return nt.mergeArray(a,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:Y.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:Y.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:Y.toString(t)}})}nonempty(e){return this.min(1,e)}};fr.create=(r,e)=>new fr({type:r,minLength:null,maxLength:null,exactLength:null,typeName:re.ZodArray,...se(e)});function Un(r){if(r instanceof bt){let e={};for(let t in r.shape){let a=r.shape[t];e[t]=Lt.create(Un(a))}return new bt({...r._def,shape:()=>e})}else return r instanceof fr?new fr({...r._def,type:Un(r.element)}):r instanceof Lt?Lt.create(Un(r.unwrap())):r instanceof rr?rr.create(Un(r.unwrap())):r instanceof tr?tr.create(r.items.map(e=>Un(e))):r}var bt=class r extends ue{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=pe.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==j.object){let c=this._getOrReturnCtx(e);return W(c,{code:U.invalid_type,expected:j.object,received:c.parsedType}),ee}let{status:a,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof jt&&this._def.unknownKeys==="strip"))for(let c in n.data)o.includes(c)||s.push(c);let l=[];for(let c of o){let u=i[c],p=n.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Mt(n,p,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof jt){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of s)l.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(c==="strict")s.length>0&&(W(n,{code:U.unrecognized_keys,keys:s}),a.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of s){let p=n.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Mt(n,p,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let p=await u.key,m=await u.value;c.push({key:p,value:m,alwaysSet:u.alwaysSet})}return c}).then(c=>nt.mergeObjectSync(a,c)):nt.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return Y.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,a)=>{let n=this._def.errorMap?.(t,a).message??a.defaultError;return t.code==="unrecognized_keys"?{message:Y.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:re.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let a of pe.objectKeys(e))e[a]&&this.shape[a]&&(t[a]=this.shape[a]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let a of pe.objectKeys(this.shape))e[a]||(t[a]=this.shape[a]);return new r({...this._def,shape:()=>t})}deepPartial(){return Un(this)}partial(e){let t={};for(let a of pe.objectKeys(this.shape)){let n=this.shape[a];e&&!e[a]?t[a]=n:t[a]=n.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let a of pe.objectKeys(this.shape))if(e&&!e[a])t[a]=this.shape[a];else{let i=this.shape[a];for(;i instanceof Lt;)i=i._def.innerType;t[a]=i}return new r({...this._def,shape:()=>t})}keyof(){return sd(pe.objectKeys(this.shape))}};bt.create=(r,e)=>new bt({shape:()=>r,unknownKeys:"strip",catchall:jt.create(),typeName:re.ZodObject,...se(e)});bt.strictCreate=(r,e)=>new bt({shape:()=>r,unknownKeys:"strict",catchall:jt.create(),typeName:re.ZodObject,...se(e)});bt.lazycreate=(r,e)=>new bt({shape:r,unknownKeys:"strip",catchall:jt.create(),typeName:re.ZodObject,...se(e)});var Qr=class extends ue{_parse(e){let{ctx:t}=this._processInputParams(e),a=this._def.options;function n(i){for(let s of i)if(s.result.status==="valid")return s.result;for(let s of i)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let o=i.map(s=>new yt(s.ctx.common.issues));return W(t,{code:U.invalid_union,unionErrors:o}),ee}if(t.common.async)return Promise.all(a.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let l of a){let c={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let s=o.map(l=>new yt(l));return W(t,{code:U.invalid_union,unionErrors:s}),ee}}get options(){return this._def.options}};Qr.create=(r,e)=>new Qr({options:r,typeName:re.ZodUnion,...se(e)});var hr=r=>r instanceof tn?hr(r.schema):r instanceof Ft?hr(r.innerType()):r instanceof rn?[r.value]:r instanceof nn?r.options:r instanceof an?pe.objectValues(r.enum):r instanceof on?hr(r._def.innerType):r instanceof Zr?[void 0]:r instanceof Jr?[null]:r instanceof Lt?[void 0,...hr(r.unwrap())]:r instanceof rr?[null,...hr(r.unwrap())]:r instanceof _a||r instanceof ln?hr(r.unwrap()):r instanceof sn?hr(r._def.innerType):[],Si=class r extends ue{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.object)return W(t,{code:U.invalid_type,expected:j.object,received:t.parsedType}),ee;let a=this.discriminator,n=t.data[a],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(W(t,{code:U.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),ee)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,a){let n=new Map;for(let i of t){let o=hr(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of o){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,i)}}return new r({typeName:re.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...se(a)})}};function Ks(r,e){let t=er(r),a=er(e);if(r===e)return{valid:!0,data:r};if(t===j.object&&a===j.object){let n=pe.objectKeys(e),i=pe.objectKeys(r).filter(s=>n.indexOf(s)!==-1),o={...r,...e};for(let s of i){let l=Ks(r[s],e[s]);if(!l.valid)return{valid:!1};o[s]=l.data}return{valid:!0,data:o}}else if(t===j.array&&a===j.array){if(r.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<r.length;i++){let o=r[i],s=e[i],l=Ks(o,s);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return t===j.date&&a===j.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var en=class extends ue{_parse(e){let{status:t,ctx:a}=this._processInputParams(e),n=(i,o)=>{if(vi(i)||vi(o))return ee;let s=Ks(i.value,o.value);return s.valid?((_i(i)||_i(o))&&t.dirty(),{status:t.value,value:s.data}):(W(a,{code:U.invalid_intersection_types}),ee)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([i,o])=>n(i,o)):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};en.create=(r,e,t)=>new en({left:r,right:e,typeName:re.ZodIntersection,...se(t)});var tr=class r extends ue{_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==j.array)return W(a,{code:U.invalid_type,expected:j.array,received:a.parsedType}),ee;if(a.data.length<this._def.items.length)return W(a,{code:U.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&a.data.length>this._def.items.length&&(W(a,{code:U.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...a.data].map((o,s)=>{let l=this._def.items[s]||this._def.rest;return l?l._parse(new Mt(a,o,a.path,s)):null}).filter(o=>!!o);return a.common.async?Promise.all(i).then(o=>nt.mergeArray(t,o)):nt.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};tr.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tr({items:r,typeName:re.ZodTuple,rest:null,...se(e)})};var Ei=class r extends ue{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==j.object)return W(a,{code:U.invalid_type,expected:j.object,received:a.parsedType}),ee;let n=[],i=this._def.keyType,o=this._def.valueType;for(let s in a.data)n.push({key:i._parse(new Mt(a,s,a.path,s)),value:o._parse(new Mt(a,a.data[s],a.path,s)),alwaysSet:s in a.data});return a.common.async?nt.mergeObjectAsync(t,n):nt.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,a){return t instanceof ue?new r({keyType:e,valueType:t,typeName:re.ZodRecord,...se(a)}):new r({keyType:Ar.create(),valueType:e,typeName:re.ZodRecord,...se(t)})}},Wn=class extends ue{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==j.map)return W(a,{code:U.invalid_type,expected:j.map,received:a.parsedType}),ee;let n=this._def.keyType,i=this._def.valueType,o=[...a.data.entries()].map(([s,l],c)=>({key:n._parse(new Mt(a,s,a.path,[c,"key"])),value:i._parse(new Mt(a,l,a.path,[c,"value"]))}));if(a.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of o){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return ee;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),s.set(c.value,u.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let l of o){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return ee;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),s.set(c.value,u.value)}return{status:t.value,value:s}}}};Wn.create=(r,e,t)=>new Wn({valueType:e,keyType:r,typeName:re.ZodMap,...se(t)});var jn=class r extends ue{_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==j.set)return W(a,{code:U.invalid_type,expected:j.set,received:a.parsedType}),ee;let n=this._def;n.minSize!==null&&a.data.size<n.minSize.value&&(W(a,{code:U.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&a.data.size>n.maxSize.value&&(W(a,{code:U.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let i=this._def.valueType;function o(l){let c=new Set;for(let u of l){if(u.status==="aborted")return ee;u.status==="dirty"&&t.dirty(),c.add(u.value)}return{status:t.value,value:c}}let s=[...a.data.values()].map((l,c)=>i._parse(new Mt(a,l,a.path,c)));return a.common.async?Promise.all(s).then(l=>o(l)):o(s)}min(e,t){return new r({...this._def,minSize:{value:e,message:Y.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:Y.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};jn.create=(r,e)=>new jn({valueType:r,minSize:null,maxSize:null,typeName:re.ZodSet,...se(e)});var wi=class r extends ue{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.function)return W(t,{code:U.invalid_type,expected:j.function,received:t.parsedType}),ee;function a(s,l){return va({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Gn(),mr].filter(c=>!!c),issueData:{code:U.invalid_arguments,argumentsError:l}})}function n(s,l){return va({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Gn(),mr].filter(c=>!!c),issueData:{code:U.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Rr){let s=this;return ot(async function(...l){let c=new yt([]),u=await s._def.args.parseAsync(l,i).catch(d=>{throw c.addIssue(a(l,d)),c}),p=await Reflect.apply(o,this,u);return await s._def.returns._def.type.parseAsync(p,i).catch(d=>{throw c.addIssue(n(p,d)),c})})}else{let s=this;return ot(function(...l){let c=s._def.args.safeParse(l,i);if(!c.success)throw new yt([a(l,c.error)]);let u=Reflect.apply(o,this,c.data),p=s._def.returns.safeParse(u,i);if(!p.success)throw new yt([n(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:tr.create(e).rest(gr.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,a){return new r({args:e||tr.create([]).rest(gr.create()),returns:t||gr.create(),typeName:re.ZodFunction,...se(a)})}},tn=class extends ue{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};tn.create=(r,e)=>new tn({getter:r,typeName:re.ZodLazy,...se(e)});var rn=class extends ue{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return W(t,{received:t.data,code:U.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}};rn.create=(r,e)=>new rn({value:r,typeName:re.ZodLiteral,...se(e)});function sd(r,e){return new nn({values:r,typeName:re.ZodEnum,...se(e)})}var nn=class r extends ue{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),a=this._def.values;return W(t,{expected:pe.joinValues(a),received:t.parsedType,code:U.invalid_type}),ee}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),a=this._def.values;return W(t,{received:t.data,code:U.invalid_enum_value,options:a}),ee}return ot(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(a=>!e.includes(a)),{...this._def,...t})}};nn.create=sd;var an=class extends ue{_parse(e){let t=pe.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==j.string&&a.parsedType!==j.number){let n=pe.objectValues(t);return W(a,{expected:pe.joinValues(n),received:a.parsedType,code:U.invalid_type}),ee}if(this._cache||(this._cache=new Set(pe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=pe.objectValues(t);return W(a,{received:a.data,code:U.invalid_enum_value,options:n}),ee}return ot(e.data)}get enum(){return this._def.values}};an.create=(r,e)=>new an({values:r,typeName:re.ZodNativeEnum,...se(e)});var Rr=class extends ue{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.promise&&t.common.async===!1)return W(t,{code:U.invalid_type,expected:j.promise,received:t.parsedType}),ee;let a=t.parsedType===j.promise?t.data:Promise.resolve(t.data);return ot(a.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Rr.create=(r,e)=>new Rr({type:r,typeName:re.ZodPromise,...se(e)});var Ft=class extends ue{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===re.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:a}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{W(a,o),o.fatal?t.abort():t.dirty()},get path(){return a.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let o=n.transform(a.data,i);if(a.common.async)return Promise.resolve(o).then(async s=>{if(t.value==="aborted")return ee;let l=await this._def.schema._parseAsync({data:s,path:a.path,parent:a});return l.status==="aborted"?ee:l.status==="dirty"?qr(l.value):t.value==="dirty"?qr(l.value):l});{if(t.value==="aborted")return ee;let s=this._def.schema._parseSync({data:o,path:a.path,parent:a});return s.status==="aborted"?ee:s.status==="dirty"?qr(s.value):t.value==="dirty"?qr(s.value):s}}if(n.type==="refinement"){let o=s=>{let l=n.refinement(s,i);if(a.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(a.common.async===!1){let s=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return s.status==="aborted"?ee:(s.status==="dirty"&&t.dirty(),o(s.value),{status:t.value,value:s.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(s=>s.status==="aborted"?ee:(s.status==="dirty"&&t.dirty(),o(s.value).then(()=>({status:t.value,value:s.value}))))}if(n.type==="transform")if(a.common.async===!1){let o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!xr(o))return ee;let s=n.transform(o.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>xr(o)?Promise.resolve(n.transform(o.value,i)).then(s=>({status:t.value,value:s})):ee);pe.assertNever(n)}};Ft.create=(r,e,t)=>new Ft({schema:r,typeName:re.ZodEffects,effect:e,...se(t)});Ft.createWithPreprocess=(r,e,t)=>new Ft({schema:e,effect:{type:"preprocess",transform:r},typeName:re.ZodEffects,...se(t)});var Lt=class extends ue{_parse(e){return this._getType(e)===j.undefined?ot(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Lt.create=(r,e)=>new Lt({innerType:r,typeName:re.ZodOptional,...se(e)});var rr=class extends ue{_parse(e){return this._getType(e)===j.null?ot(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rr.create=(r,e)=>new rr({innerType:r,typeName:re.ZodNullable,...se(e)});var on=class extends ue{_parse(e){let{ctx:t}=this._processInputParams(e),a=t.data;return t.parsedType===j.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};on.create=(r,e)=>new on({innerType:r,typeName:re.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...se(e)});var sn=class extends ue{_parse(e){let{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return zn(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new yt(a.common.issues)},input:a.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new yt(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};sn.create=(r,e)=>new sn({innerType:r,typeName:re.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...se(e)});var qn=class extends ue{_parse(e){if(this._getType(e)!==j.nan){let a=this._getOrReturnCtx(e);return W(a,{code:U.invalid_type,expected:j.nan,received:a.parsedType}),ee}return{status:"valid",value:e.data}}};qn.create=r=>new qn({typeName:re.ZodNaN,...se(r)});var Nb=Symbol("zod_brand"),_a=class extends ue{_parse(e){let{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}},Sa=class r extends ue{_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?ee:i.status==="dirty"?(t.dirty(),qr(i.value)):this._def.out._parseAsync({data:i.value,path:a.path,parent:a})})();{let n=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?ee:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:a.path,parent:a})}}static create(e,t){return new r({in:e,out:t,typeName:re.ZodPipeline})}},ln=class extends ue{_parse(e){let t=this._def.innerType._parse(e),a=n=>(xr(n)&&(n.value=Object.freeze(n.value)),n);return zn(t)?t.then(n=>a(n)):a(t)}unwrap(){return this._def.innerType}};ln.create=(r,e)=>new ln({innerType:r,typeName:re.ZodReadonly,...se(e)});function nd(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function ld(r,e={},t){return r?Ir.create().superRefine((a,n)=>{let i=r(a);if(i instanceof Promise)return i.then(o=>{if(!o){let s=nd(e,a),l=s.fatal??t??!0;n.addIssue({code:"custom",...s,fatal:l})}});if(!i){let o=nd(e,a),s=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:s})}}):Ir.create()}var Ob={object:bt.lazycreate},re;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(re||(re={}));var Lb=(r,e={message:`Input not instance of ${r.name}`})=>ld(t=>t instanceof r,e),cd=Ar.create,ud=Kr.create,Mb=qn.create,Fb=$r.create,dd=Xr.create,Bb=Yr.create,Gb=Hn.create,zb=Zr.create,Ub=Jr.create,Hb=Ir.create,Vb=gr.create,Wb=jt.create,jb=Vn.create,qb=fr.create,Kb=bt.create,$b=bt.strictCreate,Xb=Qr.create,Yb=Si.create,Zb=en.create,Jb=tr.create,Qb=Ei.create,ev=Wn.create,tv=jn.create,rv=wi.create,nv=tn.create,av=rn.create,iv=nn.create,ov=an.create,sv=Rr.create,lv=Ft.create,cv=Lt.create,uv=rr.create,dv=Ft.createWithPreprocess,pv=Sa.create,mv=()=>cd().optional(),hv=()=>ud().optional(),gv=()=>dd().optional(),fv={string:r=>Ar.create({...r,coerce:!0}),number:r=>Kr.create({...r,coerce:!0}),boolean:r=>Xr.create({...r,coerce:!0}),bigint:r=>$r.create({...r,coerce:!0}),date:r=>Yr.create({...r,coerce:!0})};var yv=ee;var Kn="2025-03-26",pd=[Kn,"2024-11-05","2024-10-07"],Ci="2.0",md=h.union([h.string(),h.number().int()]),hd=h.string(),bv=h.object({progressToken:h.optional(md)}).passthrough(),qt=h.object({_meta:h.optional(bv)}).passthrough(),kt=h.object({method:h.string(),params:h.optional(qt)}),Ea=h.object({_meta:h.optional(h.object({}).passthrough())}).passthrough(),nr=h.object({method:h.string(),params:h.optional(Ea)}),Kt=h.object({_meta:h.optional(h.object({}).passthrough())}).passthrough(),ki=h.union([h.string(),h.number().int()]),gd=h.object({jsonrpc:h.literal(Ci),id:ki}).merge(kt).strict(),Ti=r=>gd.safeParse(r).success,fd=h.object({jsonrpc:h.literal(Ci)}).merge(nr).strict(),yd=r=>fd.safeParse(r).success,bd=h.object({jsonrpc:h.literal(Ci),id:ki,result:Kt}).strict(),wa=r=>bd.safeParse(r).success,Bt;(function(r){r[r.ConnectionClosed=-32e3]="ConnectionClosed",r[r.RequestTimeout=-32001]="RequestTimeout",r[r.ParseError=-32700]="ParseError",r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError"})(Bt||(Bt={}));var vd=h.object({jsonrpc:h.literal(Ci),id:ki,error:h.object({code:h.number().int(),message:h.string(),data:h.optional(h.unknown())})}).strict(),_d=r=>vd.safeParse(r).success,$n=h.union([gd,fd,bd,vd]),cn=Kt.strict(),xi=nr.extend({method:h.literal("notifications/cancelled"),params:Ea.extend({requestId:ki,reason:h.string().optional()})}),Sd=h.object({name:h.string(),version:h.string()}).passthrough(),vv=h.object({experimental:h.optional(h.object({}).passthrough()),sampling:h.optional(h.object({}).passthrough()),roots:h.optional(h.object({listChanged:h.optional(h.boolean())}).passthrough())}).passthrough(),_v=kt.extend({method:h.literal("initialize"),params:qt.extend({protocolVersion:h.string(),capabilities:vv,clientInfo:Sd})});var Sv=h.object({experimental:h.optional(h.object({}).passthrough()),logging:h.optional(h.object({}).passthrough()),completions:h.optional(h.object({}).passthrough()),prompts:h.optional(h.object({listChanged:h.optional(h.boolean())}).passthrough()),resources:h.optional(h.object({subscribe:h.optional(h.boolean()),listChanged:h.optional(h.boolean())}).passthrough()),tools:h.optional(h.object({listChanged:h.optional(h.boolean())}).passthrough())}).passthrough(),$s=Kt.extend({protocolVersion:h.string(),capabilities:Sv,serverInfo:Sd,instructions:h.optional(h.string())}),Ed=nr.extend({method:h.literal("notifications/initialized")}),wd=r=>Ed.safeParse(r).success,Ai=kt.extend({method:h.literal("ping")}),Ev=h.object({progress:h.number(),total:h.optional(h.number()),message:h.optional(h.string())}).passthrough(),Ii=nr.extend({method:h.literal("notifications/progress"),params:Ea.merge(Ev).extend({progressToken:md})}),Ri=kt.extend({params:qt.extend({cursor:h.optional(hd)}).optional()}),Pi=Kt.extend({nextCursor:h.optional(hd)}),Cd=h.object({uri:h.string(),mimeType:h.optional(h.string())}).passthrough(),kd=Cd.extend({text:h.string()}),Td=Cd.extend({blob:h.string().base64()}),wv=h.object({uri:h.string(),name:h.string(),description:h.optional(h.string()),mimeType:h.optional(h.string())}).passthrough(),Cv=h.object({uriTemplate:h.string(),name:h.string(),description:h.optional(h.string()),mimeType:h.optional(h.string())}).passthrough(),kv=Ri.extend({method:h.literal("resources/list")}),Xs=Pi.extend({resources:h.array(wv)}),Tv=Ri.extend({method:h.literal("resources/templates/list")}),Ys=Pi.extend({resourceTemplates:h.array(Cv)}),xv=kt.extend({method:h.literal("resources/read"),params:qt.extend({uri:h.string()})}),Zs=Kt.extend({contents:h.array(h.union([kd,Td]))}),Av=nr.extend({method:h.literal("notifications/resources/list_changed")}),Iv=kt.extend({method:h.literal("resources/subscribe"),params:qt.extend({uri:h.string()})}),Rv=kt.extend({method:h.literal("resources/unsubscribe"),params:qt.extend({uri:h.string()})}),Pv=nr.extend({method:h.literal("notifications/resources/updated"),params:Ea.extend({uri:h.string()})}),Dv=h.object({name:h.string(),description:h.optional(h.string()),required:h.optional(h.boolean())}).passthrough(),Nv=h.object({name:h.string(),description:h.optional(h.string()),arguments:h.optional(h.array(Dv))}).passthrough(),Ov=Ri.extend({method:h.literal("prompts/list")}),Js=Pi.extend({prompts:h.array(Nv)}),Lv=kt.extend({method:h.literal("prompts/get"),params:qt.extend({name:h.string(),arguments:h.optional(h.record(h.string()))})}),Di=h.object({type:h.literal("text"),text:h.string()}).passthrough(),Ni=h.object({type:h.literal("image"),data:h.string().base64(),mimeType:h.string()}).passthrough(),Oi=h.object({type:h.literal("audio"),data:h.string().base64(),mimeType:h.string()}).passthrough(),xd=h.object({type:h.literal("resource"),resource:h.union([kd,Td])}).passthrough(),Mv=h.object({role:h.enum(["user","assistant"]),content:h.union([Di,Ni,Oi,xd])}).passthrough(),Qs=Kt.extend({description:h.optional(h.string()),messages:h.array(Mv)}),Fv=nr.extend({method:h.literal("notifications/prompts/list_changed")}),Bv=h.object({title:h.optional(h.string()),readOnlyHint:h.optional(h.boolean()),destructiveHint:h.optional(h.boolean()),idempotentHint:h.optional(h.boolean()),openWorldHint:h.optional(h.boolean())}).passthrough(),Gv=h.object({name:h.string(),description:h.optional(h.string()),inputSchema:h.object({type:h.literal("object"),properties:h.optional(h.object({}).passthrough()),required:h.optional(h.array(h.string()))}).passthrough(),outputSchema:h.optional(h.object({type:h.literal("object"),properties:h.optional(h.object({}).passthrough()),required:h.optional(h.array(h.string()))}).passthrough()),annotations:h.optional(Bv)}).passthrough(),zv=Ri.extend({method:h.literal("tools/list")}),el=Pi.extend({tools:h.array(Gv)}),Li=Kt.extend({content:h.array(h.union([Di,Ni,Oi,xd])).default([]),structuredContent:h.object({}).passthrough().optional(),isError:h.optional(h.boolean())}),mA=Li.or(Kt.extend({toolResult:h.unknown()})),Uv=kt.extend({method:h.literal("tools/call"),params:qt.extend({name:h.string(),arguments:h.optional(h.record(h.unknown()))})}),tl=nr.extend({method:h.literal("notifications/tools/list_changed")}),Ad=h.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Hv=kt.extend({method:h.literal("logging/setLevel"),params:qt.extend({level:Ad})}),rl=nr.extend({method:h.literal("notifications/message"),params:Ea.extend({level:Ad,logger:h.optional(h.string()),data:h.unknown()})}),Vv=h.object({name:h.string().optional()}).passthrough(),Wv=h.object({hints:h.optional(h.array(Vv)),costPriority:h.optional(h.number().min(0).max(1)),speedPriority:h.optional(h.number().min(0).max(1)),intelligencePriority:h.optional(h.number().min(0).max(1))}).passthrough(),jv=h.object({role:h.enum(["user","assistant"]),content:h.union([Di,Ni,Oi])}).passthrough(),qv=kt.extend({method:h.literal("sampling/createMessage"),params:qt.extend({messages:h.array(jv),systemPrompt:h.optional(h.string()),includeContext:h.optional(h.enum(["none","thisServer","allServers"])),temperature:h.optional(h.number()),maxTokens:h.number().int(),stopSequences:h.optional(h.array(h.string())),metadata:h.optional(h.object({}).passthrough()),modelPreferences:h.optional(Wv)})}),Kv=Kt.extend({model:h.string(),stopReason:h.optional(h.enum(["endTurn","stopSequence","maxTokens"]).or(h.string())),role:h.enum(["user","assistant"]),content:h.discriminatedUnion("type",[Di,Ni,Oi])}),$v=h.object({type:h.literal("ref/resource"),uri:h.string()}).passthrough(),Xv=h.object({type:h.literal("ref/prompt"),name:h.string()}).passthrough(),Yv=kt.extend({method:h.literal("completion/complete"),params:qt.extend({ref:h.union([Xv,$v]),argument:h.object({name:h.string(),value:h.string()}).passthrough()})}),nl=Kt.extend({completion:h.object({values:h.array(h.string()).max(100),total:h.optional(h.number().int()),hasMore:h.optional(h.boolean())}).passthrough()}),Zv=h.object({uri:h.string().startsWith("file://"),name:h.optional(h.string())}).passthrough(),Jv=kt.extend({method:h.literal("roots/list")}),Qv=Kt.extend({roots:h.array(Zv)}),e_=nr.extend({method:h.literal("notifications/roots/list_changed")}),hA=h.union([Ai,_v,Yv,Hv,Lv,Ov,kv,Tv,xv,Iv,Rv,Uv,zv]),gA=h.union([xi,Ii,Ed,e_]),fA=h.union([cn,Kv,Qv]),yA=h.union([Ai,qv,Jv]),bA=h.union([xi,Ii,rl,Pv,Av,tl,Fv]),vA=h.union([cn,$s,nl,Qs,Js,Xs,Ys,Zs,Li,el]),Gt=class extends Error{constructor(e,t,a){super(`MCP error ${e}: ${t}`),this.code=e,this.data=a,this.name="McpError"}};var t_=6e4,Mi=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this.setNotificationHandler(xi,t=>{let a=this._requestHandlerAbortControllers.get(t.params.requestId);a?.abort(t.params.reason)}),this.setNotificationHandler(Ii,t=>{this._onprogress(t)}),this.setRequestHandler(Ai,t=>({}))}_setupTimeout(e,t,a,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:a,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let a=Date.now()-t.startTime;if(t.maxTotalTimeout&&a>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Gt(Bt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:a});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=t=>{this._onerror(t)},this._transport.onmessage=(t,a)=>{wa(t)||_d(t)?this._onresponse(t):Ti(t)?this._onrequest(t,a):yd(t)?this._onnotification(t):this._onerror(new Error(`Unknown message type: ${JSON.stringify(t)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let a=new Gt(Bt.ConnectionClosed,"Connection closed");for(let n of t.values())n(a)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let a=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){var a,n,i,o;let s=(a=this._requestHandlers.get(e.method))!==null&&a!==void 0?a:this.fallbackRequestHandler;if(s===void 0){(n=this._transport)===null||n===void 0||n.send({jsonrpc:"2.0",id:e.id,error:{code:Bt.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let c={signal:l.signal,sessionId:(i=this._transport)===null||i===void 0?void 0:i.sessionId,_meta:(o=e.params)===null||o===void 0?void 0:o._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,p,m)=>this.request(u,p,{...m,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id};Promise.resolve().then(()=>s(e,c)).then(u=>{var p;if(!l.signal.aborted)return(p=this._transport)===null||p===void 0?void 0:p.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var p,m;if(!l.signal.aborted)return(p=this._transport)===null||p===void 0?void 0:p.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Bt.InternalError,message:(m=u.message)!==null&&m!==void 0?m:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...a}=e.params,n=Number(t),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){o(l);return}i(a)}_onresponse(e){let t=Number(e.id),a=this._responseHandlers.get(t);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),wa(e))a(e);else{let n=new Gt(e.error.code,e.error.message,e.error.data);a(n)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,a){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}=a??{};return new Promise((s,l)=>{var c,u,p,m,d,g;if(!this._transport){l(new Error("Not connected"));return}((c=this._options)===null||c===void 0?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(u=a?.signal)===null||u===void 0||u.throwIfAborted();let f=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:f};a?.onprogress&&(this._progressHandlers.set(f,a.onprogress),y.params={...e.params,_meta:{...((p=e.params)===null||p===void 0?void 0:p._meta)||{},progressToken:f}});let v=I=>{var D;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),(D=this._transport)===null||D===void 0||D.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(I)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}).catch(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`))),l(I)};this._responseHandlers.set(f,I=>{var D;if(!(!((D=a?.signal)===null||D===void 0)&&D.aborted)){if(I instanceof Error)return l(I);try{let C=t.parse(I.result);s(C)}catch(C){l(C)}}}),(m=a?.signal)===null||m===void 0||m.addEventListener("abort",()=>{var I;v((I=a?.signal)===null||I===void 0?void 0:I.reason)});let T=(d=a?.timeout)!==null&&d!==void 0?d:t_,E=()=>v(new Gt(Bt.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(f,T,a?.maxTotalTimeout,E,(g=a?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(y,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}).catch(I=>{this._cleanupTimeout(f),l(I)})})}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let a={...e,jsonrpc:"2.0"};await this._transport.send(a,t)}setRequestHandler(e,t){let a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(n,i)=>Promise.resolve(t(e.parse(n),i)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(t(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Id(r,e){return Object.entries(e).reduce((t,[a,n])=>(n&&typeof n=="object"?t[a]=t[a]?{...t[a],...n}:n:t[a]=n,t),{...r})}var Pm=Es(Rm(),1),ka=class extends Mi{constructor(e,t){var a;super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=t?.capabilities)!==null&&a!==void 0?a:{},this._ajv=new Pm.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Id(this._capabilities,e)}assertCapability(e,t){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[e]))throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let a=await this.request({method:"initialize",params:{protocolVersion:Kn,capabilities:this._capabilities,clientInfo:this._clientInfo}},$s,t);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!pd.includes(a.protocolVersion))throw new Error(`Server's protocol version is not supported: ${a.protocolVersion}`);this._serverCapabilities=a.capabilities,this._serverVersion=a.serverInfo,this._instructions=a.instructions,await this.notification({method:"notifications/initialized"})}catch(a){throw this.close(),a}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var t,a,n,i,o;switch(e){case"logging/setLevel":if(!(!((t=this._serverCapabilities)===null||t===void 0)&&t.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var t;switch(e){case"notifications/roots/list_changed":if(!(!((t=this._capabilities.roots)===null||t===void 0)&&t.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},cn,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},nl,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},cn,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Qs,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},Js,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},Xs,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},Ys,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},Zs,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},cn,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},cn,t)}async callTool(e,t=Li,a){let n=await this.request({method:"tools/call",params:e},t,a),i=this.getToolOutputValidator(e.name);if(i){if(!n.structuredContent&&!n.isError)throw new Gt(Bt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{if(!i(n.structuredContent))throw new Gt(Bt.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(i.errors)}`)}catch(o){throw o instanceof Gt?o:new Gt(Bt.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return n}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let t of e)if(t.outputSchema)try{let a=this._ajv.compile(t.outputSchema);this._cachedToolOutputValidators.set(t.name,a)}catch(a){console.warn(`Failed to compile output schema for tool ${t.name}: ${a}`)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let a=await this.request({method:"tools/list",params:e},el,t);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Al;Al=globalThis.crypto;async function OS(r){return(await Al).getRandomValues(new Uint8Array(r))}async function LS(r){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",t="",a=await OS(r);for(let n=0;n<r;n++){let i=a[n]%e.length;t+=e[i]}return t}async function MS(r){return await LS(r)}async function FS(r){let e=await(await Al).subtle.digest("SHA-256",new TextEncoder().encode(r));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Il(r){if(r||(r=43),r<43||r>128)throw`Expected a length between 43 and 128. Received ${r}.`;let e=await MS(r),t=await FS(e);return{code_verifier:e,code_challenge:t}}var Dm=h.object({resource:h.string().url(),authorization_servers:h.array(h.string().url()).optional(),jwks_uri:h.string().url().optional(),scopes_supported:h.array(h.string()).optional(),bearer_methods_supported:h.array(h.string()).optional(),resource_signing_alg_values_supported:h.array(h.string()).optional(),resource_name:h.string().optional(),resource_documentation:h.string().optional(),resource_policy_uri:h.string().url().optional(),resource_tos_uri:h.string().url().optional(),tls_client_certificate_bound_access_tokens:h.boolean().optional(),authorization_details_types_supported:h.array(h.string()).optional(),dpop_signing_alg_values_supported:h.array(h.string()).optional(),dpop_bound_access_tokens_required:h.boolean().optional()}).passthrough(),Nm=h.object({issuer:h.string(),authorization_endpoint:h.string(),token_endpoint:h.string(),registration_endpoint:h.string().optional(),scopes_supported:h.array(h.string()).optional(),response_types_supported:h.array(h.string()),response_modes_supported:h.array(h.string()).optional(),grant_types_supported:h.array(h.string()).optional(),token_endpoint_auth_methods_supported:h.array(h.string()).optional(),token_endpoint_auth_signing_alg_values_supported:h.array(h.string()).optional(),service_documentation:h.string().optional(),revocation_endpoint:h.string().optional(),revocation_endpoint_auth_methods_supported:h.array(h.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:h.array(h.string()).optional(),introspection_endpoint:h.string().optional(),introspection_endpoint_auth_methods_supported:h.array(h.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:h.array(h.string()).optional(),code_challenge_methods_supported:h.array(h.string()).optional()}).passthrough(),Rl=h.object({access_token:h.string(),token_type:h.string(),expires_in:h.number().optional(),scope:h.string().optional(),refresh_token:h.string().optional()}).strip(),vI=h.object({error:h.string(),error_description:h.string().optional(),error_uri:h.string().optional()}),BS=h.object({redirect_uris:h.array(h.string()).refine(r=>r.every(e=>URL.canParse(e)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:h.string().optional(),grant_types:h.array(h.string()).optional(),response_types:h.array(h.string()).optional(),client_name:h.string().optional(),client_uri:h.string().optional(),logo_uri:h.string().optional(),scope:h.string().optional(),contacts:h.array(h.string()).optional(),tos_uri:h.string().optional(),policy_uri:h.string().optional(),jwks_uri:h.string().optional(),jwks:h.any().optional(),software_id:h.string().optional(),software_version:h.string().optional()}).strip(),GS=h.object({client_id:h.string(),client_secret:h.string().optional(),client_id_issued_at:h.number().optional(),client_secret_expires_at:h.number().optional()}).strip(),Om=BS.merge(GS),_I=h.object({error:h.string(),error_description:h.string().optional()}).strip(),SI=h.object({token:h.string(),token_type_hint:h.string().optional()}).strip();var vt=class extends Error{constructor(e){super(e??"Unauthorized")}};async function Or(r,{serverUrl:e,authorizationCode:t,scope:a,resourceMetadataUrl:n}){let i=e;try{let m=await zS(n||e);m.authorization_servers&&m.authorization_servers.length>0&&(i=m.authorization_servers[0])}catch(m){console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server",m)}let o=await US(i),s=await Promise.resolve(r.clientInformation());if(!s){if(t!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!r.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let m=await jS(i,{metadata:o,clientMetadata:r.clientMetadata});await r.saveClientInformation(m),s=m}if(t!==void 0){let m=await r.codeVerifier(),d=await VS(i,{metadata:o,clientInformation:s,authorizationCode:t,codeVerifier:m,redirectUri:r.redirectUrl});return await r.saveTokens(d),"AUTHORIZED"}let l=await r.tokens();if(l?.refresh_token)try{let m=await WS(i,{metadata:o,clientInformation:s,refreshToken:l.refresh_token});return await r.saveTokens(m),"AUTHORIZED"}catch(m){console.error("Could not refresh OAuth tokens:",m)}let c=r.state?await r.state():void 0,{authorizationUrl:u,codeVerifier:p}=await HS(i,{metadata:o,clientInformation:s,state:c,redirectUrl:r.redirectUrl,scope:a||r.clientMetadata.scope});return await r.saveCodeVerifier(p),await r.redirectToAuthorization(u),"REDIRECT"}function to(r){let e=r.headers.get("WWW-Authenticate");if(!e)return;let[t,a]=e.split(" ");if(t.toLowerCase()!=="bearer"||!a){console.log("Invalid WWW-Authenticate header format, expected 'Bearer'");return}let i=/resource_metadata="([^"]*)"/.exec(e);if(i)try{return new URL(i[1])}catch{console.log("Invalid resource metadata url: ",i[1]);return}}async function zS(r,e){var t;let a;e?.resourceMetadataUrl?a=new URL(e?.resourceMetadataUrl):a=new URL("/.well-known/oauth-protected-resource",r);let n;try{n=await fetch(a,{headers:{"MCP-Protocol-Version":(t=e?.protocolVersion)!==null&&t!==void 0?t:Kn}})}catch(i){if(i instanceof TypeError)n=await fetch(a);else throw i}if(n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Dm.parse(await n.json())}async function US(r,e){var t;let a=new URL("/.well-known/oauth-authorization-server",r),n;try{n=await fetch(a,{headers:{"MCP-Protocol-Version":(t=e?.protocolVersion)!==null&&t!==void 0?t:Kn}})}catch(i){if(i instanceof TypeError)n=await fetch(a);else throw i}if(n.status!==404){if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth metadata`);return Nm.parse(await n.json())}}async function HS(r,{metadata:e,clientInformation:t,redirectUrl:a,scope:n,state:i}){let o="code",s="S256",l;if(e){if(l=new URL(e.authorization_endpoint),!e.response_types_supported.includes(o))throw new Error(`Incompatible auth server: does not support response type ${o}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(s))throw new Error(`Incompatible auth server: does not support code challenge method ${s}`)}else l=new URL("/authorize",r);let c=await Il(),u=c.code_verifier,p=c.code_challenge;return l.searchParams.set("response_type",o),l.searchParams.set("client_id",t.client_id),l.searchParams.set("code_challenge",p),l.searchParams.set("code_challenge_method",s),l.searchParams.set("redirect_uri",String(a)),i&&l.searchParams.set("state",i),n&&l.searchParams.set("scope",n),{authorizationUrl:l,codeVerifier:u}}async function VS(r,{metadata:e,clientInformation:t,authorizationCode:a,codeVerifier:n,redirectUri:i}){let o="authorization_code",s;if(e){if(s=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(o))throw new Error(`Incompatible auth server: does not support grant type ${o}`)}else s=new URL("/token",r);let l=new URLSearchParams({grant_type:o,client_id:t.client_id,code:a,code_verifier:n,redirect_uri:String(i)});t.client_secret&&l.set("client_secret",t.client_secret);let c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return Rl.parse(await c.json())}async function WS(r,{metadata:e,clientInformation:t,refreshToken:a}){let n="refresh_token",i;if(e){if(i=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(n))throw new Error(`Incompatible auth server: does not support grant type ${n}`)}else i=new URL("/token",r);let o=new URLSearchParams({grant_type:n,client_id:t.client_id,refresh_token:a});t.client_secret&&o.set("client_secret",t.client_secret);let s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o});if(!s.ok)throw new Error(`Token refresh failed: HTTP ${s.status}`);return Rl.parse({refresh_token:a,...await s.json()})}async function jS(r,{metadata:e,clientMetadata:t}){let a;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");a=new URL(e.registration_endpoint)}else a=new URL("/register",r);let n=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Dynamic client registration failed: HTTP ${n.status}`);return Om.parse(await n.json())}var ro=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Pl(r){}function no(r){if(typeof r=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=Pl,onError:t=Pl,onRetry:a=Pl,onComment:n}=r,i="",o=!0,s,l="",c="";function u(f){let y=o?f.replace(/^\xEF\xBB\xBF/,""):f,[v,T]=qS(`${i}${y}`);for(let E of v)p(E);i=T,o=!1}function p(f){if(f===""){d();return}if(f.startsWith(":")){n&&n(f.slice(f.startsWith(": ")?2:1));return}let y=f.indexOf(":");if(y!==-1){let v=f.slice(0,y),T=f[y+1]===" "?2:1,E=f.slice(y+T);m(v,E,f);return}m(f,"",f)}function m(f,y,v){switch(f){case"event":c=y;break;case"data":l=`${l}${y}
|
|
3255
3255
|
`;break;case"id":s=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?a(parseInt(y,10)):t(new ro(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:v}));break;default:t(new ro(`Unknown field "${f.length>20?`${f.slice(0,20)}\u2026`:f}"`,{type:"unknown-field",field:f,value:y,line:v}));break}}function d(){l.length>0&&e({id:s,event:c||void 0,data:l.endsWith(`
|
|
3256
3256
|
`)?l.slice(0,-1):l}),s=void 0,l="",c=""}function g(f={}){i&&f.consume&&p(i),o=!0,s=void 0,l="",c="",i=""}return{feed:u,reset:g}}function qS(r){let e=[],t="",a=0;for(;a<r.length;){let n=r.indexOf("\r",a),i=r.indexOf(`
|
|
3257
3257
|
`,a),o=-1;if(n!==-1&&i!==-1?o=Math.min(n,i):n!==-1?o=n:i!==-1&&(o=i),o===-1){t=r.slice(a);break}else{let s=r.slice(a,o);e.push(s),a=o+1,r[a-1]==="\r"&&r[a]===`
|
|
3258
|
-
`&&a++}}return[e,t]}var ao=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:a}={}){let n;super({start(i){n=no({onEvent:o=>{i.enqueue(o)},onError(o){e==="terminate"?i.error(o):typeof e=="function"&&e(o)},onRetry:t,onComment:a})},transform(i){n.feed(i)}})}};var KS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ta=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},io=class{constructor(e,t){var a;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._sessionId=t?.sessionId,this._reconnectionOptions=(a=t?.reconnectionOptions)!==null&&a!==void 0?a:KS}async _authThenStart(){var e;if(!this._authProvider)throw new vt("No auth provider");let t;try{t=await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(t!=="AUTHORIZED")throw new vt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let t={};if(this._authProvider){let a=await this._authProvider.tokens();a&&(t.Authorization=`Bearer ${a.access_token}`)}return this._sessionId&&(t["mcp-session-id"]=this._sessionId),new Headers({...t,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}async _startOrAuthSse(e){var t,a;let{resumptionToken:n}=e;try{let i=await this._commonHeaders();i.set("Accept","text/event-stream"),n&&i.set("last-event-id",n);let o=await fetch(this._url,{method:"GET",headers:i,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal});if(!o.ok){if(o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Ta(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e)}catch(i){throw(a=this.onerror)===null||a===void 0||a.call(this,i),i}}_getNextReconnectionDelay(e){let t=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(a,e),n)}_scheduleReconnection(e,t=0){var a;let n=this._reconnectionOptions.maxRetries;if(n>0&&t>=n){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t){if(!e)return;let{onresumptiontoken:a,replayMessageId:n}=t,i;(async()=>{var s,l,c,u;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new ao).getReader();for(;;){let{value:m,done:d}=await p.read();if(d)break;if(m.id&&(i=m.id,a?.(m.id)),!m.event||m.event==="message")try{let g=$n.parse(JSON.parse(m.data));n!==void 0&&wa(g)&&(g.id=n),(s=this.onmessage)===null||s===void 0||s.call(this,g)}catch(g){(l=this.onerror)===null||l===void 0||l.call(this,g)}}}catch(p){if((c=this.onerror)===null||c===void 0||c.call(this,new Error(`SSE stream disconnected: ${p}`)),this._abortController&&!this._abortController.signal.aborted&&i!==void 0)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(m){(u=this.onerror)===null||u===void 0||u.call(this,new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new vt("No auth provider");if(await Or(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new vt("Failed to authorize")}async close(){var e,t;(e=this._abortController)===null||e===void 0||e.abort(),(t=this.onclose)===null||t===void 0||t.call(this)}async send(e,t){var a,n,i;try{let{resumptionToken:o,onresumptiontoken:s}=t||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:Ti(e)?e.id:void 0}).catch(f=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,f)});return}let l=await this._commonHeaders();l.set("content-type","application/json"),l.set("accept","application/json, text/event-stream");let c={...this._requestInit,method:"POST",headers:l,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},u=await fetch(this._url,c),p=u.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!u.ok){if(u.status===401&&this._authProvider){if(this._resourceMetadataUrl=to(u),await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new vt;return this.send(e)}let f=await u.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${f}`)}if(u.status===202){wd(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,f)});return}let d=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,g=u.headers.get("content-type");if(d)if(g?.includes("text/event-stream"))this._handleSseStream(u.body,{onresumptiontoken:s});else if(g?.includes("application/json")){let f=await u.json(),y=Array.isArray(f)?f.map(v=>$n.parse(v)):[$n.parse(f)];for(let v of y)(n=this.onmessage)===null||n===void 0||n.call(this,v)}else throw new Ta(-1,`Unexpected content type: ${g}`)}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}get sessionId(){return this._sessionId}async terminateSession(){var e,t;if(this._sessionId)try{let a=await this._commonHeaders(),n={...this._requestInit,method:"DELETE",headers:a,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},i=await fetch(this._url,n);if(!i.ok&&i.status!==405)throw new Ta(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}}};var so=class extends Event{constructor(e,t){var a,n;super(e),this.code=(a=t?.code)!=null?a:void 0,this.message=(n=t?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,a){return a(Lm(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(Lm(this),t)}};function $S(r){let e=globalThis.DOMException;return typeof e=="function"?new e(r,"SyntaxError"):new SyntaxError(r)}function Dl(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(Dl).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${Dl(r.cause)}`:r.message:`${r}`}function Lm(r){return{type:r.type,message:r.message,code:r.code,defaultPrevented:r.defaultPrevented,cancelable:r.cancelable,timeStamp:r.timeStamp}}var Fm=r=>{throw TypeError(r)},zl=(r,e,t)=>e.has(r)||Fm("Cannot "+t),me=(r,e,t)=>(zl(r,e,"read from private field"),t?t.call(r):e.get(r)),Xe=(r,e,t)=>e.has(r)?Fm("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Le=(r,e,t,a)=>(zl(r,e,"write to private field"),e.set(r,t),t),yr=(r,e,t)=>(zl(r,e,"access private method"),t),_t,pn,Xn,oo,lo,Ia,Jn,Ra,Lr,Yn,Qn,Zn,xa,$t,Nl,Ol,Ll,Mm,Ml,Fl,Aa,Bl,Gl,mn=class extends EventTarget{constructor(e,t){var a,n;super(),Xe(this,$t),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Xe(this,_t),Xe(this,pn),Xe(this,Xn),Xe(this,oo),Xe(this,lo),Xe(this,Ia),Xe(this,Jn),Xe(this,Ra,null),Xe(this,Lr),Xe(this,Yn),Xe(this,Qn,null),Xe(this,Zn,null),Xe(this,xa,null),Xe(this,Ol,async i=>{var o;me(this,Yn).reset();let{body:s,redirected:l,status:c,headers:u}=i;if(c===204){yr(this,$t,Aa).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Le(this,Xn,new URL(i.url)):Le(this,Xn,void 0),c!==200){yr(this,$t,Aa).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){yr(this,$t,Aa).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(me(this,_t)===this.CLOSED)return;Le(this,_t,this.OPEN);let p=new Event("open");if((o=me(this,xa))==null||o.call(this,p),this.dispatchEvent(p),typeof s!="object"||!s||!("getReader"in s)){yr(this,$t,Aa).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,d=s.getReader(),g=!0;do{let{done:f,value:y}=await d.read();y&&me(this,Yn).feed(m.decode(y,{stream:!f})),f&&(g=!1,me(this,Yn).reset(),yr(this,$t,Bl).call(this))}while(g)}),Xe(this,Ll,i=>{Le(this,Lr,void 0),!(i.name==="AbortError"||i.type==="aborted")&&yr(this,$t,Bl).call(this,Dl(i))}),Xe(this,Ml,i=>{typeof i.id=="string"&&Le(this,Ra,i.id);let o=new MessageEvent(i.event||"message",{data:i.data,origin:me(this,Xn)?me(this,Xn).origin:me(this,pn).origin,lastEventId:i.id||""});me(this,Zn)&&(!i.event||i.event==="message")&&me(this,Zn).call(this,o),this.dispatchEvent(o)}),Xe(this,Fl,i=>{Le(this,Ia,i)}),Xe(this,Gl,()=>{Le(this,Jn,void 0),me(this,_t)===this.CONNECTING&&yr(this,$t,Nl).call(this)});try{if(e instanceof URL)Le(this,pn,e);else if(typeof e=="string")Le(this,pn,new URL(e,XS()));else throw new Error("Invalid URL")}catch{throw $S("An invalid or illegal string was specified")}Le(this,Yn,no({onEvent:me(this,Ml),onRetry:me(this,Fl)})),Le(this,_t,this.CONNECTING),Le(this,Ia,3e3),Le(this,lo,(a=t?.fetch)!=null?a:globalThis.fetch),Le(this,oo,(n=t?.withCredentials)!=null?n:!1),yr(this,$t,Nl).call(this)}get readyState(){return me(this,_t)}get url(){return me(this,pn).href}get withCredentials(){return me(this,oo)}get onerror(){return me(this,Qn)}set onerror(e){Le(this,Qn,e)}get onmessage(){return me(this,Zn)}set onmessage(e){Le(this,Zn,e)}get onopen(){return me(this,xa)}set onopen(e){Le(this,xa,e)}addEventListener(e,t,a){let n=t;super.addEventListener(e,n,a)}removeEventListener(e,t,a){let n=t;super.removeEventListener(e,n,a)}close(){me(this,Jn)&&clearTimeout(me(this,Jn)),me(this,_t)!==this.CLOSED&&(me(this,Lr)&&me(this,Lr).abort(),Le(this,_t,this.CLOSED),Le(this,Lr,void 0))}};_t=new WeakMap,pn=new WeakMap,Xn=new WeakMap,oo=new WeakMap,lo=new WeakMap,Ia=new WeakMap,Jn=new WeakMap,Ra=new WeakMap,Lr=new WeakMap,Yn=new WeakMap,Qn=new WeakMap,Zn=new WeakMap,xa=new WeakMap,$t=new WeakSet,Nl=function(){Le(this,_t,this.CONNECTING),Le(this,Lr,new AbortController),me(this,lo)(me(this,pn),yr(this,$t,Mm).call(this)).then(me(this,Ol)).catch(me(this,Ll))},Ol=new WeakMap,Ll=new WeakMap,Mm=function(){var r;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...me(this,Ra)?{"Last-Event-ID":me(this,Ra)}:void 0},cache:"no-store",signal:(r=me(this,Lr))==null?void 0:r.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Ml=new WeakMap,Fl=new WeakMap,Aa=function(r,e){var t;me(this,_t)!==this.CLOSED&&Le(this,_t,this.CLOSED);let a=new so("error",{code:e,message:r});(t=me(this,Qn))==null||t.call(this,a),this.dispatchEvent(a)},Bl=function(r,e){var t;if(me(this,_t)===this.CLOSED)return;Le(this,_t,this.CONNECTING);let a=new so("error",{code:e,message:r});(t=me(this,Qn))==null||t.call(this,a),this.dispatchEvent(a),Le(this,Jn,setTimeout(me(this,Gl),me(this,Ia)))},Gl=new WeakMap,mn.CONNECTING=0,mn.OPEN=1,mn.CLOSED=2;function XS(){let r="document"in globalThis?globalThis.document:void 0;return r&&typeof r=="object"&&"baseURI"in r&&typeof r.baseURI=="string"?r.baseURI:void 0}var Ul=class extends Error{constructor(e,t,a){super(`SSE error: ${t}`),this.code=e,this.event=a}},co=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider}async _authThenStart(){var e;if(!this._authProvider)throw new vt("No auth provider");let t;try{t=await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(t!=="AUTHORIZED")throw new vt;return await this._startOrAuth()}async _commonHeaders(){var e;let t={...(e=this._requestInit)===null||e===void 0?void 0:e.headers};if(this._authProvider){let a=await this._authProvider.tokens();a&&(t.Authorization=`Bearer ${a.access_token}`)}return t}_startOrAuth(){return new Promise((e,t)=>{var a;this._eventSource=new mn(this._url.href,(a=this._eventSourceInit)!==null&&a!==void 0?a:{fetch:(n,i)=>this._commonHeaders().then(o=>fetch(n,{...i,headers:{...o,Accept:"text/event-stream"}}))}),this._abortController=new AbortController,this._eventSource.onerror=n=>{var i;if(n.code===401&&this._authProvider){this._authThenStart().then(e,t);return}let o=new Ul(n.code,n.message,n);t(o),(i=this.onerror)===null||i===void 0||i.call(this,o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{var i;let o=n;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(s){t(s),(i=this.onerror)===null||i===void 0||i.call(this,s),this.close();return}e()}),this._eventSource.onmessage=n=>{var i,o;let s=n,l;try{l=$n.parse(JSON.parse(s.data))}catch(c){(i=this.onerror)===null||i===void 0||i.call(this,c);return}(o=this.onmessage)===null||o===void 0||o.call(this,l)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new vt("No auth provider");if(await Or(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new vt("Failed to authorize")}async close(){var e,t,a;(e=this._abortController)===null||e===void 0||e.abort(),(t=this._eventSource)===null||t===void 0||t.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(e){var t,a,n;if(!this._endpoint)throw new Error("Not connected");try{let i=await this._commonHeaders(),o=new Headers({...i,...(t=this._requestInit)===null||t===void 0?void 0:t.headers});o.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},l=await fetch(this._endpoint,s);if(!l.ok){if(l.status===401&&this._authProvider){if(this._resourceMetadataUrl=to(l),await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new vt;return this.send(e)}let c=await l.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}};var hn={name:"@intelliweave/embedded",version:"1.8.61",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && IW_TESTER_API_KEY=97150cfc-5b97-413e-8da3-e86d01f70057 tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@modelcontextprotocol/sdk":"^1.12.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var Ye=new be("MCPKnowledgeClient"),uo=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){Ye.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new ka({name:hn.name,version:hn.version}),a=new io(new URL(this.config.baseURL));return await t.connect(a),Ye.debug("Connected with HTTP streaming mode"),t}).catch(async t=>{let a=new ka({name:hn.name,version:hn.version}),n=new co(new URL(this.config.baseURL));return await a.connect(n),Ye.debug("Connected with SSE mode"),a});return await this.disconnect(),this.client=e,e.onerror=t=>{Ye.error(`MCP client error: ${t.message}`)},e.onclose=()=>{Ye.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(rl,t=>{t.params.level=="critical"?Ye.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?Ye.error(`[Server] ${t.params.data}`):t.params.level=="error"?Ye.error(`[Server] ${t.params.data}`):t.params.level=="warning"?Ye.warn(`[Server] ${t.params.data}`):t.params.level=="info"?Ye.info(`[Server] ${t.params.data}`):t.params.level=="debug"?Ye.debug(`[Server] ${t.params.data}`):Ye.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(tl,t=>{Ye.debug("Tool list changed",t),this.fetchTools()}),Ye.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],t;for(;;){let n=await this.client.listTools({cursor:t});t=n.nextCursor;for(let i of n.tools||[])e.push(i);if(!n?.tools?.length||!t)break}let a=[];for(let n of e){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);a.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:o=>this.performToolCall(n.name,o),disabled:i})}Ye.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=a}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),a=await this.performSearchCall(e);return t=t.concat(a),this.lastSearchQuery=e,this.lastSearchResults=t,Ye.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let a=this.tools.find(i=>i.name==this.config.searchToolName);if(!a)return Ye.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let n;if(a.inputSchema.required?.length==1){let i=a.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:e})}else if(a.inputSchema.properties&&Object.keys(a.inputSchema.properties).length==1){let i=Object.keys(a.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:e})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let o=n[i];t.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else t.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return t}async performToolCall(e,t){await this.connect(),Ye.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let a=await this.client.callTool({name:e,arguments:t});if(a.isError){let n=a.content?.[0]?.text||"Unknown error";throw Ye.error(`Error calling tool ${e}: ${n}`),new Error(`Error calling tool ${e}: ${n}`)}if(Array.isArray(a.content)&&a.content.length==1&&a.content[0].type=="text")try{return JSON.parse(a.content[0].text)}catch{}return a.content||[]}};var gn=new be("KnowledgeBase"),Hl=1,po=class r{constructor(e){this._sources=[{id:"core.internal",query:async()=>ed}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,t){let a=e;return typeof e=="function"&&(t=e,a=`source.${Hl++}`),this._sources.push({id:a,query:t}),a}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return Ne().knowledgeBaseSources&&(e=e.concat(Ne().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(t=>!t.disabled),e}async search(e){gn.debug(`Searching knowledge base for: ${e}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=e,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async l=>{try{let c=Date.now(),u=await l.query(e);return gn.debug(`Source '${l.id}' took ${Date.now()-c}ms`),u||[]}catch(c){return gn.warn(`Knowledge source '${l.id}' failed:`,c),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),Ne().knowledgeBase&&(n=n.concat(Ne().knowledgeBase)),n=n.filter(l=>l&&!l.disabled);for(let l=0;l<n.length;l++){let c=n[l];c.id=c.id||`temp.${l}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!c.action&&c.type=="tour"&&(c.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!c.action&&c.type=="info"&&(c.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let i=new Qu({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});i.addAll(n);let s=i.search(e).map(l=>n.find(c=>c.id==l.id));for(let l of n)l.isContext&&(s.find(c=>c.id===l.id)||s.push(l));return this.lastResults=s,gn.debug("Found results:",s),s}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${Hl++}`),gn.debug(`Registering remote knowledge base source: ${e}`);let a=[],n=[],i=!0,o=async(l,c)=>{gn.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:c},p=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let m=await p.json();return s(m.updateItems||[]),m.response},s=l=>{for(let c of l){if(!c.id){gn.warn("KB item skipped since it has no ID.",c);continue}let u=a.find(p=>p.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}a.push({...c,action:p=>o(c,p)})}};this.registerSource(t,async l=>{if(i&&n.includes(l))return a;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return i=!p.noCache,n.includes(l)||n.push(l),s(p.items),a})}clone(){let e=new r(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${Hl++}`);let t=new uo(e);return this.registerSource(e.id,a=>t.search(a)),t}};var mo=class{constructor(e){this.ai=e}async boolean(e){let t=await this.instruct({...e,instruction:`${e.instruction}
|
|
3258
|
+
`&&a++}}return[e,t]}var ao=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:a}={}){let n;super({start(i){n=no({onEvent:o=>{i.enqueue(o)},onError(o){e==="terminate"?i.error(o):typeof e=="function"&&e(o)},onRetry:t,onComment:a})},transform(i){n.feed(i)}})}};var KS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ta=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},io=class{constructor(e,t){var a;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._sessionId=t?.sessionId,this._reconnectionOptions=(a=t?.reconnectionOptions)!==null&&a!==void 0?a:KS}async _authThenStart(){var e;if(!this._authProvider)throw new vt("No auth provider");let t;try{t=await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(t!=="AUTHORIZED")throw new vt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let t={};if(this._authProvider){let a=await this._authProvider.tokens();a&&(t.Authorization=`Bearer ${a.access_token}`)}return this._sessionId&&(t["mcp-session-id"]=this._sessionId),new Headers({...t,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}async _startOrAuthSse(e){var t,a;let{resumptionToken:n}=e;try{let i=await this._commonHeaders();i.set("Accept","text/event-stream"),n&&i.set("last-event-id",n);let o=await fetch(this._url,{method:"GET",headers:i,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal});if(!o.ok){if(o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Ta(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e)}catch(i){throw(a=this.onerror)===null||a===void 0||a.call(this,i),i}}_getNextReconnectionDelay(e){let t=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(a,e),n)}_scheduleReconnection(e,t=0){var a;let n=this._reconnectionOptions.maxRetries;if(n>0&&t>=n){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t){if(!e)return;let{onresumptiontoken:a,replayMessageId:n}=t,i;(async()=>{var s,l,c,u;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new ao).getReader();for(;;){let{value:m,done:d}=await p.read();if(d)break;if(m.id&&(i=m.id,a?.(m.id)),!m.event||m.event==="message")try{let g=$n.parse(JSON.parse(m.data));n!==void 0&&wa(g)&&(g.id=n),(s=this.onmessage)===null||s===void 0||s.call(this,g)}catch(g){(l=this.onerror)===null||l===void 0||l.call(this,g)}}}catch(p){if((c=this.onerror)===null||c===void 0||c.call(this,new Error(`SSE stream disconnected: ${p}`)),this._abortController&&!this._abortController.signal.aborted&&i!==void 0)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(m){(u=this.onerror)===null||u===void 0||u.call(this,new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new vt("No auth provider");if(await Or(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new vt("Failed to authorize")}async close(){var e,t;(e=this._abortController)===null||e===void 0||e.abort(),(t=this.onclose)===null||t===void 0||t.call(this)}async send(e,t){var a,n,i;try{let{resumptionToken:o,onresumptiontoken:s}=t||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:Ti(e)?e.id:void 0}).catch(f=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,f)});return}let l=await this._commonHeaders();l.set("content-type","application/json"),l.set("accept","application/json, text/event-stream");let c={...this._requestInit,method:"POST",headers:l,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},u=await fetch(this._url,c),p=u.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!u.ok){if(u.status===401&&this._authProvider){if(this._resourceMetadataUrl=to(u),await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new vt;return this.send(e)}let f=await u.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${f}`)}if(u.status===202){wd(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,f)});return}let d=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,g=u.headers.get("content-type");if(d)if(g?.includes("text/event-stream"))this._handleSseStream(u.body,{onresumptiontoken:s});else if(g?.includes("application/json")){let f=await u.json(),y=Array.isArray(f)?f.map(v=>$n.parse(v)):[$n.parse(f)];for(let v of y)(n=this.onmessage)===null||n===void 0||n.call(this,v)}else throw new Ta(-1,`Unexpected content type: ${g}`)}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}get sessionId(){return this._sessionId}async terminateSession(){var e,t;if(this._sessionId)try{let a=await this._commonHeaders(),n={...this._requestInit,method:"DELETE",headers:a,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},i=await fetch(this._url,n);if(!i.ok&&i.status!==405)throw new Ta(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}}};var so=class extends Event{constructor(e,t){var a,n;super(e),this.code=(a=t?.code)!=null?a:void 0,this.message=(n=t?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,a){return a(Lm(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(Lm(this),t)}};function $S(r){let e=globalThis.DOMException;return typeof e=="function"?new e(r,"SyntaxError"):new SyntaxError(r)}function Dl(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(Dl).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${Dl(r.cause)}`:r.message:`${r}`}function Lm(r){return{type:r.type,message:r.message,code:r.code,defaultPrevented:r.defaultPrevented,cancelable:r.cancelable,timeStamp:r.timeStamp}}var Fm=r=>{throw TypeError(r)},zl=(r,e,t)=>e.has(r)||Fm("Cannot "+t),me=(r,e,t)=>(zl(r,e,"read from private field"),t?t.call(r):e.get(r)),Xe=(r,e,t)=>e.has(r)?Fm("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Le=(r,e,t,a)=>(zl(r,e,"write to private field"),e.set(r,t),t),yr=(r,e,t)=>(zl(r,e,"access private method"),t),_t,pn,Xn,oo,lo,Ia,Jn,Ra,Lr,Yn,Qn,Zn,xa,$t,Nl,Ol,Ll,Mm,Ml,Fl,Aa,Bl,Gl,mn=class extends EventTarget{constructor(e,t){var a,n;super(),Xe(this,$t),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Xe(this,_t),Xe(this,pn),Xe(this,Xn),Xe(this,oo),Xe(this,lo),Xe(this,Ia),Xe(this,Jn),Xe(this,Ra,null),Xe(this,Lr),Xe(this,Yn),Xe(this,Qn,null),Xe(this,Zn,null),Xe(this,xa,null),Xe(this,Ol,async i=>{var o;me(this,Yn).reset();let{body:s,redirected:l,status:c,headers:u}=i;if(c===204){yr(this,$t,Aa).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Le(this,Xn,new URL(i.url)):Le(this,Xn,void 0),c!==200){yr(this,$t,Aa).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){yr(this,$t,Aa).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(me(this,_t)===this.CLOSED)return;Le(this,_t,this.OPEN);let p=new Event("open");if((o=me(this,xa))==null||o.call(this,p),this.dispatchEvent(p),typeof s!="object"||!s||!("getReader"in s)){yr(this,$t,Aa).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,d=s.getReader(),g=!0;do{let{done:f,value:y}=await d.read();y&&me(this,Yn).feed(m.decode(y,{stream:!f})),f&&(g=!1,me(this,Yn).reset(),yr(this,$t,Bl).call(this))}while(g)}),Xe(this,Ll,i=>{Le(this,Lr,void 0),!(i.name==="AbortError"||i.type==="aborted")&&yr(this,$t,Bl).call(this,Dl(i))}),Xe(this,Ml,i=>{typeof i.id=="string"&&Le(this,Ra,i.id);let o=new MessageEvent(i.event||"message",{data:i.data,origin:me(this,Xn)?me(this,Xn).origin:me(this,pn).origin,lastEventId:i.id||""});me(this,Zn)&&(!i.event||i.event==="message")&&me(this,Zn).call(this,o),this.dispatchEvent(o)}),Xe(this,Fl,i=>{Le(this,Ia,i)}),Xe(this,Gl,()=>{Le(this,Jn,void 0),me(this,_t)===this.CONNECTING&&yr(this,$t,Nl).call(this)});try{if(e instanceof URL)Le(this,pn,e);else if(typeof e=="string")Le(this,pn,new URL(e,XS()));else throw new Error("Invalid URL")}catch{throw $S("An invalid or illegal string was specified")}Le(this,Yn,no({onEvent:me(this,Ml),onRetry:me(this,Fl)})),Le(this,_t,this.CONNECTING),Le(this,Ia,3e3),Le(this,lo,(a=t?.fetch)!=null?a:globalThis.fetch),Le(this,oo,(n=t?.withCredentials)!=null?n:!1),yr(this,$t,Nl).call(this)}get readyState(){return me(this,_t)}get url(){return me(this,pn).href}get withCredentials(){return me(this,oo)}get onerror(){return me(this,Qn)}set onerror(e){Le(this,Qn,e)}get onmessage(){return me(this,Zn)}set onmessage(e){Le(this,Zn,e)}get onopen(){return me(this,xa)}set onopen(e){Le(this,xa,e)}addEventListener(e,t,a){let n=t;super.addEventListener(e,n,a)}removeEventListener(e,t,a){let n=t;super.removeEventListener(e,n,a)}close(){me(this,Jn)&&clearTimeout(me(this,Jn)),me(this,_t)!==this.CLOSED&&(me(this,Lr)&&me(this,Lr).abort(),Le(this,_t,this.CLOSED),Le(this,Lr,void 0))}};_t=new WeakMap,pn=new WeakMap,Xn=new WeakMap,oo=new WeakMap,lo=new WeakMap,Ia=new WeakMap,Jn=new WeakMap,Ra=new WeakMap,Lr=new WeakMap,Yn=new WeakMap,Qn=new WeakMap,Zn=new WeakMap,xa=new WeakMap,$t=new WeakSet,Nl=function(){Le(this,_t,this.CONNECTING),Le(this,Lr,new AbortController),me(this,lo)(me(this,pn),yr(this,$t,Mm).call(this)).then(me(this,Ol)).catch(me(this,Ll))},Ol=new WeakMap,Ll=new WeakMap,Mm=function(){var r;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...me(this,Ra)?{"Last-Event-ID":me(this,Ra)}:void 0},cache:"no-store",signal:(r=me(this,Lr))==null?void 0:r.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Ml=new WeakMap,Fl=new WeakMap,Aa=function(r,e){var t;me(this,_t)!==this.CLOSED&&Le(this,_t,this.CLOSED);let a=new so("error",{code:e,message:r});(t=me(this,Qn))==null||t.call(this,a),this.dispatchEvent(a)},Bl=function(r,e){var t;if(me(this,_t)===this.CLOSED)return;Le(this,_t,this.CONNECTING);let a=new so("error",{code:e,message:r});(t=me(this,Qn))==null||t.call(this,a),this.dispatchEvent(a),Le(this,Jn,setTimeout(me(this,Gl),me(this,Ia)))},Gl=new WeakMap,mn.CONNECTING=0,mn.OPEN=1,mn.CLOSED=2;function XS(){let r="document"in globalThis?globalThis.document:void 0;return r&&typeof r=="object"&&"baseURI"in r&&typeof r.baseURI=="string"?r.baseURI:void 0}var Ul=class extends Error{constructor(e,t,a){super(`SSE error: ${t}`),this.code=e,this.event=a}},co=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider}async _authThenStart(){var e;if(!this._authProvider)throw new vt("No auth provider");let t;try{t=await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(t!=="AUTHORIZED")throw new vt;return await this._startOrAuth()}async _commonHeaders(){var e;let t={...(e=this._requestInit)===null||e===void 0?void 0:e.headers};if(this._authProvider){let a=await this._authProvider.tokens();a&&(t.Authorization=`Bearer ${a.access_token}`)}return t}_startOrAuth(){return new Promise((e,t)=>{var a;this._eventSource=new mn(this._url.href,(a=this._eventSourceInit)!==null&&a!==void 0?a:{fetch:(n,i)=>this._commonHeaders().then(o=>fetch(n,{...i,headers:{...o,Accept:"text/event-stream"}}))}),this._abortController=new AbortController,this._eventSource.onerror=n=>{var i;if(n.code===401&&this._authProvider){this._authThenStart().then(e,t);return}let o=new Ul(n.code,n.message,n);t(o),(i=this.onerror)===null||i===void 0||i.call(this,o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{var i;let o=n;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(s){t(s),(i=this.onerror)===null||i===void 0||i.call(this,s),this.close();return}e()}),this._eventSource.onmessage=n=>{var i,o;let s=n,l;try{l=$n.parse(JSON.parse(s.data))}catch(c){(i=this.onerror)===null||i===void 0||i.call(this,c);return}(o=this.onmessage)===null||o===void 0||o.call(this,l)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new vt("No auth provider");if(await Or(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new vt("Failed to authorize")}async close(){var e,t,a;(e=this._abortController)===null||e===void 0||e.abort(),(t=this._eventSource)===null||t===void 0||t.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(e){var t,a,n;if(!this._endpoint)throw new Error("Not connected");try{let i=await this._commonHeaders(),o=new Headers({...i,...(t=this._requestInit)===null||t===void 0?void 0:t.headers});o.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},l=await fetch(this._endpoint,s);if(!l.ok){if(l.status===401&&this._authProvider){if(this._resourceMetadataUrl=to(l),await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new vt;return this.send(e)}let c=await l.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}};var hn={name:"@intelliweave/embedded",version:"1.8.62",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && IW_TESTER_API_KEY=97150cfc-5b97-413e-8da3-e86d01f70057 tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@modelcontextprotocol/sdk":"^1.12.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var Ye=new be("MCPKnowledgeClient"),uo=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){Ye.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new ka({name:hn.name,version:hn.version}),a=new io(new URL(this.config.baseURL));return await t.connect(a),Ye.debug("Connected with HTTP streaming mode"),t}).catch(async t=>{let a=new ka({name:hn.name,version:hn.version}),n=new co(new URL(this.config.baseURL));return await a.connect(n),Ye.debug("Connected with SSE mode"),a});return await this.disconnect(),this.client=e,e.onerror=t=>{Ye.error(`MCP client error: ${t.message}`)},e.onclose=()=>{Ye.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(rl,t=>{t.params.level=="critical"?Ye.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?Ye.error(`[Server] ${t.params.data}`):t.params.level=="error"?Ye.error(`[Server] ${t.params.data}`):t.params.level=="warning"?Ye.warn(`[Server] ${t.params.data}`):t.params.level=="info"?Ye.info(`[Server] ${t.params.data}`):t.params.level=="debug"?Ye.debug(`[Server] ${t.params.data}`):Ye.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(tl,t=>{Ye.debug("Tool list changed",t),this.fetchTools()}),Ye.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],t;for(;;){let n=await this.client.listTools({cursor:t});t=n.nextCursor;for(let i of n.tools||[])e.push(i);if(!n?.tools?.length||!t)break}let a=[];for(let n of e){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);a.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:o=>this.performToolCall(n.name,o),disabled:i})}Ye.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=a}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),a=await this.performSearchCall(e);return t=t.concat(a),this.lastSearchQuery=e,this.lastSearchResults=t,Ye.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let a=this.tools.find(i=>i.name==this.config.searchToolName);if(!a)return Ye.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let n;if(a.inputSchema.required?.length==1){let i=a.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:e})}else if(a.inputSchema.properties&&Object.keys(a.inputSchema.properties).length==1){let i=Object.keys(a.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:e})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let o=n[i];t.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else t.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return t}async performToolCall(e,t){await this.connect(),Ye.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let a=await this.client.callTool({name:e,arguments:t});if(a.isError){let n=a.content?.[0]?.text||"Unknown error";throw Ye.error(`Error calling tool ${e}: ${n}`),new Error(`Error calling tool ${e}: ${n}`)}if(Array.isArray(a.content)&&a.content.length==1&&a.content[0].type=="text")try{return JSON.parse(a.content[0].text)}catch{}return a.content||[]}};var gn=new be("KnowledgeBase"),Hl=1,po=class r{constructor(e){this._sources=[{id:"core.internal",query:async()=>ed}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,t){let a=e;return typeof e=="function"&&(t=e,a=`source.${Hl++}`),this._sources.push({id:a,query:t}),a}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return Ne().knowledgeBaseSources&&(e=e.concat(Ne().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(t=>!t.disabled),e}async search(e){gn.debug(`Searching knowledge base for: ${e}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=e,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async l=>{try{let c=Date.now(),u=await l.query(e);return gn.debug(`Source '${l.id}' took ${Date.now()-c}ms`),u||[]}catch(c){return gn.warn(`Knowledge source '${l.id}' failed:`,c),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),Ne().knowledgeBase&&(n=n.concat(Ne().knowledgeBase)),n=n.filter(l=>l&&!l.disabled);for(let l=0;l<n.length;l++){let c=n[l];c.id=c.id||`temp.${l}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!c.action&&c.type=="tour"&&(c.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!c.action&&c.type=="info"&&(c.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let i=new Qu({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});i.addAll(n);let s=i.search(e).map(l=>n.find(c=>c.id==l.id));for(let l of n)l.isContext&&(s.find(c=>c.id===l.id)||s.push(l));return this.lastResults=s,gn.debug("Found results:",s),s}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${Hl++}`),gn.debug(`Registering remote knowledge base source: ${e}`);let a=[],n=[],i=!0,o=async(l,c)=>{gn.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:c},p=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let m=await p.json();return s(m.updateItems||[]),m.response},s=l=>{for(let c of l){if(!c.id){gn.warn("KB item skipped since it has no ID.",c);continue}let u=a.find(p=>p.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}a.push({...c,action:p=>o(c,p)})}};this.registerSource(t,async l=>{if(i&&n.includes(l))return a;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return i=!p.noCache,n.includes(l)||n.push(l),s(p.items),a})}clone(){let e=new r(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${Hl++}`);let t=new uo(e);return this.registerSource(e.id,a=>t.search(a)),t}};var mo=class{constructor(e){this.ai=e}async boolean(e){let t=await this.instruct({...e,instruction:`${e.instruction}
|
|
3259
3259
|
|
|
3260
3260
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(t.toLowerCase().includes("true"))return!0;if(t.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+t)}async choose(e){let t=await this.instruct({...e,instruction:`${e.instruction}
|
|
3261
3261
|
|