@opentiny/next-sdk 0.2.0 → 0.2.2

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.
@@ -0,0 +1,43 @@
1
+ (function(S,Qt){typeof exports=="object"&&typeof module<"u"?Qt(exports):typeof define=="function"&&define.amd?define(["exports"],Qt):(S=typeof globalThis<"u"?globalThis:S||self,Qt(S.MCPSDK={}))})(this,(function(S){"use strict";function Qt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var tn={exports:{}},Vs={},yt={},Zt={},Fs={},Hs={},Ws={},Ki;function rn(){return Ki||(Ki=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(d){if(super(),!t.IDENTIFIER.test(d))throw new Error("CodeGen: name must be a valid identifier");this.str=d}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(d){super(),this._items=typeof d=="string"?[d]:d}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const d=this._items[0];return d===""||d==='""'}get str(){var d;return(d=this._str)!==null&&d!==void 0?d:this._str=this._items.reduce((m,b)=>`${m}${b}`,"")}get names(){var d;return(d=this._names)!==null&&d!==void 0?d:this._names=this._items.reduce((m,b)=>(b instanceof r&&(m[b.str]=(m[b.str]||0)+1),m),{})}}t._Code=n,t.nil=new n("");function s(v,...d){const m=[v[0]];let b=0;for(;b<d.length;)o(m,d[b]),m.push(v[++b]);return new n(m)}t._=s;const a=new n("+");function i(v,...d){const m=[_(v[0])];let b=0;for(;b<d.length;)m.push(a),o(m,d[b]),m.push(a,_(v[++b]));return c(m),new n(m)}t.str=i;function o(v,d){d instanceof n?v.push(...d._items):d instanceof r?v.push(d):v.push(p(d))}t.addCodeArg=o;function c(v){let d=1;for(;d<v.length-1;){if(v[d]===a){const m=u(v[d-1],v[d+1]);if(m!==void 0){v.splice(d-1,3,m);continue}v[d++]="+"}d++}}function u(v,d){if(d==='""')return v;if(v==='""')return d;if(typeof v=="string")return d instanceof r||v[v.length-1]!=='"'?void 0:typeof d!="string"?`${v.slice(0,-1)}${d}"`:d[0]==='"'?v.slice(0,-1)+d.slice(1):void 0;if(typeof d=="string"&&d[0]==='"'&&!(v instanceof r))return`"${v}${d.slice(1)}`}function l(v,d){return d.emptyStr()?v:v.emptyStr()?d:i`${v}${d}`}t.strConcat=l;function p(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:_(Array.isArray(v)?v.join(","):v)}function g(v){return new n(_(v))}t.stringify=g;function _(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=_;function h(v){return typeof v=="string"&&t.IDENTIFIER.test(v)?new n(`.${v}`):s`[${v}]`}t.getProperty=h;function w(v){if(typeof v=="string"&&t.IDENTIFIER.test(v))return new n(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}t.getEsmExportName=w;function f(v){return new n(v.toString())}t.regexpCode=f})(Ws)),Ws}var Ks={},Ji;function Gi(){return Ji||(Ji=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=rn();class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(t.UsedValueState=n={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class s{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,p;if(!((p=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||p===void 0)&&p.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}t.Scope=s;class a extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:p}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${p}]`}}t.ValueScopeName=a;const i=(0,e._)`\n`;class o extends s{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:e.nil}}get(){return this._scope}name(u){return new a(u,this._newName(u))}value(u,l){var p;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const g=this.toName(u),{prefix:_}=g,h=(p=l.key)!==null&&p!==void 0?p:l.ref;let w=this._values[_];if(w){const d=w.get(h);if(d)return d}else w=this._values[_]=new Map;w.set(h,g);const f=this._scope[_]||(this._scope[_]=[]),v=f.length;return f[v]=l.ref,g.setValue(l,{property:_,itemIndex:v}),g}getValue(u,l){const p=this._values[u];if(p)return p.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,p=>{if(p.scopePath===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return(0,e._)`${u}${p.scopePath}`})}scopeCode(u=this._values,l,p){return this._reduceValues(u,g=>{if(g.value===void 0)throw new Error(`CodeGen: name "${g}" has no value`);return g.value.code},l,p)}_reduceValues(u,l,p={},g){let _=e.nil;for(const h in u){const w=u[h];if(!w)continue;const f=p[h]=p[h]||new Map;w.forEach(v=>{if(f.has(v))return;f.set(v,n.Started);let d=l(v);if(d){const m=this.opts.es5?t.varKinds.var:t.varKinds.const;_=(0,e._)`${_}${m} ${v} = ${d};${this.opts._n}`}else if(d=g?.(v))_=(0,e._)`${_}${d}${this.opts._n}`;else throw new r(v);f.set(v,n.Completed)})}return _}}t.ValueScope=o})(Ks)),Ks}var Bi;function ae(){return Bi||(Bi=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=rn(),r=Gi();var n=rn();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var s=Gi();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class a{optimizeNodes(){return this}optimizeNames(k,T){return this}}class i extends a{constructor(k,T,j){super(),this.varKind=k,this.name=T,this.rhs=j}render({es5:k,_n:T}){const j=k?r.varKinds.var:this.varKind,ee=this.rhs===void 0?"":` = ${this.rhs}`;return`${j} ${this.name}${ee};`+T}optimizeNames(k,T){if(k[this.name.str])return this.rhs&&(this.rhs=Y(this.rhs,k,T)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class o extends a{constructor(k,T,j){super(),this.lhs=k,this.rhs=T,this.sideEffects=j}render({_n:k}){return`${this.lhs} = ${this.rhs};`+k}optimizeNames(k,T){if(!(this.lhs instanceof e.Name&&!k[this.lhs.str]&&!this.sideEffects))return this.rhs=Y(this.rhs,k,T),this}get names(){const k=this.lhs instanceof e.Name?{}:{...this.lhs.names};return G(k,this.rhs)}}class c extends o{constructor(k,T,j,ee){super(k,j,ee),this.op=T}render({_n:k}){return`${this.lhs} ${this.op}= ${this.rhs};`+k}}class u extends a{constructor(k){super(),this.label=k,this.names={}}render({_n:k}){return`${this.label}:`+k}}class l extends a{constructor(k){super(),this.label=k,this.names={}}render({_n:k}){return`break${this.label?` ${this.label}`:""};`+k}}class p extends a{constructor(k){super(),this.error=k}render({_n:k}){return`throw ${this.error};`+k}get names(){return this.error.names}}class g extends a{constructor(k){super(),this.code=k}render({_n:k}){return`${this.code};`+k}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(k,T){return this.code=Y(this.code,k,T),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class _ extends a{constructor(k=[]){super(),this.nodes=k}render(k){return this.nodes.reduce((T,j)=>T+j.render(k),"")}optimizeNodes(){const{nodes:k}=this;let T=k.length;for(;T--;){const j=k[T].optimizeNodes();Array.isArray(j)?k.splice(T,1,...j):j?k[T]=j:k.splice(T,1)}return k.length>0?this:void 0}optimizeNames(k,T){const{nodes:j}=this;let ee=j.length;for(;ee--;){const ne=j[ee];ne.optimizeNames(k,T)||(ge(k,ne.names),j.splice(ee,1))}return j.length>0?this:void 0}get names(){return this.nodes.reduce((k,T)=>F(k,T.names),{})}}class h extends _{render(k){return"{"+k._n+super.render(k)+"}"+k._n}}class w extends _{}class f extends h{}f.kind="else";class v extends h{constructor(k,T){super(T),this.condition=k}render(k){let T=`if(${this.condition})`+super.render(k);return this.else&&(T+="else "+this.else.render(k)),T}optimizeNodes(){super.optimizeNodes();const k=this.condition;if(k===!0)return this.nodes;let T=this.else;if(T){const j=T.optimizeNodes();T=this.else=Array.isArray(j)?new f(j):j}if(T)return k===!1?T instanceof v?T:T.nodes:this.nodes.length?this:new v(We(k),T instanceof v?[T]:T.nodes);if(!(k===!1||!this.nodes.length))return this}optimizeNames(k,T){var j;if(this.else=(j=this.else)===null||j===void 0?void 0:j.optimizeNames(k,T),!!(super.optimizeNames(k,T)||this.else))return this.condition=Y(this.condition,k,T),this}get names(){const k=super.names;return G(k,this.condition),this.else&&F(k,this.else.names),k}}v.kind="if";class d extends h{}d.kind="for";class m extends d{constructor(k){super(),this.iteration=k}render(k){return`for(${this.iteration})`+super.render(k)}optimizeNames(k,T){if(super.optimizeNames(k,T))return this.iteration=Y(this.iteration,k,T),this}get names(){return F(super.names,this.iteration.names)}}class b extends d{constructor(k,T,j,ee){super(),this.varKind=k,this.name=T,this.from=j,this.to=ee}render(k){const T=k.es5?r.varKinds.var:this.varKind,{name:j,from:ee,to:ne}=this;return`for(${T} ${j}=${ee}; ${j}<${ne}; ${j}++)`+super.render(k)}get names(){const k=G(super.names,this.from);return G(k,this.to)}}class y extends d{constructor(k,T,j,ee){super(),this.loop=k,this.varKind=T,this.name=j,this.iterable=ee}render(k){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(k)}optimizeNames(k,T){if(super.optimizeNames(k,T))return this.iterable=Y(this.iterable,k,T),this}get names(){return F(super.names,this.iterable.names)}}class $ extends h{constructor(k,T,j){super(),this.name=k,this.args=T,this.async=j}render(k){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(k)}}$.kind="func";class E extends _{render(k){return"return "+super.render(k)}}E.kind="return";class N extends h{render(k){let T="try"+super.render(k);return this.catch&&(T+=this.catch.render(k)),this.finally&&(T+=this.finally.render(k)),T}optimizeNodes(){var k,T;return super.optimizeNodes(),(k=this.catch)===null||k===void 0||k.optimizeNodes(),(T=this.finally)===null||T===void 0||T.optimizeNodes(),this}optimizeNames(k,T){var j,ee;return super.optimizeNames(k,T),(j=this.catch)===null||j===void 0||j.optimizeNames(k,T),(ee=this.finally)===null||ee===void 0||ee.optimizeNames(k,T),this}get names(){const k=super.names;return this.catch&&F(k,this.catch.names),this.finally&&F(k,this.finally.names),k}}class L extends h{constructor(k){super(),this.error=k}render(k){return`catch(${this.error})`+super.render(k)}}L.kind="catch";class K extends h{render(k){return"finally"+super.render(k)}}K.kind="finally";class z{constructor(k,T={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...T,_n:T.lines?`
2
+ `:""},this._extScope=k,this._scope=new r.Scope({parent:k}),this._nodes=[new w]}toString(){return this._root.render(this.opts)}name(k){return this._scope.name(k)}scopeName(k){return this._extScope.name(k)}scopeValue(k,T){const j=this._extScope.value(k,T);return(this._values[j.prefix]||(this._values[j.prefix]=new Set)).add(j),j}getScopeValue(k,T){return this._extScope.getValue(k,T)}scopeRefs(k){return this._extScope.scopeRefs(k,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(k,T,j,ee){const ne=this._scope.toName(T);return j!==void 0&&ee&&(this._constants[ne.str]=j),this._leafNode(new i(k,ne,j)),ne}const(k,T,j){return this._def(r.varKinds.const,k,T,j)}let(k,T,j){return this._def(r.varKinds.let,k,T,j)}var(k,T,j){return this._def(r.varKinds.var,k,T,j)}assign(k,T,j){return this._leafNode(new o(k,T,j))}add(k,T){return this._leafNode(new c(k,t.operators.ADD,T))}code(k){return typeof k=="function"?k():k!==e.nil&&this._leafNode(new g(k)),this}object(...k){const T=["{"];for(const[j,ee]of k)T.length>1&&T.push(","),T.push(j),(j!==ee||this.opts.es5)&&(T.push(":"),(0,e.addCodeArg)(T,ee));return T.push("}"),new e._Code(T)}if(k,T,j){if(this._blockNode(new v(k)),T&&j)this.code(T).else().code(j).endIf();else if(T)this.code(T).endIf();else if(j)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(k){return this._elseNode(new v(k))}else(){return this._elseNode(new f)}endIf(){return this._endBlockNode(v,f)}_for(k,T){return this._blockNode(k),T&&this.code(T).endFor(),this}for(k,T){return this._for(new m(k),T)}forRange(k,T,j,ee,ne=this.opts.es5?r.varKinds.var:r.varKinds.let){const me=this._scope.toName(k);return this._for(new b(ne,me,T,j),()=>ee(me))}forOf(k,T,j,ee=r.varKinds.const){const ne=this._scope.toName(k);if(this.opts.es5){const me=T instanceof e.Name?T:this.var("_arr",T);return this.forRange("_i",0,(0,e._)`${me}.length`,le=>{this.var(ne,(0,e._)`${me}[${le}]`),j(ne)})}return this._for(new y("of",ee,ne,T),()=>j(ne))}forIn(k,T,j,ee=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(k,(0,e._)`Object.keys(${T})`,j);const ne=this._scope.toName(k);return this._for(new y("in",ee,ne,T),()=>j(ne))}endFor(){return this._endBlockNode(d)}label(k){return this._leafNode(new u(k))}break(k){return this._leafNode(new l(k))}return(k){const T=new E;if(this._blockNode(T),this.code(k),T.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(E)}try(k,T,j){if(!T&&!j)throw new Error('CodeGen: "try" without "catch" and "finally"');const ee=new N;if(this._blockNode(ee),this.code(k),T){const ne=this.name("e");this._currNode=ee.catch=new L(ne),T(ne)}return j&&(this._currNode=ee.finally=new K,this.code(j)),this._endBlockNode(L,K)}throw(k){return this._leafNode(new p(k))}block(k,T){return this._blockStarts.push(this._nodes.length),k&&this.code(k).endBlock(T),this}endBlock(k){const T=this._blockStarts.pop();if(T===void 0)throw new Error("CodeGen: not in self-balancing block");const j=this._nodes.length-T;if(j<0||k!==void 0&&j!==k)throw new Error(`CodeGen: wrong number of nodes: ${j} vs ${k} expected`);return this._nodes.length=T,this}func(k,T=e.nil,j,ee){return this._blockNode(new $(k,T,j)),ee&&this.code(ee).endFunc(),this}endFunc(){return this._endBlockNode($)}optimize(k=1){for(;k-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(k){return this._currNode.nodes.push(k),this}_blockNode(k){this._currNode.nodes.push(k),this._nodes.push(k)}_endBlockNode(k,T){const j=this._currNode;if(j instanceof k||T&&j instanceof T)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${T?`${k.kind}/${T.kind}`:k.kind}"`)}_elseNode(k){const T=this._currNode;if(!(T instanceof v))throw new Error('CodeGen: "else" without "if"');return this._currNode=T.else=k,this}get _root(){return this._nodes[0]}get _currNode(){const k=this._nodes;return k[k.length-1]}set _currNode(k){const T=this._nodes;T[T.length-1]=k}}t.CodeGen=z;function F(O,k){for(const T in k)O[T]=(O[T]||0)+(k[T]||0);return O}function G(O,k){return k instanceof e._CodeOrName?F(O,k.names):O}function Y(O,k,T){if(O instanceof e.Name)return j(O);if(!ee(O))return O;return new e._Code(O._items.reduce((ne,me)=>(me instanceof e.Name&&(me=j(me)),me instanceof e._Code?ne.push(...me._items):ne.push(me),ne),[]));function j(ne){const me=T[ne.str];return me===void 0||k[ne.str]!==1?ne:(delete k[ne.str],me)}function ee(ne){return ne instanceof e._Code&&ne._items.some(me=>me instanceof e.Name&&k[me.str]===1&&T[me.str]!==void 0)}}function ge(O,k){for(const T in k)O[T]=(O[T]||0)-(k[T]||0)}function We(O){return typeof O=="boolean"||typeof O=="number"||O===null?!O:(0,e._)`!${q(O)}`}t.not=We;const Ke=C(t.operators.AND);function we(...O){return O.reduce(Ke)}t.and=we;const mt=C(t.operators.OR);function x(...O){return O.reduce(mt)}t.or=x;function C(O){return(k,T)=>k===e.nil?T:T===e.nil?k:(0,e._)`${q(k)} ${O} ${q(T)}`}function q(O){return O instanceof e.Name?O:(0,e._)`(${O})`}})(Hs)),Hs}var ie={},Yi;function fe(){if(Yi)return ie;Yi=1,Object.defineProperty(ie,"__esModule",{value:!0}),ie.checkStrictMode=ie.getErrorPath=ie.Type=ie.useFunc=ie.setEvaluated=ie.evaluatedPropsToName=ie.mergeEvaluated=ie.eachItem=ie.unescapeJsonPointer=ie.escapeJsonPointer=ie.escapeFragment=ie.unescapeFragment=ie.schemaRefOrVal=ie.schemaHasRulesButRef=ie.schemaHasRules=ie.checkUnknownRules=ie.alwaysValidSchema=ie.toHash=void 0;const t=ae(),e=rn();function r(y){const $={};for(const E of y)$[E]=!0;return $}ie.toHash=r;function n(y,$){return typeof $=="boolean"?$:Object.keys($).length===0?!0:(s(y,$),!a($,y.self.RULES.all))}ie.alwaysValidSchema=n;function s(y,$=y.schema){const{opts:E,self:N}=y;if(!E.strictSchema||typeof $=="boolean")return;const L=N.RULES.keywords;for(const K in $)L[K]||b(y,`unknown keyword: "${K}"`)}ie.checkUnknownRules=s;function a(y,$){if(typeof y=="boolean")return!y;for(const E in y)if($[E])return!0;return!1}ie.schemaHasRules=a;function i(y,$){if(typeof y=="boolean")return!y;for(const E in y)if(E!=="$ref"&&$.all[E])return!0;return!1}ie.schemaHasRulesButRef=i;function o({topSchemaRef:y,schemaPath:$},E,N,L){if(!L){if(typeof E=="number"||typeof E=="boolean")return E;if(typeof E=="string")return(0,t._)`${E}`}return(0,t._)`${y}${$}${(0,t.getProperty)(N)}`}ie.schemaRefOrVal=o;function c(y){return p(decodeURIComponent(y))}ie.unescapeFragment=c;function u(y){return encodeURIComponent(l(y))}ie.escapeFragment=u;function l(y){return typeof y=="number"?`${y}`:y.replace(/~/g,"~0").replace(/\//g,"~1")}ie.escapeJsonPointer=l;function p(y){return y.replace(/~1/g,"/").replace(/~0/g,"~")}ie.unescapeJsonPointer=p;function g(y,$){if(Array.isArray(y))for(const E of y)$(E);else $(y)}ie.eachItem=g;function _({mergeNames:y,mergeToName:$,mergeValues:E,resultToName:N}){return(L,K,z,F)=>{const G=z===void 0?K:z instanceof t.Name?(K instanceof t.Name?y(L,K,z):$(L,K,z),z):K instanceof t.Name?($(L,z,K),K):E(K,z);return F===t.Name&&!(G instanceof t.Name)?N(L,G):G}}ie.mergeEvaluated={props:_({mergeNames:(y,$,E)=>y.if((0,t._)`${E} !== true && ${$} !== undefined`,()=>{y.if((0,t._)`${$} === true`,()=>y.assign(E,!0),()=>y.assign(E,(0,t._)`${E} || {}`).code((0,t._)`Object.assign(${E}, ${$})`))}),mergeToName:(y,$,E)=>y.if((0,t._)`${E} !== true`,()=>{$===!0?y.assign(E,!0):(y.assign(E,(0,t._)`${E} || {}`),w(y,E,$))}),mergeValues:(y,$)=>y===!0?!0:{...y,...$},resultToName:h}),items:_({mergeNames:(y,$,E)=>y.if((0,t._)`${E} !== true && ${$} !== undefined`,()=>y.assign(E,(0,t._)`${$} === true ? true : ${E} > ${$} ? ${E} : ${$}`)),mergeToName:(y,$,E)=>y.if((0,t._)`${E} !== true`,()=>y.assign(E,$===!0?!0:(0,t._)`${E} > ${$} ? ${E} : ${$}`)),mergeValues:(y,$)=>y===!0?!0:Math.max(y,$),resultToName:(y,$)=>y.var("items",$)})};function h(y,$){if($===!0)return y.var("props",!0);const E=y.var("props",(0,t._)`{}`);return $!==void 0&&w(y,E,$),E}ie.evaluatedPropsToName=h;function w(y,$,E){Object.keys(E).forEach(N=>y.assign((0,t._)`${$}${(0,t.getProperty)(N)}`,!0))}ie.setEvaluated=w;const f={};function v(y,$){return y.scopeValue("func",{ref:$,code:f[$.code]||(f[$.code]=new e._Code($.code))})}ie.useFunc=v;var d;(function(y){y[y.Num=0]="Num",y[y.Str=1]="Str"})(d||(ie.Type=d={}));function m(y,$,E){if(y instanceof t.Name){const N=$===d.Num;return E?N?(0,t._)`"[" + ${y} + "]"`:(0,t._)`"['" + ${y} + "']"`:N?(0,t._)`"/" + ${y}`:(0,t._)`"/" + ${y}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return E?(0,t.getProperty)(y).toString():"/"+l(y)}ie.getErrorPath=m;function b(y,$,E=y.opts.strictSchema){if(E){if($=`strict mode: ${$}`,E===!0)throw new Error($);y.self.logger.warn($)}}return ie.checkStrictMode=b,ie}var nn={},Qi;function Et(){if(Qi)return nn;Qi=1,Object.defineProperty(nn,"__esModule",{value:!0});const t=ae(),e={data:new t.Name("data"),valCxt:new t.Name("valCxt"),instancePath:new t.Name("instancePath"),parentData:new t.Name("parentData"),parentDataProperty:new t.Name("parentDataProperty"),rootData:new t.Name("rootData"),dynamicAnchors:new t.Name("dynamicAnchors"),vErrors:new t.Name("vErrors"),errors:new t.Name("errors"),this:new t.Name("this"),self:new t.Name("self"),scope:new t.Name("scope"),json:new t.Name("json"),jsonPos:new t.Name("jsonPos"),jsonLen:new t.Name("jsonLen"),jsonPart:new t.Name("jsonPart")};return nn.default=e,nn}var Xi;function sn(){return Xi||(Xi=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=ae(),r=fe(),n=Et();t.keywordError={message:({keyword:f})=>(0,e.str)`must pass "${f}" keyword validation`},t.keyword$DataError={message:({keyword:f,schemaType:v})=>v?(0,e.str)`"${f}" keyword must be ${v} ($data)`:(0,e.str)`"${f}" keyword is invalid ($data)`};function s(f,v=t.keywordError,d,m){const{it:b}=f,{gen:y,compositeRule:$,allErrors:E}=b,N=p(f,v,d);m??($||E)?c(y,N):u(b,(0,e._)`[${N}]`)}t.reportError=s;function a(f,v=t.keywordError,d){const{it:m}=f,{gen:b,compositeRule:y,allErrors:$}=m,E=p(f,v,d);c(b,E),y||$||u(m,n.default.vErrors)}t.reportExtraError=a;function i(f,v){f.assign(n.default.errors,v),f.if((0,e._)`${n.default.vErrors} !== null`,()=>f.if(v,()=>f.assign((0,e._)`${n.default.vErrors}.length`,v),()=>f.assign(n.default.vErrors,null)))}t.resetErrorsCount=i;function o({gen:f,keyword:v,schemaValue:d,data:m,errsCount:b,it:y}){if(b===void 0)throw new Error("ajv implementation error");const $=f.name("err");f.forRange("i",b,n.default.errors,E=>{f.const($,(0,e._)`${n.default.vErrors}[${E}]`),f.if((0,e._)`${$}.instancePath === undefined`,()=>f.assign((0,e._)`${$}.instancePath`,(0,e.strConcat)(n.default.instancePath,y.errorPath))),f.assign((0,e._)`${$}.schemaPath`,(0,e.str)`${y.errSchemaPath}/${v}`),y.opts.verbose&&(f.assign((0,e._)`${$}.schema`,d),f.assign((0,e._)`${$}.data`,m))})}t.extendErrors=o;function c(f,v){const d=f.const("err",v);f.if((0,e._)`${n.default.vErrors} === null`,()=>f.assign(n.default.vErrors,(0,e._)`[${d}]`),(0,e._)`${n.default.vErrors}.push(${d})`),f.code((0,e._)`${n.default.errors}++`)}function u(f,v){const{gen:d,validateName:m,schemaEnv:b}=f;b.$async?d.throw((0,e._)`new ${f.ValidationError}(${v})`):(d.assign((0,e._)`${m}.errors`,v),d.return(!1))}const l={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function p(f,v,d){const{createErrors:m}=f.it;return m===!1?(0,e._)`{}`:g(f,v,d)}function g(f,v,d={}){const{gen:m,it:b}=f,y=[_(b,d),h(f,d)];return w(f,v,y),m.object(...y)}function _({errorPath:f},{instancePath:v}){const d=v?(0,e.str)`${f}${(0,r.getErrorPath)(v,r.Type.Str)}`:f;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,d)]}function h({keyword:f,it:{errSchemaPath:v}},{schemaPath:d,parentSchema:m}){let b=m?v:(0,e.str)`${v}/${f}`;return d&&(b=(0,e.str)`${b}${(0,r.getErrorPath)(d,r.Type.Str)}`),[l.schemaPath,b]}function w(f,{params:v,message:d},m){const{keyword:b,data:y,schemaValue:$,it:E}=f,{opts:N,propertyName:L,topSchemaRef:K,schemaPath:z}=E;m.push([l.keyword,b],[l.params,typeof v=="function"?v(f):v||(0,e._)`{}`]),N.messages&&m.push([l.message,typeof d=="function"?d(f):d]),N.verbose&&m.push([l.schema,$],[l.parentSchema,(0,e._)`${K}${z}`],[n.default.data,y]),L&&m.push([l.propertyName,L])}})(Fs)),Fs}var eo;function Bd(){if(eo)return Zt;eo=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.boolOrEmptySchema=Zt.topBoolOrEmptySchema=void 0;const t=sn(),e=ae(),r=Et(),n={message:"boolean schema is false"};function s(o){const{gen:c,schema:u,validateName:l}=o;u===!1?i(o,!1):typeof u=="object"&&u.$async===!0?c.return(r.default.data):(c.assign((0,e._)`${l}.errors`,null),c.return(!0))}Zt.topBoolOrEmptySchema=s;function a(o,c){const{gen:u,schema:l}=o;l===!1?(u.var(c,!1),i(o)):u.var(c,!0)}Zt.boolOrEmptySchema=a;function i(o,c){const{gen:u,data:l}=o,p={gen:u,keyword:"false schema",data:l,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:o};(0,t.reportError)(p,n,void 0,c)}return Zt}var Ze={},Lt={},to;function ro(){if(to)return Lt;to=1,Object.defineProperty(Lt,"__esModule",{value:!0}),Lt.getRules=Lt.isJSONType=void 0;const t=["string","number","integer","boolean","null","object","array"],e=new Set(t);function r(s){return typeof s=="string"&&e.has(s)}Lt.isJSONType=r;function n(){const s={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...s,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},s.number,s.string,s.array,s.object],post:{rules:[]},all:{},keywords:{}}}return Lt.getRules=n,Lt}var vt={},no;function so(){if(no)return vt;no=1,Object.defineProperty(vt,"__esModule",{value:!0}),vt.shouldUseRule=vt.shouldUseGroup=vt.schemaHasRulesForType=void 0;function t({schema:n,self:s},a){const i=s.RULES.types[a];return i&&i!==!0&&e(n,i)}vt.schemaHasRulesForType=t;function e(n,s){return s.rules.some(a=>r(n,a))}vt.shouldUseGroup=e;function r(n,s){var a;return n[s.keyword]!==void 0||((a=s.definition.implements)===null||a===void 0?void 0:a.some(i=>n[i]!==void 0))}return vt.shouldUseRule=r,vt}var ao;function an(){if(ao)return Ze;ao=1,Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.reportTypeError=Ze.checkDataTypes=Ze.checkDataType=Ze.coerceAndCheckDataType=Ze.getJSONTypes=Ze.getSchemaTypes=Ze.DataType=void 0;const t=ro(),e=so(),r=sn(),n=ae(),s=fe();var a;(function(d){d[d.Correct=0]="Correct",d[d.Wrong=1]="Wrong"})(a||(Ze.DataType=a={}));function i(d){const m=o(d.type);if(m.includes("null")){if(d.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!m.length&&d.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');d.nullable===!0&&m.push("null")}return m}Ze.getSchemaTypes=i;function o(d){const m=Array.isArray(d)?d:d?[d]:[];if(m.every(t.isJSONType))return m;throw new Error("type must be JSONType or JSONType[]: "+m.join(","))}Ze.getJSONTypes=o;function c(d,m){const{gen:b,data:y,opts:$}=d,E=l(m,$.coerceTypes),N=m.length>0&&!(E.length===0&&m.length===1&&(0,e.schemaHasRulesForType)(d,m[0]));if(N){const L=h(m,y,$.strictNumbers,a.Wrong);b.if(L,()=>{E.length?p(d,m,E):f(d)})}return N}Ze.coerceAndCheckDataType=c;const u=new Set(["string","number","integer","boolean","null"]);function l(d,m){return m?d.filter(b=>u.has(b)||m==="array"&&b==="array"):[]}function p(d,m,b){const{gen:y,data:$,opts:E}=d,N=y.let("dataType",(0,n._)`typeof ${$}`),L=y.let("coerced",(0,n._)`undefined`);E.coerceTypes==="array"&&y.if((0,n._)`${N} == 'object' && Array.isArray(${$}) && ${$}.length == 1`,()=>y.assign($,(0,n._)`${$}[0]`).assign(N,(0,n._)`typeof ${$}`).if(h(m,$,E.strictNumbers),()=>y.assign(L,$))),y.if((0,n._)`${L} !== undefined`);for(const z of b)(u.has(z)||z==="array"&&E.coerceTypes==="array")&&K(z);y.else(),f(d),y.endIf(),y.if((0,n._)`${L} !== undefined`,()=>{y.assign($,L),g(d,L)});function K(z){switch(z){case"string":y.elseIf((0,n._)`${N} == "number" || ${N} == "boolean"`).assign(L,(0,n._)`"" + ${$}`).elseIf((0,n._)`${$} === null`).assign(L,(0,n._)`""`);return;case"number":y.elseIf((0,n._)`${N} == "boolean" || ${$} === null
3
+ || (${N} == "string" && ${$} && ${$} == +${$})`).assign(L,(0,n._)`+${$}`);return;case"integer":y.elseIf((0,n._)`${N} === "boolean" || ${$} === null
4
+ || (${N} === "string" && ${$} && ${$} == +${$} && !(${$} % 1))`).assign(L,(0,n._)`+${$}`);return;case"boolean":y.elseIf((0,n._)`${$} === "false" || ${$} === 0 || ${$} === null`).assign(L,!1).elseIf((0,n._)`${$} === "true" || ${$} === 1`).assign(L,!0);return;case"null":y.elseIf((0,n._)`${$} === "" || ${$} === 0 || ${$} === false`),y.assign(L,null);return;case"array":y.elseIf((0,n._)`${N} === "string" || ${N} === "number"
5
+ || ${N} === "boolean" || ${$} === null`).assign(L,(0,n._)`[${$}]`)}}}function g({gen:d,parentData:m,parentDataProperty:b},y){d.if((0,n._)`${m} !== undefined`,()=>d.assign((0,n._)`${m}[${b}]`,y))}function _(d,m,b,y=a.Correct){const $=y===a.Correct?n.operators.EQ:n.operators.NEQ;let E;switch(d){case"null":return(0,n._)`${m} ${$} null`;case"array":E=(0,n._)`Array.isArray(${m})`;break;case"object":E=(0,n._)`${m} && typeof ${m} == "object" && !Array.isArray(${m})`;break;case"integer":E=N((0,n._)`!(${m} % 1) && !isNaN(${m})`);break;case"number":E=N();break;default:return(0,n._)`typeof ${m} ${$} ${d}`}return y===a.Correct?E:(0,n.not)(E);function N(L=n.nil){return(0,n.and)((0,n._)`typeof ${m} == "number"`,L,b?(0,n._)`isFinite(${m})`:n.nil)}}Ze.checkDataType=_;function h(d,m,b,y){if(d.length===1)return _(d[0],m,b,y);let $;const E=(0,s.toHash)(d);if(E.array&&E.object){const N=(0,n._)`typeof ${m} != "object"`;$=E.null?N:(0,n._)`!${m} || ${N}`,delete E.null,delete E.array,delete E.object}else $=n.nil;E.number&&delete E.integer;for(const N in E)$=(0,n.and)($,_(N,m,b,y));return $}Ze.checkDataTypes=h;const w={message:({schema:d})=>`must be ${d}`,params:({schema:d,schemaValue:m})=>typeof d=="string"?(0,n._)`{type: ${d}}`:(0,n._)`{type: ${m}}`};function f(d){const m=v(d);(0,r.reportError)(m,w)}Ze.reportTypeError=f;function v(d){const{gen:m,data:b,schema:y}=d,$=(0,s.schemaRefOrVal)(d,y,"type");return{gen:m,keyword:"type",data:b,schema:y.type,schemaCode:$,schemaValue:$,parentSchema:y,params:{},it:d}}return Ze}var Sr={},io;function Yd(){if(io)return Sr;io=1,Object.defineProperty(Sr,"__esModule",{value:!0}),Sr.assignDefaults=void 0;const t=ae(),e=fe();function r(s,a){const{properties:i,items:o}=s.schema;if(a==="object"&&i)for(const c in i)n(s,c,i[c].default);else a==="array"&&Array.isArray(o)&&o.forEach((c,u)=>n(s,u,c.default))}Sr.assignDefaults=r;function n(s,a,i){const{gen:o,compositeRule:c,data:u,opts:l}=s;if(i===void 0)return;const p=(0,t._)`${u}${(0,t.getProperty)(a)}`;if(c){(0,e.checkStrictMode)(s,`default is ignored for: ${p}`);return}let g=(0,t._)`${p} === undefined`;l.useDefaults==="empty"&&(g=(0,t._)`${g} || ${p} === null || ${p} === ""`),o.if(g,(0,t._)`${p} = ${(0,t.stringify)(i)}`)}return Sr}var ct={},ye={},oo;function ut(){if(oo)return ye;oo=1,Object.defineProperty(ye,"__esModule",{value:!0}),ye.validateUnion=ye.validateArray=ye.usePattern=ye.callValidateCode=ye.schemaProperties=ye.allSchemaProperties=ye.noPropertyInData=ye.propertyInData=ye.isOwnProperty=ye.hasPropFunc=ye.reportMissingProp=ye.checkMissingProp=ye.checkReportMissingProp=void 0;const t=ae(),e=fe(),r=Et(),n=fe();function s(d,m){const{gen:b,data:y,it:$}=d;b.if(l(b,y,m,$.opts.ownProperties),()=>{d.setParams({missingProperty:(0,t._)`${m}`},!0),d.error()})}ye.checkReportMissingProp=s;function a({gen:d,data:m,it:{opts:b}},y,$){return(0,t.or)(...y.map(E=>(0,t.and)(l(d,m,E,b.ownProperties),(0,t._)`${$} = ${E}`)))}ye.checkMissingProp=a;function i(d,m){d.setParams({missingProperty:m},!0),d.error()}ye.reportMissingProp=i;function o(d){return d.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}ye.hasPropFunc=o;function c(d,m,b){return(0,t._)`${o(d)}.call(${m}, ${b})`}ye.isOwnProperty=c;function u(d,m,b,y){const $=(0,t._)`${m}${(0,t.getProperty)(b)} !== undefined`;return y?(0,t._)`${$} && ${c(d,m,b)}`:$}ye.propertyInData=u;function l(d,m,b,y){const $=(0,t._)`${m}${(0,t.getProperty)(b)} === undefined`;return y?(0,t.or)($,(0,t.not)(c(d,m,b))):$}ye.noPropertyInData=l;function p(d){return d?Object.keys(d).filter(m=>m!=="__proto__"):[]}ye.allSchemaProperties=p;function g(d,m){return p(m).filter(b=>!(0,e.alwaysValidSchema)(d,m[b]))}ye.schemaProperties=g;function _({schemaCode:d,data:m,it:{gen:b,topSchemaRef:y,schemaPath:$,errorPath:E},it:N},L,K,z){const F=z?(0,t._)`${d}, ${m}, ${y}${$}`:m,G=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,E)],[r.default.parentData,N.parentData],[r.default.parentDataProperty,N.parentDataProperty],[r.default.rootData,r.default.rootData]];N.opts.dynamicRef&&G.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const Y=(0,t._)`${F}, ${b.object(...G)}`;return K!==t.nil?(0,t._)`${L}.call(${K}, ${Y})`:(0,t._)`${L}(${Y})`}ye.callValidateCode=_;const h=(0,t._)`new RegExp`;function w({gen:d,it:{opts:m}},b){const y=m.unicodeRegExp?"u":"",{regExp:$}=m.code,E=$(b,y);return d.scopeValue("pattern",{key:E.toString(),ref:E,code:(0,t._)`${$.code==="new RegExp"?h:(0,n.useFunc)(d,$)}(${b}, ${y})`})}ye.usePattern=w;function f(d){const{gen:m,data:b,keyword:y,it:$}=d,E=m.name("valid");if($.allErrors){const L=m.let("valid",!0);return N(()=>m.assign(L,!1)),L}return m.var(E,!0),N(()=>m.break()),E;function N(L){const K=m.const("len",(0,t._)`${b}.length`);m.forRange("i",0,K,z=>{d.subschema({keyword:y,dataProp:z,dataPropType:e.Type.Num},E),m.if((0,t.not)(E),L)})}}ye.validateArray=f;function v(d){const{gen:m,schema:b,keyword:y,it:$}=d;if(!Array.isArray(b))throw new Error("ajv implementation error");if(b.some(K=>(0,e.alwaysValidSchema)($,K))&&!$.opts.unevaluated)return;const N=m.let("valid",!1),L=m.name("_valid");m.block(()=>b.forEach((K,z)=>{const F=d.subschema({keyword:y,schemaProp:z,compositeRule:!0},L);m.assign(N,(0,t._)`${N} || ${L}`),d.mergeValidEvaluated(F,L)||m.if((0,t.not)(N))})),d.result(N,()=>d.reset(),()=>d.error(!0))}return ye.validateUnion=v,ye}var co;function Qd(){if(co)return ct;co=1,Object.defineProperty(ct,"__esModule",{value:!0}),ct.validateKeywordUsage=ct.validSchemaType=ct.funcKeywordCode=ct.macroKeywordCode=void 0;const t=ae(),e=Et(),r=ut(),n=sn();function s(g,_){const{gen:h,keyword:w,schema:f,parentSchema:v,it:d}=g,m=_.macro.call(d.self,f,v,d),b=u(h,w,m);d.opts.validateSchema!==!1&&d.self.validateSchema(m,!0);const y=h.name("valid");g.subschema({schema:m,schemaPath:t.nil,errSchemaPath:`${d.errSchemaPath}/${w}`,topSchemaRef:b,compositeRule:!0},y),g.pass(y,()=>g.error(!0))}ct.macroKeywordCode=s;function a(g,_){var h;const{gen:w,keyword:f,schema:v,parentSchema:d,$data:m,it:b}=g;c(b,_);const y=!m&&_.compile?_.compile.call(b.self,v,d,b):_.validate,$=u(w,f,y),E=w.let("valid");g.block$data(E,N),g.ok((h=_.valid)!==null&&h!==void 0?h:E);function N(){if(_.errors===!1)z(),_.modifying&&i(g),F(()=>g.error());else{const G=_.async?L():K();_.modifying&&i(g),F(()=>o(g,G))}}function L(){const G=w.let("ruleErrs",null);return w.try(()=>z((0,t._)`await `),Y=>w.assign(E,!1).if((0,t._)`${Y} instanceof ${b.ValidationError}`,()=>w.assign(G,(0,t._)`${Y}.errors`),()=>w.throw(Y))),G}function K(){const G=(0,t._)`${$}.errors`;return w.assign(G,null),z(t.nil),G}function z(G=_.async?(0,t._)`await `:t.nil){const Y=b.opts.passContext?e.default.this:e.default.self,ge=!("compile"in _&&!m||_.schema===!1);w.assign(E,(0,t._)`${G}${(0,r.callValidateCode)(g,$,Y,ge)}`,_.modifying)}function F(G){var Y;w.if((0,t.not)((Y=_.valid)!==null&&Y!==void 0?Y:E),G)}}ct.funcKeywordCode=a;function i(g){const{gen:_,data:h,it:w}=g;_.if(w.parentData,()=>_.assign(h,(0,t._)`${w.parentData}[${w.parentDataProperty}]`))}function o(g,_){const{gen:h}=g;h.if((0,t._)`Array.isArray(${_})`,()=>{h.assign(e.default.vErrors,(0,t._)`${e.default.vErrors} === null ? ${_} : ${e.default.vErrors}.concat(${_})`).assign(e.default.errors,(0,t._)`${e.default.vErrors}.length`),(0,n.extendErrors)(g)},()=>g.error())}function c({schemaEnv:g},_){if(_.async&&!g.$async)throw new Error("async keyword in sync schema")}function u(g,_,h){if(h===void 0)throw new Error(`keyword "${_}" failed to compile`);return g.scopeValue("keyword",typeof h=="function"?{ref:h}:{ref:h,code:(0,t.stringify)(h)})}function l(g,_,h=!1){return!_.length||_.some(w=>w==="array"?Array.isArray(g):w==="object"?g&&typeof g=="object"&&!Array.isArray(g):typeof g==w||h&&typeof g>"u")}ct.validSchemaType=l;function p({schema:g,opts:_,self:h,errSchemaPath:w},f,v){if(Array.isArray(f.keyword)?!f.keyword.includes(v):f.keyword!==v)throw new Error("ajv implementation error");const d=f.dependencies;if(d?.some(m=>!Object.prototype.hasOwnProperty.call(g,m)))throw new Error(`parent schema must have dependencies of ${v}: ${d.join(",")}`);if(f.validateSchema&&!f.validateSchema(g[v])){const b=`keyword "${v}" value is invalid at path "${w}": `+h.errorsText(f.validateSchema.errors);if(_.validateSchema==="log")h.logger.error(b);else throw new Error(b)}}return ct.validateKeywordUsage=p,ct}var wt={},uo;function Xd(){if(uo)return wt;uo=1,Object.defineProperty(wt,"__esModule",{value:!0}),wt.extendSubschemaMode=wt.extendSubschemaData=wt.getSubschema=void 0;const t=ae(),e=fe();function r(a,{keyword:i,schemaProp:o,schema:c,schemaPath:u,errSchemaPath:l,topSchemaRef:p}){if(i!==void 0&&c!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(i!==void 0){const g=a.schema[i];return o===void 0?{schema:g,schemaPath:(0,t._)`${a.schemaPath}${(0,t.getProperty)(i)}`,errSchemaPath:`${a.errSchemaPath}/${i}`}:{schema:g[o],schemaPath:(0,t._)`${a.schemaPath}${(0,t.getProperty)(i)}${(0,t.getProperty)(o)}`,errSchemaPath:`${a.errSchemaPath}/${i}/${(0,e.escapeFragment)(o)}`}}if(c!==void 0){if(u===void 0||l===void 0||p===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:c,schemaPath:u,topSchemaRef:p,errSchemaPath:l}}throw new Error('either "keyword" or "schema" must be passed')}wt.getSubschema=r;function n(a,i,{dataProp:o,dataPropType:c,data:u,dataTypes:l,propertyName:p}){if(u!==void 0&&o!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:g}=i;if(o!==void 0){const{errorPath:h,dataPathArr:w,opts:f}=i,v=g.let("data",(0,t._)`${i.data}${(0,t.getProperty)(o)}`,!0);_(v),a.errorPath=(0,t.str)`${h}${(0,e.getErrorPath)(o,c,f.jsPropertySyntax)}`,a.parentDataProperty=(0,t._)`${o}`,a.dataPathArr=[...w,a.parentDataProperty]}if(u!==void 0){const h=u instanceof t.Name?u:g.let("data",u,!0);_(h),p!==void 0&&(a.propertyName=p)}l&&(a.dataTypes=l);function _(h){a.data=h,a.dataLevel=i.dataLevel+1,a.dataTypes=[],i.definedProperties=new Set,a.parentData=i.data,a.dataNames=[...i.dataNames,h]}}wt.extendSubschemaData=n;function s(a,{jtdDiscriminator:i,jtdMetadata:o,compositeRule:c,createErrors:u,allErrors:l}){c!==void 0&&(a.compositeRule=c),u!==void 0&&(a.createErrors=u),l!==void 0&&(a.allErrors=l),a.jtdDiscriminator=i,a.jtdMetadata=o}return wt.extendSubschemaMode=s,wt}var Fe={},Js,lo;function fo(){return lo||(lo=1,Js=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,a;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(a=Object.keys(e),n=a.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,a[s]))return!1;for(s=n;s--!==0;){var i=a[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}),Js}var Gs={exports:{}},ho;function ef(){if(ho)return Gs.exports;ho=1;var t=Gs.exports=function(n,s,a){typeof s=="function"&&(a=s,s={}),a=s.cb||a;var i=typeof a=="function"?a:a.pre||function(){},o=a.post||function(){};e(s,i,o,n,"",n)};t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function e(n,s,a,i,o,c,u,l,p,g){if(i&&typeof i=="object"&&!Array.isArray(i)){s(i,o,c,u,l,p,g);for(var _ in i){var h=i[_];if(Array.isArray(h)){if(_ in t.arrayKeywords)for(var w=0;w<h.length;w++)e(n,s,a,h[w],o+"/"+_+"/"+w,c,o,_,i,w)}else if(_ in t.propsKeywords){if(h&&typeof h=="object")for(var f in h)e(n,s,a,h[f],o+"/"+_+"/"+r(f),c,o,_,i,f)}else(_ in t.keywords||n.allKeys&&!(_ in t.skipKeywords))&&e(n,s,a,h,o+"/"+_,c,o,_,i)}a(i,o,c,u,l,p,g)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Gs.exports}var po;function on(){if(po)return Fe;po=1,Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.getSchemaRefs=Fe.resolveUrl=Fe.normalizeId=Fe._getFullPath=Fe.getFullPath=Fe.inlineRef=void 0;const t=fe(),e=fo(),r=ef(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function s(w,f=!0){return typeof w=="boolean"?!0:f===!0?!i(w):f?o(w)<=f:!1}Fe.inlineRef=s;const a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(w){for(const f in w){if(a.has(f))return!0;const v=w[f];if(Array.isArray(v)&&v.some(i)||typeof v=="object"&&i(v))return!0}return!1}function o(w){let f=0;for(const v in w){if(v==="$ref")return 1/0;if(f++,!n.has(v)&&(typeof w[v]=="object"&&(0,t.eachItem)(w[v],d=>f+=o(d)),f===1/0))return 1/0}return f}function c(w,f="",v){v!==!1&&(f=p(f));const d=w.parse(f);return u(w,d)}Fe.getFullPath=c;function u(w,f){return w.serialize(f).split("#")[0]+"#"}Fe._getFullPath=u;const l=/#\/?$/;function p(w){return w?w.replace(l,""):""}Fe.normalizeId=p;function g(w,f,v){return v=p(v),w.resolve(f,v)}Fe.resolveUrl=g;const _=/^[a-z_][-a-z0-9._]*$/i;function h(w,f){if(typeof w=="boolean")return{};const{schemaId:v,uriResolver:d}=this.opts,m=p(w[v]||f),b={"":m},y=c(d,m,!1),$={},E=new Set;return r(w,{allKeys:!0},(K,z,F,G)=>{if(G===void 0)return;const Y=y+z;let ge=b[G];typeof K[v]=="string"&&(ge=We.call(this,K[v])),Ke.call(this,K.$anchor),Ke.call(this,K.$dynamicAnchor),b[z]=ge;function We(we){const mt=this.opts.uriResolver.resolve;if(we=p(ge?mt(ge,we):we),E.has(we))throw L(we);E.add(we);let x=this.refs[we];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?N(K,x.schema,we):we!==p(Y)&&(we[0]==="#"?(N(K,$[we],we),$[we]=K):this.refs[we]=Y),we}function Ke(we){if(typeof we=="string"){if(!_.test(we))throw new Error(`invalid anchor "${we}"`);We.call(this,`#${we}`)}}}),$;function N(K,z,F){if(z!==void 0&&!e(K,z))throw L(F)}function L(K){return new Error(`reference "${K}" resolves to more than one schema`)}}return Fe.getSchemaRefs=h,Fe}var mo;function cn(){if(mo)return yt;mo=1,Object.defineProperty(yt,"__esModule",{value:!0}),yt.getData=yt.KeywordCxt=yt.validateFunctionCode=void 0;const t=Bd(),e=an(),r=so(),n=an(),s=Yd(),a=Qd(),i=Xd(),o=ae(),c=Et(),u=on(),l=fe(),p=sn();function g(P){if(y(P)&&(E(P),b(P))){f(P);return}_(P,()=>(0,t.topBoolOrEmptySchema)(P))}yt.validateFunctionCode=g;function _({gen:P,validateName:I,schema:M,schemaEnv:U,opts:re},ce){re.code.es5?P.func(I,(0,o._)`${c.default.data}, ${c.default.valCxt}`,U.$async,()=>{P.code((0,o._)`"use strict"; ${d(M,re)}`),w(P,re),P.code(ce)}):P.func(I,(0,o._)`${c.default.data}, ${h(re)}`,U.$async,()=>P.code(d(M,re)).code(ce))}function h(P){return(0,o._)`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${P.dynamicRef?(0,o._)`, ${c.default.dynamicAnchors}={}`:o.nil}}={}`}function w(P,I){P.if(c.default.valCxt,()=>{P.var(c.default.instancePath,(0,o._)`${c.default.valCxt}.${c.default.instancePath}`),P.var(c.default.parentData,(0,o._)`${c.default.valCxt}.${c.default.parentData}`),P.var(c.default.parentDataProperty,(0,o._)`${c.default.valCxt}.${c.default.parentDataProperty}`),P.var(c.default.rootData,(0,o._)`${c.default.valCxt}.${c.default.rootData}`),I.dynamicRef&&P.var(c.default.dynamicAnchors,(0,o._)`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{P.var(c.default.instancePath,(0,o._)`""`),P.var(c.default.parentData,(0,o._)`undefined`),P.var(c.default.parentDataProperty,(0,o._)`undefined`),P.var(c.default.rootData,c.default.data),I.dynamicRef&&P.var(c.default.dynamicAnchors,(0,o._)`{}`)})}function f(P){const{schema:I,opts:M,gen:U}=P;_(P,()=>{M.$comment&&I.$comment&&G(P),K(P),U.let(c.default.vErrors,null),U.let(c.default.errors,0),M.unevaluated&&v(P),N(P),Y(P)})}function v(P){const{gen:I,validateName:M}=P;P.evaluated=I.const("evaluated",(0,o._)`${M}.evaluated`),I.if((0,o._)`${P.evaluated}.dynamicProps`,()=>I.assign((0,o._)`${P.evaluated}.props`,(0,o._)`undefined`)),I.if((0,o._)`${P.evaluated}.dynamicItems`,()=>I.assign((0,o._)`${P.evaluated}.items`,(0,o._)`undefined`))}function d(P,I){const M=typeof P=="object"&&P[I.schemaId];return M&&(I.code.source||I.code.process)?(0,o._)`/*# sourceURL=${M} */`:o.nil}function m(P,I){if(y(P)&&(E(P),b(P))){$(P,I);return}(0,t.boolOrEmptySchema)(P,I)}function b({schema:P,self:I}){if(typeof P=="boolean")return!P;for(const M in P)if(I.RULES.all[M])return!0;return!1}function y(P){return typeof P.schema!="boolean"}function $(P,I){const{schema:M,gen:U,opts:re}=P;re.$comment&&M.$comment&&G(P),z(P),F(P);const ce=U.const("_errs",c.default.errors);N(P,ce),U.var(I,(0,o._)`${ce} === ${c.default.errors}`)}function E(P){(0,l.checkUnknownRules)(P),L(P)}function N(P,I){if(P.opts.jtd)return We(P,[],!1,I);const M=(0,e.getSchemaTypes)(P.schema),U=(0,e.coerceAndCheckDataType)(P,M);We(P,M,!U,I)}function L(P){const{schema:I,errSchemaPath:M,opts:U,self:re}=P;I.$ref&&U.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(I,re.RULES)&&re.logger.warn(`$ref: keywords ignored in schema at path "${M}"`)}function K(P){const{schema:I,opts:M}=P;I.default!==void 0&&M.useDefaults&&M.strictSchema&&(0,l.checkStrictMode)(P,"default is ignored in the schema root")}function z(P){const I=P.schema[P.opts.schemaId];I&&(P.baseId=(0,u.resolveUrl)(P.opts.uriResolver,P.baseId,I))}function F(P){if(P.schema.$async&&!P.schemaEnv.$async)throw new Error("async schema in sync schema")}function G({gen:P,schemaEnv:I,schema:M,errSchemaPath:U,opts:re}){const ce=M.$comment;if(re.$comment===!0)P.code((0,o._)`${c.default.self}.logger.log(${ce})`);else if(typeof re.$comment=="function"){const Ue=(0,o.str)`${U}/$comment`,_t=P.scopeValue("root",{ref:I.root});P.code((0,o._)`${c.default.self}.opts.$comment(${ce}, ${Ue}, ${_t}.schema)`)}}function Y(P){const{gen:I,schemaEnv:M,validateName:U,ValidationError:re,opts:ce}=P;M.$async?I.if((0,o._)`${c.default.errors} === 0`,()=>I.return(c.default.data),()=>I.throw((0,o._)`new ${re}(${c.default.vErrors})`)):(I.assign((0,o._)`${U}.errors`,c.default.vErrors),ce.unevaluated&&ge(P),I.return((0,o._)`${c.default.errors} === 0`))}function ge({gen:P,evaluated:I,props:M,items:U}){M instanceof o.Name&&P.assign((0,o._)`${I}.props`,M),U instanceof o.Name&&P.assign((0,o._)`${I}.items`,U)}function We(P,I,M,U){const{gen:re,schema:ce,data:Ue,allErrors:_t,opts:Ye,self:Qe}=P,{RULES:Ve}=Qe;if(ce.$ref&&(Ye.ignoreKeywordsWithRef||!(0,l.schemaHasRulesButRef)(ce,Ve))){re.block(()=>ee(P,"$ref",Ve.all.$ref.definition));return}Ye.jtd||we(P,I),re.block(()=>{for(const ot of Ve.rules)br(ot);br(Ve.post)});function br(ot){(0,r.shouldUseGroup)(ce,ot)&&(ot.type?(re.if((0,n.checkDataType)(ot.type,Ue,Ye.strictNumbers)),Ke(P,ot),I.length===1&&I[0]===ot.type&&M&&(re.else(),(0,n.reportTypeError)(P)),re.endIf()):Ke(P,ot),_t||re.if((0,o._)`${c.default.errors} === ${U||0}`))}}function Ke(P,I){const{gen:M,schema:U,opts:{useDefaults:re}}=P;re&&(0,s.assignDefaults)(P,I.type),M.block(()=>{for(const ce of I.rules)(0,r.shouldUseRule)(U,ce)&&ee(P,ce.keyword,ce.definition,I.type)})}function we(P,I){P.schemaEnv.meta||!P.opts.strictTypes||(mt(P,I),P.opts.allowUnionTypes||x(P,I),C(P,P.dataTypes))}function mt(P,I){if(I.length){if(!P.dataTypes.length){P.dataTypes=I;return}I.forEach(M=>{O(P.dataTypes,M)||T(P,`type "${M}" not allowed by context "${P.dataTypes.join(",")}"`)}),k(P,I)}}function x(P,I){I.length>1&&!(I.length===2&&I.includes("null"))&&T(P,"use allowUnionTypes to allow union type keyword")}function C(P,I){const M=P.self.RULES.all;for(const U in M){const re=M[U];if(typeof re=="object"&&(0,r.shouldUseRule)(P.schema,re)){const{type:ce}=re.definition;ce.length&&!ce.some(Ue=>q(I,Ue))&&T(P,`missing type "${ce.join(",")}" for keyword "${U}"`)}}}function q(P,I){return P.includes(I)||I==="number"&&P.includes("integer")}function O(P,I){return P.includes(I)||I==="integer"&&P.includes("number")}function k(P,I){const M=[];for(const U of P.dataTypes)O(I,U)?M.push(U):I.includes("integer")&&U==="number"&&M.push("integer");P.dataTypes=M}function T(P,I){const M=P.schemaEnv.baseId+P.errSchemaPath;I+=` at "${M}" (strictTypes)`,(0,l.checkStrictMode)(P,I,P.opts.strictTypes)}class j{constructor(I,M,U){if((0,a.validateKeywordUsage)(I,M,U),this.gen=I.gen,this.allErrors=I.allErrors,this.keyword=U,this.data=I.data,this.schema=I.schema[U],this.$data=M.$data&&I.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,l.schemaRefOrVal)(I,this.schema,U,this.$data),this.schemaType=M.schemaType,this.parentSchema=I.schema,this.params={},this.it=I,this.def=M,this.$data)this.schemaCode=I.gen.const("vSchema",le(this.$data,I));else if(this.schemaCode=this.schemaValue,!(0,a.validSchemaType)(this.schema,M.schemaType,M.allowUndefined))throw new Error(`${U} value must be ${JSON.stringify(M.schemaType)}`);("code"in M?M.trackErrors:M.errors!==!1)&&(this.errsCount=I.gen.const("_errs",c.default.errors))}result(I,M,U){this.failResult((0,o.not)(I),M,U)}failResult(I,M,U){this.gen.if(I),U?U():this.error(),M?(this.gen.else(),M(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(I,M){this.failResult((0,o.not)(I),void 0,M)}fail(I){if(I===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(I),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(I){if(!this.$data)return this.fail(I);const{schemaCode:M}=this;this.fail((0,o._)`${M} !== undefined && (${(0,o.or)(this.invalid$data(),I)})`)}error(I,M,U){if(M){this.setParams(M),this._error(I,U),this.setParams({});return}this._error(I,U)}_error(I,M){(I?p.reportExtraError:p.reportError)(this,this.def.error,M)}$dataError(){(0,p.reportError)(this,this.def.$dataError||p.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,p.resetErrorsCount)(this.gen,this.errsCount)}ok(I){this.allErrors||this.gen.if(I)}setParams(I,M){M?Object.assign(this.params,I):this.params=I}block$data(I,M,U=o.nil){this.gen.block(()=>{this.check$data(I,U),M()})}check$data(I=o.nil,M=o.nil){if(!this.$data)return;const{gen:U,schemaCode:re,schemaType:ce,def:Ue}=this;U.if((0,o.or)((0,o._)`${re} === undefined`,M)),I!==o.nil&&U.assign(I,!0),(ce.length||Ue.validateSchema)&&(U.elseIf(this.invalid$data()),this.$dataError(),I!==o.nil&&U.assign(I,!1)),U.else()}invalid$data(){const{gen:I,schemaCode:M,schemaType:U,def:re,it:ce}=this;return(0,o.or)(Ue(),_t());function Ue(){if(U.length){if(!(M instanceof o.Name))throw new Error("ajv implementation error");const Ye=Array.isArray(U)?U:[U];return(0,o._)`${(0,n.checkDataTypes)(Ye,M,ce.opts.strictNumbers,n.DataType.Wrong)}`}return o.nil}function _t(){if(re.validateSchema){const Ye=I.scopeValue("validate$data",{ref:re.validateSchema});return(0,o._)`!${Ye}(${M})`}return o.nil}}subschema(I,M){const U=(0,i.getSubschema)(this.it,I);(0,i.extendSubschemaData)(U,this.it,I),(0,i.extendSubschemaMode)(U,I);const re={...this.it,...U,items:void 0,props:void 0};return m(re,M),re}mergeEvaluated(I,M){const{it:U,gen:re}=this;U.opts.unevaluated&&(U.props!==!0&&I.props!==void 0&&(U.props=l.mergeEvaluated.props(re,I.props,U.props,M)),U.items!==!0&&I.items!==void 0&&(U.items=l.mergeEvaluated.items(re,I.items,U.items,M)))}mergeValidEvaluated(I,M){const{it:U,gen:re}=this;if(U.opts.unevaluated&&(U.props!==!0||U.items!==!0))return re.if(M,()=>this.mergeEvaluated(I,o.Name)),!0}}yt.KeywordCxt=j;function ee(P,I,M,U){const re=new j(P,M,I);"code"in M?M.code(re,U):re.$data&&M.validate?(0,a.funcKeywordCode)(re,M):"macro"in M?(0,a.macroKeywordCode)(re,M):(M.compile||M.validate)&&(0,a.funcKeywordCode)(re,M)}const ne=/^\/(?:[^~]|~0|~1)*$/,me=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function le(P,{dataLevel:I,dataNames:M,dataPathArr:U}){let re,ce;if(P==="")return c.default.rootData;if(P[0]==="/"){if(!ne.test(P))throw new Error(`Invalid JSON-pointer: ${P}`);re=P,ce=c.default.rootData}else{const Qe=me.exec(P);if(!Qe)throw new Error(`Invalid JSON-pointer: ${P}`);const Ve=+Qe[1];if(re=Qe[2],re==="#"){if(Ve>=I)throw new Error(Ye("property/index",Ve));return U[I-Ve]}if(Ve>I)throw new Error(Ye("data",Ve));if(ce=M[I-Ve],!re)return ce}let Ue=ce;const _t=re.split("/");for(const Qe of _t)Qe&&(ce=(0,o._)`${ce}${(0,o.getProperty)((0,l.unescapeJsonPointer)(Qe))}`,Ue=(0,o._)`${Ue} && ${ce}`);return Ue;function Ye(Qe,Ve){return`Cannot access ${Qe} ${Ve} levels up, current level is ${I}`}}return yt.getData=le,yt}var un={},_o;function Bs(){if(_o)return un;_o=1,Object.defineProperty(un,"__esModule",{value:!0});class t extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return un.default=t,un}var ln={},go;function dn(){if(go)return ln;go=1,Object.defineProperty(ln,"__esModule",{value:!0});const t=on();class e extends Error{constructor(n,s,a,i){super(i||`can't resolve reference ${a} from id ${s}`),this.missingRef=(0,t.resolveUrl)(n,s,a),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(n,this.missingRef))}}return ln.default=e,ln}var Xe={},yo;function Ys(){if(yo)return Xe;yo=1,Object.defineProperty(Xe,"__esModule",{value:!0}),Xe.resolveSchema=Xe.getCompilingSchema=Xe.resolveRef=Xe.compileSchema=Xe.SchemaEnv=void 0;const t=ae(),e=Bs(),r=Et(),n=on(),s=fe(),a=cn();class i{constructor(v){var d;this.refs={},this.dynamicAnchors={};let m;typeof v.schema=="object"&&(m=v.schema),this.schema=v.schema,this.schemaId=v.schemaId,this.root=v.root||this,this.baseId=(d=v.baseId)!==null&&d!==void 0?d:(0,n.normalizeId)(m?.[v.schemaId||"$id"]),this.schemaPath=v.schemaPath,this.localRefs=v.localRefs,this.meta=v.meta,this.$async=m?.$async,this.refs={}}}Xe.SchemaEnv=i;function o(f){const v=l.call(this,f);if(v)return v;const d=(0,n.getFullPath)(this.opts.uriResolver,f.root.baseId),{es5:m,lines:b}=this.opts.code,{ownProperties:y}=this.opts,$=new t.CodeGen(this.scope,{es5:m,lines:b,ownProperties:y});let E;f.$async&&(E=$.scopeValue("Error",{ref:e.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));const N=$.scopeName("validate");f.validateName=N;const L={gen:$,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:$.scopeValue("schema",this.opts.code.source===!0?{ref:f.schema,code:(0,t.stringify)(f.schema)}:{ref:f.schema}),validateName:N,ValidationError:E,schema:f.schema,schemaEnv:f,rootId:d,baseId:f.baseId||d,schemaPath:t.nil,errSchemaPath:f.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,t._)`""`,opts:this.opts,self:this};let K;try{this._compilations.add(f),(0,a.validateFunctionCode)(L),$.optimize(this.opts.code.optimize);const z=$.toString();K=`${$.scopeRefs(r.default.scope)}return ${z}`,this.opts.code.process&&(K=this.opts.code.process(K,f));const G=new Function(`${r.default.self}`,`${r.default.scope}`,K)(this,this.scope.get());if(this.scope.value(N,{ref:G}),G.errors=null,G.schema=f.schema,G.schemaEnv=f,f.$async&&(G.$async=!0),this.opts.code.source===!0&&(G.source={validateName:N,validateCode:z,scopeValues:$._values}),this.opts.unevaluated){const{props:Y,items:ge}=L;G.evaluated={props:Y instanceof t.Name?void 0:Y,items:ge instanceof t.Name?void 0:ge,dynamicProps:Y instanceof t.Name,dynamicItems:ge instanceof t.Name},G.source&&(G.source.evaluated=(0,t.stringify)(G.evaluated))}return f.validate=G,f}catch(z){throw delete f.validate,delete f.validateName,K&&this.logger.error("Error compiling schema, function code:",K),z}finally{this._compilations.delete(f)}}Xe.compileSchema=o;function c(f,v,d){var m;d=(0,n.resolveUrl)(this.opts.uriResolver,v,d);const b=f.refs[d];if(b)return b;let y=g.call(this,f,d);if(y===void 0){const $=(m=f.localRefs)===null||m===void 0?void 0:m[d],{schemaId:E}=this.opts;$&&(y=new i({schema:$,schemaId:E,root:f,baseId:v}))}if(y!==void 0)return f.refs[d]=u.call(this,y)}Xe.resolveRef=c;function u(f){return(0,n.inlineRef)(f.schema,this.opts.inlineRefs)?f.schema:f.validate?f:o.call(this,f)}function l(f){for(const v of this._compilations)if(p(v,f))return v}Xe.getCompilingSchema=l;function p(f,v){return f.schema===v.schema&&f.root===v.root&&f.baseId===v.baseId}function g(f,v){let d;for(;typeof(d=this.refs[v])=="string";)v=d;return d||this.schemas[v]||_.call(this,f,v)}function _(f,v){const d=this.opts.uriResolver.parse(v),m=(0,n._getFullPath)(this.opts.uriResolver,d);let b=(0,n.getFullPath)(this.opts.uriResolver,f.baseId,void 0);if(Object.keys(f.schema).length>0&&m===b)return w.call(this,d,f);const y=(0,n.normalizeId)(m),$=this.refs[y]||this.schemas[y];if(typeof $=="string"){const E=_.call(this,f,$);return typeof E?.schema!="object"?void 0:w.call(this,d,E)}if(typeof $?.schema=="object"){if($.validate||o.call(this,$),y===(0,n.normalizeId)(v)){const{schema:E}=$,{schemaId:N}=this.opts,L=E[N];return L&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,L)),new i({schema:E,schemaId:N,root:f,baseId:b})}return w.call(this,d,$)}}Xe.resolveSchema=_;const h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function w(f,{baseId:v,schema:d,root:m}){var b;if(((b=f.fragment)===null||b===void 0?void 0:b[0])!=="/")return;for(const E of f.fragment.slice(1).split("/")){if(typeof d=="boolean")return;const N=d[(0,s.unescapeFragment)(E)];if(N===void 0)return;d=N;const L=typeof d=="object"&&d[this.opts.schemaId];!h.has(E)&&L&&(v=(0,n.resolveUrl)(this.opts.uriResolver,v,L))}let y;if(typeof d!="boolean"&&d.$ref&&!(0,s.schemaHasRulesButRef)(d,this.RULES)){const E=(0,n.resolveUrl)(this.opts.uriResolver,v,d.$ref);y=_.call(this,m,E)}const{schemaId:$}=this.opts;if(y=y||new i({schema:d,schemaId:$,root:m,baseId:v}),y.schema!==y.root.schema)return y}return Xe}const tf={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var fn={},kr={exports:{}},Qs,vo;function wo(){if(vo)return Qs;vo=1;const t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),e=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(g){let _="",h=0,w=0;for(w=0;w<g.length;w++)if(h=g[w].charCodeAt(0),h!==48){if(!(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102))return"";_+=g[w];break}for(w+=1;w<g.length;w++){if(h=g[w].charCodeAt(0),!(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102))return"";_+=g[w]}return _}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(g){return g.length=0,!0}function a(g,_,h){if(g.length){const w=r(g);if(w!=="")_.push(w);else return h.error=!0,!1;g.length=0}return!0}function i(g){let _=0;const h={error:!1,address:"",zone:""},w=[],f=[];let v=!1,d=!1,m=a;for(let b=0;b<g.length;b++){const y=g[b];if(!(y==="["||y==="]"))if(y===":"){if(v===!0&&(d=!0),!m(f,w,h))break;if(++_>7){h.error=!0;break}b>0&&g[b-1]===":"&&(v=!0),w.push(":");continue}else if(y==="%"){if(!m(f,w,h))break;m=s}else{f.push(y);continue}}return f.length&&(m===s?h.zone=f.join(""):d?w.push(f.join("")):w.push(r(f))),h.address=w.join(""),h}function o(g){if(c(g,":")<2)return{host:g,isIPV6:!1};const _=i(g);if(_.error)return{host:g,isIPV6:!1};{let h=_.address,w=_.address;return _.zone&&(h+="%"+_.zone,w+="%25"+_.zone),{host:h,isIPV6:!0,escapedHost:w}}}function c(g,_){let h=0;for(let w=0;w<g.length;w++)g[w]===_&&h++;return h}function u(g){let _=g;const h=[];let w=-1,f=0;for(;f=_.length;){if(f===1){if(_===".")break;if(_==="/"){h.push("/");break}else{h.push(_);break}}else if(f===2){if(_[0]==="."){if(_[1]===".")break;if(_[1]==="/"){_=_.slice(2);continue}}else if(_[0]==="/"&&(_[1]==="."||_[1]==="/")){h.push("/");break}}else if(f===3&&_==="/.."){h.length!==0&&h.pop(),h.push("/");break}if(_[0]==="."){if(_[1]==="."){if(_[2]==="/"){_=_.slice(3);continue}}else if(_[1]==="/"){_=_.slice(2);continue}}else if(_[0]==="/"&&_[1]==="."){if(_[2]==="/"){_=_.slice(2);continue}else if(_[2]==="."&&_[3]==="/"){_=_.slice(3),h.length!==0&&h.pop();continue}}if((w=_.indexOf("/",1))===-1){h.push(_);break}else h.push(_.slice(0,w)),_=_.slice(w)}return h.join("")}function l(g,_){const h=_!==!0?escape:unescape;return g.scheme!==void 0&&(g.scheme=h(g.scheme)),g.userinfo!==void 0&&(g.userinfo=h(g.userinfo)),g.host!==void 0&&(g.host=h(g.host)),g.path!==void 0&&(g.path=h(g.path)),g.query!==void 0&&(g.query=h(g.query)),g.fragment!==void 0&&(g.fragment=h(g.fragment)),g}function p(g){const _=[];if(g.userinfo!==void 0&&(_.push(g.userinfo),_.push("@")),g.host!==void 0){let h=unescape(g.host);if(!e(h)){const w=o(h);w.isIPV6===!0?h=`[${w.escapedHost}]`:h=g.host}_.push(h)}return(typeof g.port=="number"||typeof g.port=="string")&&(_.push(":"),_.push(String(g.port))),_.length?_.join(""):void 0}return Qs={nonSimpleDomain:n,recomposeAuthority:p,normalizeComponentEncoding:l,removeDotSegments:u,isIPv4:e,isUUID:t,normalizeIPv6:o,stringArrayToHexStripped:r},Qs}var Xs,bo;function rf(){if(bo)return Xs;bo=1;const{isUUID:t}=wo(),e=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(y){return r.indexOf(y)!==-1}function s(y){return y.secure===!0?!0:y.secure===!1?!1:y.scheme?y.scheme.length===3&&(y.scheme[0]==="w"||y.scheme[0]==="W")&&(y.scheme[1]==="s"||y.scheme[1]==="S")&&(y.scheme[2]==="s"||y.scheme[2]==="S"):!1}function a(y){return y.host||(y.error=y.error||"HTTP URIs must have a host."),y}function i(y){const $=String(y.scheme).toLowerCase()==="https";return(y.port===($?443:80)||y.port==="")&&(y.port=void 0),y.path||(y.path="/"),y}function o(y){return y.secure=s(y),y.resourceName=(y.path||"/")+(y.query?"?"+y.query:""),y.path=void 0,y.query=void 0,y}function c(y){if((y.port===(s(y)?443:80)||y.port==="")&&(y.port=void 0),typeof y.secure=="boolean"&&(y.scheme=y.secure?"wss":"ws",y.secure=void 0),y.resourceName){const[$,E]=y.resourceName.split("?");y.path=$&&$!=="/"?$:void 0,y.query=E,y.resourceName=void 0}return y.fragment=void 0,y}function u(y,$){if(!y.path)return y.error="URN can not be parsed",y;const E=y.path.match(e);if(E){const N=$.scheme||y.scheme||"urn";y.nid=E[1].toLowerCase(),y.nss=E[2];const L=`${N}:${$.nid||y.nid}`,K=b(L);y.path=void 0,K&&(y=K.parse(y,$))}else y.error=y.error||"URN can not be parsed.";return y}function l(y,$){if(y.nid===void 0)throw new Error("URN without nid cannot be serialized");const E=$.scheme||y.scheme||"urn",N=y.nid.toLowerCase(),L=`${E}:${$.nid||N}`,K=b(L);K&&(y=K.serialize(y,$));const z=y,F=y.nss;return z.path=`${N||$.nid}:${F}`,$.skipEscape=!0,z}function p(y,$){const E=y;return E.uuid=E.nss,E.nss=void 0,!$.tolerant&&(!E.uuid||!t(E.uuid))&&(E.error=E.error||"UUID is not valid."),E}function g(y){const $=y;return $.nss=(y.uuid||"").toLowerCase(),$}const _={scheme:"http",domainHost:!0,parse:a,serialize:i},h={scheme:"https",domainHost:_.domainHost,parse:a,serialize:i},w={scheme:"ws",domainHost:!0,parse:o,serialize:c},f={scheme:"wss",domainHost:w.domainHost,parse:w.parse,serialize:w.serialize},m={http:_,https:h,ws:w,wss:f,urn:{scheme:"urn",parse:u,serialize:l,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:p,serialize:g,skipNormalize:!0}};Object.setPrototypeOf(m,null);function b(y){return y&&(m[y]||m[y.toLowerCase()])||void 0}return Xs={wsIsSecure:s,SCHEMES:m,isValidSchemeName:n,getSchemeHandler:b},Xs}var So;function nf(){if(So)return kr.exports;So=1;const{normalizeIPv6:t,removeDotSegments:e,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:s,nonSimpleDomain:a}=wo(),{SCHEMES:i,getSchemeHandler:o}=rf();function c(f,v){return typeof f=="string"?f=g(h(f,v),v):typeof f=="object"&&(f=h(g(f,v),v)),f}function u(f,v,d){const m=d?Object.assign({scheme:"null"},d):{scheme:"null"},b=l(h(f,m),h(v,m),m,!0);return m.skipEscape=!0,g(b,m)}function l(f,v,d,m){const b={};return m||(f=h(g(f,d),d),v=h(g(v,d),d)),d=d||{},!d.tolerant&&v.scheme?(b.scheme=v.scheme,b.userinfo=v.userinfo,b.host=v.host,b.port=v.port,b.path=e(v.path||""),b.query=v.query):(v.userinfo!==void 0||v.host!==void 0||v.port!==void 0?(b.userinfo=v.userinfo,b.host=v.host,b.port=v.port,b.path=e(v.path||""),b.query=v.query):(v.path?(v.path[0]==="/"?b.path=e(v.path):((f.userinfo!==void 0||f.host!==void 0||f.port!==void 0)&&!f.path?b.path="/"+v.path:f.path?b.path=f.path.slice(0,f.path.lastIndexOf("/")+1)+v.path:b.path=v.path,b.path=e(b.path)),b.query=v.query):(b.path=f.path,v.query!==void 0?b.query=v.query:b.query=f.query),b.userinfo=f.userinfo,b.host=f.host,b.port=f.port),b.scheme=f.scheme),b.fragment=v.fragment,b}function p(f,v,d){return typeof f=="string"?(f=unescape(f),f=g(n(h(f,d),!0),{...d,skipEscape:!0})):typeof f=="object"&&(f=g(n(f,!0),{...d,skipEscape:!0})),typeof v=="string"?(v=unescape(v),v=g(n(h(v,d),!0),{...d,skipEscape:!0})):typeof v=="object"&&(v=g(n(v,!0),{...d,skipEscape:!0})),f.toLowerCase()===v.toLowerCase()}function g(f,v){const d={host:f.host,scheme:f.scheme,userinfo:f.userinfo,port:f.port,path:f.path,query:f.query,nid:f.nid,nss:f.nss,uuid:f.uuid,fragment:f.fragment,reference:f.reference,resourceName:f.resourceName,secure:f.secure,error:""},m=Object.assign({},v),b=[],y=o(m.scheme||d.scheme);y&&y.serialize&&y.serialize(d,m),d.path!==void 0&&(m.skipEscape?d.path=unescape(d.path):(d.path=escape(d.path),d.scheme!==void 0&&(d.path=d.path.split("%3A").join(":")))),m.reference!=="suffix"&&d.scheme&&b.push(d.scheme,":");const $=r(d);if($!==void 0&&(m.reference!=="suffix"&&b.push("//"),b.push($),d.path&&d.path[0]!=="/"&&b.push("/")),d.path!==void 0){let E=d.path;!m.absolutePath&&(!y||!y.absolutePath)&&(E=e(E)),$===void 0&&E[0]==="/"&&E[1]==="/"&&(E="/%2F"+E.slice(2)),b.push(E)}return d.query!==void 0&&b.push("?",d.query),d.fragment!==void 0&&b.push("#",d.fragment),b.join("")}const _=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function h(f,v){const d=Object.assign({},v),m={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let b=!1;d.reference==="suffix"&&(d.scheme?f=d.scheme+":"+f:f="//"+f);const y=f.match(_);if(y){if(m.scheme=y[1],m.userinfo=y[3],m.host=y[4],m.port=parseInt(y[5],10),m.path=y[6]||"",m.query=y[7],m.fragment=y[8],isNaN(m.port)&&(m.port=y[5]),m.host)if(s(m.host)===!1){const N=t(m.host);m.host=N.host.toLowerCase(),b=N.isIPV6}else b=!0;m.scheme===void 0&&m.userinfo===void 0&&m.host===void 0&&m.port===void 0&&m.query===void 0&&!m.path?m.reference="same-document":m.scheme===void 0?m.reference="relative":m.fragment===void 0?m.reference="absolute":m.reference="uri",d.reference&&d.reference!=="suffix"&&d.reference!==m.reference&&(m.error=m.error||"URI is not a "+d.reference+" reference.");const $=o(d.scheme||m.scheme);if(!d.unicodeSupport&&(!$||!$.unicodeSupport)&&m.host&&(d.domainHost||$&&$.domainHost)&&b===!1&&a(m.host))try{m.host=URL.domainToASCII(m.host.toLowerCase())}catch(E){m.error=m.error||"Host's domain name can not be converted to ASCII: "+E}(!$||$&&!$.skipNormalize)&&(f.indexOf("%")!==-1&&(m.scheme!==void 0&&(m.scheme=unescape(m.scheme)),m.host!==void 0&&(m.host=unescape(m.host))),m.path&&(m.path=escape(unescape(m.path))),m.fragment&&(m.fragment=encodeURI(decodeURIComponent(m.fragment)))),$&&$.parse&&$.parse(m,d)}else m.error=m.error||"URI can not be parsed.";return m}const w={SCHEMES:i,normalize:c,resolve:u,resolveComponent:l,equal:p,serialize:g,parse:h};return kr.exports=w,kr.exports.default=w,kr.exports.fastUri=w,kr.exports}var ko;function sf(){if(ko)return fn;ko=1,Object.defineProperty(fn,"__esModule",{value:!0});const t=nf();return t.code='require("ajv/dist/runtime/uri").default',fn.default=t,fn}var $o;function af(){return $o||($o=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=cn();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=ae();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Bs(),s=dn(),a=ro(),i=Ys(),o=ae(),c=on(),u=an(),l=fe(),p=tf,g=sf(),_=(x,C)=>new RegExp(x,C);_.code="new RegExp";const h=["removeAdditional","useDefaults","coerceTypes"],w=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),f={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},v={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},d=200;function m(x){var C,q,O,k,T,j,ee,ne,me,le,P,I,M,U,re,ce,Ue,_t,Ye,Qe,Ve,br,ot,Fi,Hi;const en=x.strict,Wi=(C=x.code)===null||C===void 0?void 0:C.optimize,Jd=Wi===!0||Wi===void 0?1:Wi||0,Gd=(O=(q=x.code)===null||q===void 0?void 0:q.regExp)!==null&&O!==void 0?O:_,$v=(k=x.uriResolver)!==null&&k!==void 0?k:g.default;return{strictSchema:(j=(T=x.strictSchema)!==null&&T!==void 0?T:en)!==null&&j!==void 0?j:!0,strictNumbers:(ne=(ee=x.strictNumbers)!==null&&ee!==void 0?ee:en)!==null&&ne!==void 0?ne:!0,strictTypes:(le=(me=x.strictTypes)!==null&&me!==void 0?me:en)!==null&&le!==void 0?le:"log",strictTuples:(I=(P=x.strictTuples)!==null&&P!==void 0?P:en)!==null&&I!==void 0?I:"log",strictRequired:(U=(M=x.strictRequired)!==null&&M!==void 0?M:en)!==null&&U!==void 0?U:!1,code:x.code?{...x.code,optimize:Jd,regExp:Gd}:{optimize:Jd,regExp:Gd},loopRequired:(re=x.loopRequired)!==null&&re!==void 0?re:d,loopEnum:(ce=x.loopEnum)!==null&&ce!==void 0?ce:d,meta:(Ue=x.meta)!==null&&Ue!==void 0?Ue:!0,messages:(_t=x.messages)!==null&&_t!==void 0?_t:!0,inlineRefs:(Ye=x.inlineRefs)!==null&&Ye!==void 0?Ye:!0,schemaId:(Qe=x.schemaId)!==null&&Qe!==void 0?Qe:"$id",addUsedSchema:(Ve=x.addUsedSchema)!==null&&Ve!==void 0?Ve:!0,validateSchema:(br=x.validateSchema)!==null&&br!==void 0?br:!0,validateFormats:(ot=x.validateFormats)!==null&&ot!==void 0?ot:!0,unicodeRegExp:(Fi=x.unicodeRegExp)!==null&&Fi!==void 0?Fi:!0,int32range:(Hi=x.int32range)!==null&&Hi!==void 0?Hi:!0,uriResolver:$v}}class b{constructor(C={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,C=this.opts={...C,...m(C)};const{es5:q,lines:O}=this.opts.code;this.scope=new o.ValueScope({scope:{},prefixes:w,es5:q,lines:O}),this.logger=F(C.logger);const k=C.validateFormats;C.validateFormats=!1,this.RULES=(0,a.getRules)(),y.call(this,f,C,"NOT SUPPORTED"),y.call(this,v,C,"DEPRECATED","warn"),this._metaOpts=K.call(this),C.formats&&N.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),C.keywords&&L.call(this,C.keywords),typeof C.meta=="object"&&this.addMetaSchema(C.meta),E.call(this),C.validateFormats=k}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:C,meta:q,schemaId:O}=this.opts;let k=p;O==="id"&&(k={...p},k.id=k.$id,delete k.$id),q&&C&&this.addMetaSchema(k,k[O],!1)}defaultMeta(){const{meta:C,schemaId:q}=this.opts;return this.opts.defaultMeta=typeof C=="object"?C[q]||C:void 0}validate(C,q){let O;if(typeof C=="string"){if(O=this.getSchema(C),!O)throw new Error(`no schema with key or ref "${C}"`)}else O=this.compile(C);const k=O(q);return"$async"in O||(this.errors=O.errors),k}compile(C,q){const O=this._addSchema(C,q);return O.validate||this._compileSchemaEnv(O)}compileAsync(C,q){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:O}=this.opts;return k.call(this,C,q);async function k(le,P){await T.call(this,le.$schema);const I=this._addSchema(le,P);return I.validate||j.call(this,I)}async function T(le){le&&!this.getSchema(le)&&await k.call(this,{$ref:le},!0)}async function j(le){try{return this._compileSchemaEnv(le)}catch(P){if(!(P instanceof s.default))throw P;return ee.call(this,P),await ne.call(this,P.missingSchema),j.call(this,le)}}function ee({missingSchema:le,missingRef:P}){if(this.refs[le])throw new Error(`AnySchema ${le} is loaded but ${P} cannot be resolved`)}async function ne(le){const P=await me.call(this,le);this.refs[le]||await T.call(this,P.$schema),this.refs[le]||this.addSchema(P,le,q)}async function me(le){const P=this._loading[le];if(P)return P;try{return await(this._loading[le]=O(le))}finally{delete this._loading[le]}}}addSchema(C,q,O,k=this.opts.validateSchema){if(Array.isArray(C)){for(const j of C)this.addSchema(j,void 0,O,k);return this}let T;if(typeof C=="object"){const{schemaId:j}=this.opts;if(T=C[j],T!==void 0&&typeof T!="string")throw new Error(`schema ${j} must be string`)}return q=(0,c.normalizeId)(q||T),this._checkUnique(q),this.schemas[q]=this._addSchema(C,O,q,k,!0),this}addMetaSchema(C,q,O=this.opts.validateSchema){return this.addSchema(C,q,!0,O),this}validateSchema(C,q){if(typeof C=="boolean")return!0;let O;if(O=C.$schema,O!==void 0&&typeof O!="string")throw new Error("$schema must be a string");if(O=O||this.opts.defaultMeta||this.defaultMeta(),!O)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const k=this.validate(O,C);if(!k&&q){const T="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(T);else throw new Error(T)}return k}getSchema(C){let q;for(;typeof(q=$.call(this,C))=="string";)C=q;if(q===void 0){const{schemaId:O}=this.opts,k=new i.SchemaEnv({schema:{},schemaId:O});if(q=i.resolveSchema.call(this,k,C),!q)return;this.refs[C]=q}return q.validate||this._compileSchemaEnv(q)}removeSchema(C){if(C instanceof RegExp)return this._removeAllSchemas(this.schemas,C),this._removeAllSchemas(this.refs,C),this;switch(typeof C){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const q=$.call(this,C);return typeof q=="object"&&this._cache.delete(q.schema),delete this.schemas[C],delete this.refs[C],this}case"object":{const q=C;this._cache.delete(q);let O=C[this.opts.schemaId];return O&&(O=(0,c.normalizeId)(O),delete this.schemas[O],delete this.refs[O]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(C){for(const q of C)this.addKeyword(q);return this}addKeyword(C,q){let O;if(typeof C=="string")O=C,typeof q=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),q.keyword=O);else if(typeof C=="object"&&q===void 0){if(q=C,O=q.keyword,Array.isArray(O)&&!O.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Y.call(this,O,q),!q)return(0,l.eachItem)(O,T=>ge.call(this,T)),this;Ke.call(this,q);const k={...q,type:(0,u.getJSONTypes)(q.type),schemaType:(0,u.getJSONTypes)(q.schemaType)};return(0,l.eachItem)(O,k.type.length===0?T=>ge.call(this,T,k):T=>k.type.forEach(j=>ge.call(this,T,k,j))),this}getKeyword(C){const q=this.RULES.all[C];return typeof q=="object"?q.definition:!!q}removeKeyword(C){const{RULES:q}=this;delete q.keywords[C],delete q.all[C];for(const O of q.rules){const k=O.rules.findIndex(T=>T.keyword===C);k>=0&&O.rules.splice(k,1)}return this}addFormat(C,q){return typeof q=="string"&&(q=new RegExp(q)),this.formats[C]=q,this}errorsText(C=this.errors,{separator:q=", ",dataVar:O="data"}={}){return!C||C.length===0?"No errors":C.map(k=>`${O}${k.instancePath} ${k.message}`).reduce((k,T)=>k+q+T)}$dataMetaSchema(C,q){const O=this.RULES.all;C=JSON.parse(JSON.stringify(C));for(const k of q){const T=k.split("/").slice(1);let j=C;for(const ee of T)j=j[ee];for(const ee in O){const ne=O[ee];if(typeof ne!="object")continue;const{$data:me}=ne.definition,le=j[ee];me&&le&&(j[ee]=mt(le))}}return C}_removeAllSchemas(C,q){for(const O in C){const k=C[O];(!q||q.test(O))&&(typeof k=="string"?delete C[O]:k&&!k.meta&&(this._cache.delete(k.schema),delete C[O]))}}_addSchema(C,q,O,k=this.opts.validateSchema,T=this.opts.addUsedSchema){let j;const{schemaId:ee}=this.opts;if(typeof C=="object")j=C[ee];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof C!="boolean")throw new Error("schema must be object or boolean")}let ne=this._cache.get(C);if(ne!==void 0)return ne;O=(0,c.normalizeId)(j||O);const me=c.getSchemaRefs.call(this,C,O);return ne=new i.SchemaEnv({schema:C,schemaId:ee,meta:q,baseId:O,localRefs:me}),this._cache.set(ne.schema,ne),T&&!O.startsWith("#")&&(O&&this._checkUnique(O),this.refs[O]=ne),k&&this.validateSchema(C,!0),ne}_checkUnique(C){if(this.schemas[C]||this.refs[C])throw new Error(`schema with key or id "${C}" already exists`)}_compileSchemaEnv(C){if(C.meta?this._compileMetaSchema(C):i.compileSchema.call(this,C),!C.validate)throw new Error("ajv implementation error");return C.validate}_compileMetaSchema(C){const q=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,C)}finally{this.opts=q}}}b.ValidationError=n.default,b.MissingRefError=s.default,t.default=b;function y(x,C,q,O="error"){for(const k in x){const T=k;T in C&&this.logger[O](`${q}: option ${k}. ${x[T]}`)}}function $(x){return x=(0,c.normalizeId)(x),this.schemas[x]||this.refs[x]}function E(){const x=this.opts.schemas;if(x)if(Array.isArray(x))this.addSchema(x);else for(const C in x)this.addSchema(x[C],C)}function N(){for(const x in this.opts.formats){const C=this.opts.formats[x];C&&this.addFormat(x,C)}}function L(x){if(Array.isArray(x)){this.addVocabulary(x);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const C in x){const q=x[C];q.keyword||(q.keyword=C),this.addKeyword(q)}}function K(){const x={...this.opts};for(const C of h)delete x[C];return x}const z={log(){},warn(){},error(){}};function F(x){if(x===!1)return z;if(x===void 0)return console;if(x.log&&x.warn&&x.error)return x;throw new Error("logger must implement log, warn and error methods")}const G=/^[a-z_$][a-z0-9_$:-]*$/i;function Y(x,C){const{RULES:q}=this;if((0,l.eachItem)(x,O=>{if(q.keywords[O])throw new Error(`Keyword ${O} is already defined`);if(!G.test(O))throw new Error(`Keyword ${O} has invalid name`)}),!!C&&C.$data&&!("code"in C||"validate"in C))throw new Error('$data keyword must have "code" or "validate" function')}function ge(x,C,q){var O;const k=C?.post;if(q&&k)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:T}=this;let j=k?T.post:T.rules.find(({type:ne})=>ne===q);if(j||(j={type:q,rules:[]},T.rules.push(j)),T.keywords[x]=!0,!C)return;const ee={keyword:x,definition:{...C,type:(0,u.getJSONTypes)(C.type),schemaType:(0,u.getJSONTypes)(C.schemaType)}};C.before?We.call(this,j,ee,C.before):j.rules.push(ee),T.all[x]=ee,(O=C.implements)===null||O===void 0||O.forEach(ne=>this.addKeyword(ne))}function We(x,C,q){const O=x.rules.findIndex(k=>k.keyword===q);O>=0?x.rules.splice(O,0,C):(x.rules.push(C),this.logger.warn(`rule ${q} is not defined`))}function Ke(x){let{metaSchema:C}=x;C!==void 0&&(x.$data&&this.opts.$data&&(C=mt(C)),x.validateSchema=this.compile(C,!0))}const we={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function mt(x){return{anyOf:[x,we]}}})(Vs)),Vs}var hn={},pn={},mn={},Eo;function of(){if(Eo)return mn;Eo=1,Object.defineProperty(mn,"__esModule",{value:!0});const t={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return mn.default=t,mn}var Rt={},Ro;function cf(){if(Ro)return Rt;Ro=1,Object.defineProperty(Rt,"__esModule",{value:!0}),Rt.callRef=Rt.getValidate=void 0;const t=dn(),e=ut(),r=ae(),n=Et(),s=Ys(),a=fe(),i={keyword:"$ref",schemaType:"string",code(u){const{gen:l,schema:p,it:g}=u,{baseId:_,schemaEnv:h,validateName:w,opts:f,self:v}=g,{root:d}=h;if((p==="#"||p==="#/")&&_===d.baseId)return b();const m=s.resolveRef.call(v,d,_,p);if(m===void 0)throw new t.default(g.opts.uriResolver,_,p);if(m instanceof s.SchemaEnv)return y(m);return $(m);function b(){if(h===d)return c(u,w,h,h.$async);const E=l.scopeValue("root",{ref:d});return c(u,(0,r._)`${E}.validate`,d,d.$async)}function y(E){const N=o(u,E);c(u,N,E,E.$async)}function $(E){const N=l.scopeValue("schema",f.code.source===!0?{ref:E,code:(0,r.stringify)(E)}:{ref:E}),L=l.name("valid"),K=u.subschema({schema:E,dataTypes:[],schemaPath:r.nil,topSchemaRef:N,errSchemaPath:p},L);u.mergeEvaluated(K),u.ok(L)}}};function o(u,l){const{gen:p}=u;return l.validate?p.scopeValue("validate",{ref:l.validate}):(0,r._)`${p.scopeValue("wrapper",{ref:l})}.validate`}Rt.getValidate=o;function c(u,l,p,g){const{gen:_,it:h}=u,{allErrors:w,schemaEnv:f,opts:v}=h,d=v.passContext?n.default.this:r.nil;g?m():b();function m(){if(!f.$async)throw new Error("async schema referenced by sync schema");const E=_.let("valid");_.try(()=>{_.code((0,r._)`await ${(0,e.callValidateCode)(u,l,d)}`),$(l),w||_.assign(E,!0)},N=>{_.if((0,r._)`!(${N} instanceof ${h.ValidationError})`,()=>_.throw(N)),y(N),w||_.assign(E,!1)}),u.ok(E)}function b(){u.result((0,e.callValidateCode)(u,l,d),()=>$(l),()=>y(l))}function y(E){const N=(0,r._)`${E}.errors`;_.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${N} : ${n.default.vErrors}.concat(${N})`),_.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function $(E){var N;if(!h.opts.unevaluated)return;const L=(N=p?.validate)===null||N===void 0?void 0:N.evaluated;if(h.props!==!0)if(L&&!L.dynamicProps)L.props!==void 0&&(h.props=a.mergeEvaluated.props(_,L.props,h.props));else{const K=_.var("props",(0,r._)`${E}.evaluated.props`);h.props=a.mergeEvaluated.props(_,K,h.props,r.Name)}if(h.items!==!0)if(L&&!L.dynamicItems)L.items!==void 0&&(h.items=a.mergeEvaluated.items(_,L.items,h.items));else{const K=_.var("items",(0,r._)`${E}.evaluated.items`);h.items=a.mergeEvaluated.items(_,K,h.items,r.Name)}}}return Rt.callRef=c,Rt.default=i,Rt}var To;function uf(){if(To)return pn;To=1,Object.defineProperty(pn,"__esModule",{value:!0});const t=of(),e=cf(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,e.default];return pn.default=r,pn}var _n={},gn={},Po;function lf(){if(Po)return gn;Po=1,Object.defineProperty(gn,"__esModule",{value:!0});const t=ae(),e=t.operators,r={maximum:{okStr:"<=",ok:e.LTE,fail:e.GT},minimum:{okStr:">=",ok:e.GTE,fail:e.LT},exclusiveMaximum:{okStr:"<",ok:e.LT,fail:e.GTE},exclusiveMinimum:{okStr:">",ok:e.GT,fail:e.LTE}},n={message:({keyword:a,schemaCode:i})=>(0,t.str)`must be ${r[a].okStr} ${i}`,params:({keyword:a,schemaCode:i})=>(0,t._)`{comparison: ${r[a].okStr}, limit: ${i}}`},s={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(a){const{keyword:i,data:o,schemaCode:c}=a;a.fail$data((0,t._)`${o} ${r[i].fail} ${c} || isNaN(${o})`)}};return gn.default=s,gn}var yn={},Co;function df(){if(Co)return yn;Co=1,Object.defineProperty(yn,"__esModule",{value:!0});const t=ae(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,t._)`{multipleOf: ${n}}`},code(n){const{gen:s,data:a,schemaCode:i,it:o}=n,c=o.opts.multipleOfPrecision,u=s.let("res"),l=c?(0,t._)`Math.abs(Math.round(${u}) - ${u}) > 1e-${c}`:(0,t._)`${u} !== parseInt(${u})`;n.fail$data((0,t._)`(${i} === 0 || (${u} = ${a}/${i}, ${l}))`)}};return yn.default=r,yn}var vn={},wn={},Io;function ff(){if(Io)return wn;Io=1,Object.defineProperty(wn,"__esModule",{value:!0});function t(e){const r=e.length;let n=0,s=0,a;for(;s<r;)n++,a=e.charCodeAt(s++),a>=55296&&a<=56319&&s<r&&(a=e.charCodeAt(s),(a&64512)===56320&&s++);return n}return wn.default=t,t.code='require("ajv/dist/runtime/ucs2length").default',wn}var Oo;function hf(){if(Oo)return vn;Oo=1,Object.defineProperty(vn,"__esModule",{value:!0});const t=ae(),e=fe(),r=ff(),s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:a,schemaCode:i}){const o=a==="maxLength"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${i} characters`},params:({schemaCode:a})=>(0,t._)`{limit: ${a}}`},code(a){const{keyword:i,data:o,schemaCode:c,it:u}=a,l=i==="maxLength"?t.operators.GT:t.operators.LT,p=u.opts.unicode===!1?(0,t._)`${o}.length`:(0,t._)`${(0,e.useFunc)(a.gen,r.default)}(${o})`;a.fail$data((0,t._)`${p} ${l} ${c}`)}};return vn.default=s,vn}var bn={},No;function pf(){if(No)return bn;No=1,Object.defineProperty(bn,"__esModule",{value:!0});const t=ut(),e=ae(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,e.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,e._)`{pattern: ${s}}`},code(s){const{data:a,$data:i,schema:o,schemaCode:c,it:u}=s,l=u.opts.unicodeRegExp?"u":"",p=i?(0,e._)`(new RegExp(${c}, ${l}))`:(0,t.usePattern)(s,o);s.fail$data((0,e._)`!${p}.test(${a})`)}};return bn.default=n,bn}var Sn={},Ao;function mf(){if(Ao)return Sn;Ao=1,Object.defineProperty(Sn,"__esModule",{value:!0});const t=ae(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const a=n==="maxProperties"?"more":"fewer";return(0,t.str)`must NOT have ${a} than ${s} properties`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:a,schemaCode:i}=n,o=s==="maxProperties"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`Object.keys(${a}).length ${o} ${i}`)}};return Sn.default=r,Sn}var kn={},jo;function _f(){if(jo)return kn;jo=1,Object.defineProperty(kn,"__esModule",{value:!0});const t=ut(),e=ae(),r=fe(),s={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:a}})=>(0,e.str)`must have required property '${a}'`,params:({params:{missingProperty:a}})=>(0,e._)`{missingProperty: ${a}}`},code(a){const{gen:i,schema:o,schemaCode:c,data:u,$data:l,it:p}=a,{opts:g}=p;if(!l&&o.length===0)return;const _=o.length>=g.loopRequired;if(p.allErrors?h():w(),g.strictRequired){const d=a.parentSchema.properties,{definedProperties:m}=a.it;for(const b of o)if(d?.[b]===void 0&&!m.has(b)){const y=p.schemaEnv.baseId+p.errSchemaPath,$=`required property "${b}" is not defined at "${y}" (strictRequired)`;(0,r.checkStrictMode)(p,$,p.opts.strictRequired)}}function h(){if(_||l)a.block$data(e.nil,f);else for(const d of o)(0,t.checkReportMissingProp)(a,d)}function w(){const d=i.let("missing");if(_||l){const m=i.let("valid",!0);a.block$data(m,()=>v(d,m)),a.ok(m)}else i.if((0,t.checkMissingProp)(a,o,d)),(0,t.reportMissingProp)(a,d),i.else()}function f(){i.forOf("prop",c,d=>{a.setParams({missingProperty:d}),i.if((0,t.noPropertyInData)(i,u,d,g.ownProperties),()=>a.error())})}function v(d,m){a.setParams({missingProperty:d}),i.forOf(d,c,()=>{i.assign(m,(0,t.propertyInData)(i,u,d,g.ownProperties)),i.if((0,e.not)(m),()=>{a.error(),i.break()})},e.nil)}}};return kn.default=s,kn}var $n={},zo;function gf(){if(zo)return $n;zo=1,Object.defineProperty($n,"__esModule",{value:!0});const t=ae(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const a=n==="maxItems"?"more":"fewer";return(0,t.str)`must NOT have ${a} than ${s} items`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:a,schemaCode:i}=n,o=s==="maxItems"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`${a}.length ${o} ${i}`)}};return $n.default=r,$n}var En={},Rn={},Mo;function ea(){if(Mo)return Rn;Mo=1,Object.defineProperty(Rn,"__esModule",{value:!0});const t=fo();return t.code='require("ajv/dist/runtime/equal").default',Rn.default=t,Rn}var qo;function yf(){if(qo)return En;qo=1,Object.defineProperty(En,"__esModule",{value:!0});const t=an(),e=ae(),r=fe(),n=ea(),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i,j:o}})=>(0,e.str)`must NOT have duplicate items (items ## ${o} and ${i} are identical)`,params:({params:{i,j:o}})=>(0,e._)`{i: ${i}, j: ${o}}`},code(i){const{gen:o,data:c,$data:u,schema:l,parentSchema:p,schemaCode:g,it:_}=i;if(!u&&!l)return;const h=o.let("valid"),w=p.items?(0,t.getSchemaTypes)(p.items):[];i.block$data(h,f,(0,e._)`${g} === false`),i.ok(h);function f(){const b=o.let("i",(0,e._)`${c}.length`),y=o.let("j");i.setParams({i:b,j:y}),o.assign(h,!0),o.if((0,e._)`${b} > 1`,()=>(v()?d:m)(b,y))}function v(){return w.length>0&&!w.some(b=>b==="object"||b==="array")}function d(b,y){const $=o.name("item"),E=(0,t.checkDataTypes)(w,$,_.opts.strictNumbers,t.DataType.Wrong),N=o.const("indices",(0,e._)`{}`);o.for((0,e._)`;${b}--;`,()=>{o.let($,(0,e._)`${c}[${b}]`),o.if(E,(0,e._)`continue`),w.length>1&&o.if((0,e._)`typeof ${$} == "string"`,(0,e._)`${$} += "_"`),o.if((0,e._)`typeof ${N}[${$}] == "number"`,()=>{o.assign(y,(0,e._)`${N}[${$}]`),i.error(),o.assign(h,!1).break()}).code((0,e._)`${N}[${$}] = ${b}`)})}function m(b,y){const $=(0,r.useFunc)(o,n.default),E=o.name("outer");o.label(E).for((0,e._)`;${b}--;`,()=>o.for((0,e._)`${y} = ${b}; ${y}--;`,()=>o.if((0,e._)`${$}(${c}[${b}], ${c}[${y}])`,()=>{i.error(),o.assign(h,!1).break(E)})))}}};return En.default=a,En}var Tn={},Zo;function vf(){if(Zo)return Tn;Zo=1,Object.defineProperty(Tn,"__esModule",{value:!0});const t=ae(),e=fe(),r=ea(),s={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:a})=>(0,t._)`{allowedValue: ${a}}`},code(a){const{gen:i,data:o,$data:c,schemaCode:u,schema:l}=a;c||l&&typeof l=="object"?a.fail$data((0,t._)`!${(0,e.useFunc)(i,r.default)}(${o}, ${u})`):a.fail((0,t._)`${l} !== ${o}`)}};return Tn.default=s,Tn}var Pn={},Lo;function wf(){if(Lo)return Pn;Lo=1,Object.defineProperty(Pn,"__esModule",{value:!0});const t=ae(),e=fe(),r=ea(),s={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:a})=>(0,t._)`{allowedValues: ${a}}`},code(a){const{gen:i,data:o,$data:c,schema:u,schemaCode:l,it:p}=a;if(!c&&u.length===0)throw new Error("enum must have non-empty array");const g=u.length>=p.opts.loopEnum;let _;const h=()=>_??(_=(0,e.useFunc)(i,r.default));let w;if(g||c)w=i.let("valid"),a.block$data(w,f);else{if(!Array.isArray(u))throw new Error("ajv implementation error");const d=i.const("vSchema",l);w=(0,t.or)(...u.map((m,b)=>v(d,b)))}a.pass(w);function f(){i.assign(w,!1),i.forOf("v",l,d=>i.if((0,t._)`${h()}(${o}, ${d})`,()=>i.assign(w,!0).break()))}function v(d,m){const b=u[m];return typeof b=="object"&&b!==null?(0,t._)`${h()}(${o}, ${d}[${m}])`:(0,t._)`${o} === ${b}`}}};return Pn.default=s,Pn}var Do;function bf(){if(Do)return _n;Do=1,Object.defineProperty(_n,"__esModule",{value:!0});const t=lf(),e=df(),r=hf(),n=pf(),s=mf(),a=_f(),i=gf(),o=yf(),c=vf(),u=wf(),l=[t.default,e.default,r.default,n.default,s.default,a.default,i.default,o.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,u.default];return _n.default=l,_n}var Cn={},Xt={},xo;function Uo(){if(xo)return Xt;xo=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.validateAdditionalItems=void 0;const t=ae(),e=fe(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,t.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,t._)`{limit: ${a}}`},code(a){const{parentSchema:i,it:o}=a,{items:c}=i;if(!Array.isArray(c)){(0,e.checkStrictMode)(o,'"additionalItems" is ignored when "items" is not an array of schemas');return}s(a,c)}};function s(a,i){const{gen:o,schema:c,data:u,keyword:l,it:p}=a;p.items=!0;const g=o.const("len",(0,t._)`${u}.length`);if(c===!1)a.setParams({len:i.length}),a.pass((0,t._)`${g} <= ${i.length}`);else if(typeof c=="object"&&!(0,e.alwaysValidSchema)(p,c)){const h=o.var("valid",(0,t._)`${g} <= ${i.length}`);o.if((0,t.not)(h),()=>_(h)),a.ok(h)}function _(h){o.forRange("i",i.length,g,w=>{a.subschema({keyword:l,dataProp:w,dataPropType:e.Type.Num},h),p.allErrors||o.if((0,t.not)(h),()=>o.break())})}}return Xt.validateAdditionalItems=s,Xt.default=n,Xt}var In={},er={},Vo;function Fo(){if(Vo)return er;Vo=1,Object.defineProperty(er,"__esModule",{value:!0}),er.validateTuple=void 0;const t=ae(),e=fe(),r=ut(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(a){const{schema:i,it:o}=a;if(Array.isArray(i))return s(a,"additionalItems",i);o.items=!0,!(0,e.alwaysValidSchema)(o,i)&&a.ok((0,r.validateArray)(a))}};function s(a,i,o=a.schema){const{gen:c,parentSchema:u,data:l,keyword:p,it:g}=a;w(u),g.opts.unevaluated&&o.length&&g.items!==!0&&(g.items=e.mergeEvaluated.items(c,o.length,g.items));const _=c.name("valid"),h=c.const("len",(0,t._)`${l}.length`);o.forEach((f,v)=>{(0,e.alwaysValidSchema)(g,f)||(c.if((0,t._)`${h} > ${v}`,()=>a.subschema({keyword:p,schemaProp:v,dataProp:v},_)),a.ok(_))});function w(f){const{opts:v,errSchemaPath:d}=g,m=o.length,b=m===f.minItems&&(m===f.maxItems||f[i]===!1);if(v.strictTuples&&!b){const y=`"${p}" is ${m}-tuple, but minItems or maxItems/${i} are not specified or different at path "${d}"`;(0,e.checkStrictMode)(g,y,v.strictTuples)}}}return er.validateTuple=s,er.default=n,er}var Ho;function Sf(){if(Ho)return In;Ho=1,Object.defineProperty(In,"__esModule",{value:!0});const t=Fo(),e={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,t.validateTuple)(r,"items")};return In.default=e,In}var On={},Wo;function kf(){if(Wo)return On;Wo=1,Object.defineProperty(On,"__esModule",{value:!0});const t=ae(),e=fe(),r=ut(),n=Uo(),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:i}})=>(0,t.str)`must NOT have more than ${i} items`,params:({params:{len:i}})=>(0,t._)`{limit: ${i}}`},code(i){const{schema:o,parentSchema:c,it:u}=i,{prefixItems:l}=c;u.items=!0,!(0,e.alwaysValidSchema)(u,o)&&(l?(0,n.validateAdditionalItems)(i,l):i.ok((0,r.validateArray)(i)))}};return On.default=a,On}var Nn={},Ko;function $f(){if(Ko)return Nn;Ko=1,Object.defineProperty(Nn,"__esModule",{value:!0});const t=ae(),e=fe(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:s,max:a}})=>a===void 0?(0,t.str)`must contain at least ${s} valid item(s)`:(0,t.str)`must contain at least ${s} and no more than ${a} valid item(s)`,params:({params:{min:s,max:a}})=>a===void 0?(0,t._)`{minContains: ${s}}`:(0,t._)`{minContains: ${s}, maxContains: ${a}}`},code(s){const{gen:a,schema:i,parentSchema:o,data:c,it:u}=s;let l,p;const{minContains:g,maxContains:_}=o;u.opts.next?(l=g===void 0?1:g,p=_):l=1;const h=a.const("len",(0,t._)`${c}.length`);if(s.setParams({min:l,max:p}),p===void 0&&l===0){(0,e.checkStrictMode)(u,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(p!==void 0&&l>p){(0,e.checkStrictMode)(u,'"minContains" > "maxContains" is always invalid'),s.fail();return}if((0,e.alwaysValidSchema)(u,i)){let m=(0,t._)`${h} >= ${l}`;p!==void 0&&(m=(0,t._)`${m} && ${h} <= ${p}`),s.pass(m);return}u.items=!0;const w=a.name("valid");p===void 0&&l===1?v(w,()=>a.if(w,()=>a.break())):l===0?(a.let(w,!0),p!==void 0&&a.if((0,t._)`${c}.length > 0`,f)):(a.let(w,!1),f()),s.result(w,()=>s.reset());function f(){const m=a.name("_valid"),b=a.let("count",0);v(m,()=>a.if(m,()=>d(b)))}function v(m,b){a.forRange("i",0,h,y=>{s.subschema({keyword:"contains",dataProp:y,dataPropType:e.Type.Num,compositeRule:!0},m),b()})}function d(m){a.code((0,t._)`${m}++`),p===void 0?a.if((0,t._)`${m} >= ${l}`,()=>a.assign(w,!0).break()):(a.if((0,t._)`${m} > ${p}`,()=>a.assign(w,!1).break()),l===1?a.assign(w,!0):a.if((0,t._)`${m} >= ${l}`,()=>a.assign(w,!0)))}}};return Nn.default=n,Nn}var ta={},Jo;function Ef(){return Jo||(Jo=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=ae(),r=fe(),n=ut();t.error={message:({params:{property:c,depsCount:u,deps:l}})=>{const p=u===1?"property":"properties";return(0,e.str)`must have ${p} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:p}})=>(0,e._)`{property: ${c},
6
+ missingProperty: ${p},
7
+ depsCount: ${u},
8
+ deps: ${l}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(c){const[u,l]=a(c);i(c,u),o(c,l)}};function a({schema:c}){const u={},l={};for(const p in c){if(p==="__proto__")continue;const g=Array.isArray(c[p])?u:l;g[p]=c[p]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:p,it:g}=c;if(Object.keys(u).length===0)return;const _=l.let("missing");for(const h in u){const w=u[h];if(w.length===0)continue;const f=(0,n.propertyInData)(l,p,h,g.opts.ownProperties);c.setParams({property:h,depsCount:w.length,deps:w.join(", ")}),g.allErrors?l.if(f,()=>{for(const v of w)(0,n.checkReportMissingProp)(c,v)}):(l.if((0,e._)`${f} && (${(0,n.checkMissingProp)(c,w,_)})`),(0,n.reportMissingProp)(c,_),l.else())}}t.validatePropertyDeps=i;function o(c,u=c.schema){const{gen:l,data:p,keyword:g,it:_}=c,h=l.name("valid");for(const w in u)(0,r.alwaysValidSchema)(_,u[w])||(l.if((0,n.propertyInData)(l,p,w,_.opts.ownProperties),()=>{const f=c.subschema({keyword:g,schemaProp:w},h);c.mergeValidEvaluated(f,h)},()=>l.var(h,!0)),c.ok(h))}t.validateSchemaDeps=o,t.default=s})(ta)),ta}var An={},Go;function Rf(){if(Go)return An;Go=1,Object.defineProperty(An,"__esModule",{value:!0});const t=ae(),e=fe(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:s})=>(0,t._)`{propertyName: ${s.propertyName}}`},code(s){const{gen:a,schema:i,data:o,it:c}=s;if((0,e.alwaysValidSchema)(c,i))return;const u=a.name("valid");a.forIn("key",o,l=>{s.setParams({propertyName:l}),s.subschema({keyword:"propertyNames",data:l,dataTypes:["string"],propertyName:l,compositeRule:!0},u),a.if((0,t.not)(u),()=>{s.error(!0),c.allErrors||a.break()})}),s.ok(u)}};return An.default=n,An}var jn={},Bo;function Yo(){if(Bo)return jn;Bo=1,Object.defineProperty(jn,"__esModule",{value:!0});const t=ut(),e=ae(),r=Et(),n=fe(),a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:i})=>(0,e._)`{additionalProperty: ${i.additionalProperty}}`},code(i){const{gen:o,schema:c,parentSchema:u,data:l,errsCount:p,it:g}=i;if(!p)throw new Error("ajv implementation error");const{allErrors:_,opts:h}=g;if(g.props=!0,h.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(g,c))return;const w=(0,t.allSchemaProperties)(u.properties),f=(0,t.allSchemaProperties)(u.patternProperties);v(),i.ok((0,e._)`${p} === ${r.default.errors}`);function v(){o.forIn("key",l,$=>{!w.length&&!f.length?b($):o.if(d($),()=>b($))})}function d($){let E;if(w.length>8){const N=(0,n.schemaRefOrVal)(g,u.properties,"properties");E=(0,t.isOwnProperty)(o,N,$)}else w.length?E=(0,e.or)(...w.map(N=>(0,e._)`${$} === ${N}`)):E=e.nil;return f.length&&(E=(0,e.or)(E,...f.map(N=>(0,e._)`${(0,t.usePattern)(i,N)}.test(${$})`))),(0,e.not)(E)}function m($){o.code((0,e._)`delete ${l}[${$}]`)}function b($){if(h.removeAdditional==="all"||h.removeAdditional&&c===!1){m($);return}if(c===!1){i.setParams({additionalProperty:$}),i.error(),_||o.break();return}if(typeof c=="object"&&!(0,n.alwaysValidSchema)(g,c)){const E=o.name("valid");h.removeAdditional==="failing"?(y($,E,!1),o.if((0,e.not)(E),()=>{i.reset(),m($)})):(y($,E),_||o.if((0,e.not)(E),()=>o.break()))}}function y($,E,N){const L={keyword:"additionalProperties",dataProp:$,dataPropType:n.Type.Str};N===!1&&Object.assign(L,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(L,E)}}};return jn.default=a,jn}var zn={},Qo;function Tf(){if(Qo)return zn;Qo=1,Object.defineProperty(zn,"__esModule",{value:!0});const t=cn(),e=ut(),r=fe(),n=Yo(),s={keyword:"properties",type:"object",schemaType:"object",code(a){const{gen:i,schema:o,parentSchema:c,data:u,it:l}=a;l.opts.removeAdditional==="all"&&c.additionalProperties===void 0&&n.default.code(new t.KeywordCxt(l,n.default,"additionalProperties"));const p=(0,e.allSchemaProperties)(o);for(const f of p)l.definedProperties.add(f);l.opts.unevaluated&&p.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(i,(0,r.toHash)(p),l.props));const g=p.filter(f=>!(0,r.alwaysValidSchema)(l,o[f]));if(g.length===0)return;const _=i.name("valid");for(const f of g)h(f)?w(f):(i.if((0,e.propertyInData)(i,u,f,l.opts.ownProperties)),w(f),l.allErrors||i.else().var(_,!0),i.endIf()),a.it.definedProperties.add(f),a.ok(_);function h(f){return l.opts.useDefaults&&!l.compositeRule&&o[f].default!==void 0}function w(f){a.subschema({keyword:"properties",schemaProp:f,dataProp:f},_)}}};return zn.default=s,zn}var Mn={},Xo;function Pf(){if(Xo)return Mn;Xo=1,Object.defineProperty(Mn,"__esModule",{value:!0});const t=ut(),e=ae(),r=fe(),n=fe(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(a){const{gen:i,schema:o,data:c,parentSchema:u,it:l}=a,{opts:p}=l,g=(0,t.allSchemaProperties)(o),_=g.filter(b=>(0,r.alwaysValidSchema)(l,o[b]));if(g.length===0||_.length===g.length&&(!l.opts.unevaluated||l.props===!0))return;const h=p.strictSchema&&!p.allowMatchingProperties&&u.properties,w=i.name("valid");l.props!==!0&&!(l.props instanceof e.Name)&&(l.props=(0,n.evaluatedPropsToName)(i,l.props));const{props:f}=l;v();function v(){for(const b of g)h&&d(b),l.allErrors?m(b):(i.var(w,!0),m(b),i.if(w))}function d(b){for(const y in h)new RegExp(b).test(y)&&(0,r.checkStrictMode)(l,`property ${y} matches pattern ${b} (use allowMatchingProperties)`)}function m(b){i.forIn("key",c,y=>{i.if((0,e._)`${(0,t.usePattern)(a,b)}.test(${y})`,()=>{const $=_.includes(b);$||a.subschema({keyword:"patternProperties",schemaProp:b,dataProp:y,dataPropType:n.Type.Str},w),l.opts.unevaluated&&f!==!0?i.assign((0,e._)`${f}[${y}]`,!0):!$&&!l.allErrors&&i.if((0,e.not)(w),()=>i.break())})})}}};return Mn.default=s,Mn}var qn={},ec;function Cf(){if(ec)return qn;ec=1,Object.defineProperty(qn,"__esModule",{value:!0});const t=fe(),e={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:s,it:a}=r;if((0,t.alwaysValidSchema)(a,s)){r.fail();return}const i=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return qn.default=e,qn}var Zn={},tc;function If(){if(tc)return Zn;tc=1,Object.defineProperty(Zn,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ut().validateUnion,error:{message:"must match a schema in anyOf"}};return Zn.default=e,Zn}var Ln={},rc;function Of(){if(rc)return Ln;rc=1,Object.defineProperty(Ln,"__esModule",{value:!0});const t=ae(),e=fe(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:s})=>(0,t._)`{passingSchemas: ${s.passing}}`},code(s){const{gen:a,schema:i,parentSchema:o,it:c}=s;if(!Array.isArray(i))throw new Error("ajv implementation error");if(c.opts.discriminator&&o.discriminator)return;const u=i,l=a.let("valid",!1),p=a.let("passing",null),g=a.name("_valid");s.setParams({passing:p}),a.block(_),s.result(l,()=>s.reset(),()=>s.error(!0));function _(){u.forEach((h,w)=>{let f;(0,e.alwaysValidSchema)(c,h)?a.var(g,!0):f=s.subschema({keyword:"oneOf",schemaProp:w,compositeRule:!0},g),w>0&&a.if((0,t._)`${g} && ${l}`).assign(l,!1).assign(p,(0,t._)`[${p}, ${w}]`).else(),a.if(g,()=>{a.assign(l,!0),a.assign(p,w),f&&s.mergeEvaluated(f,t.Name)})})}}};return Ln.default=n,Ln}var Dn={},nc;function Nf(){if(nc)return Dn;nc=1,Object.defineProperty(Dn,"__esModule",{value:!0});const t=fe(),e={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:s,it:a}=r;if(!Array.isArray(s))throw new Error("ajv implementation error");const i=n.name("valid");s.forEach((o,c)=>{if((0,t.alwaysValidSchema)(a,o))return;const u=r.subschema({keyword:"allOf",schemaProp:c},i);r.ok(i),r.mergeEvaluated(u)})}};return Dn.default=e,Dn}var xn={},sc;function Af(){if(sc)return xn;sc=1,Object.defineProperty(xn,"__esModule",{value:!0});const t=ae(),e=fe(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:a})=>(0,t.str)`must match "${a.ifClause}" schema`,params:({params:a})=>(0,t._)`{failingKeyword: ${a.ifClause}}`},code(a){const{gen:i,parentSchema:o,it:c}=a;o.then===void 0&&o.else===void 0&&(0,e.checkStrictMode)(c,'"if" without "then" and "else" is ignored');const u=s(c,"then"),l=s(c,"else");if(!u&&!l)return;const p=i.let("valid",!0),g=i.name("_valid");if(_(),a.reset(),u&&l){const w=i.let("ifClause");a.setParams({ifClause:w}),i.if(g,h("then",w),h("else",w))}else u?i.if(g,h("then")):i.if((0,t.not)(g),h("else"));a.pass(p,()=>a.error(!0));function _(){const w=a.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},g);a.mergeEvaluated(w)}function h(w,f){return()=>{const v=a.subschema({keyword:w},g);i.assign(p,g),a.mergeValidEvaluated(v,p),f?i.assign(f,(0,t._)`${w}`):a.setParams({ifClause:w})}}}};function s(a,i){const o=a.schema[i];return o!==void 0&&!(0,e.alwaysValidSchema)(a,o)}return xn.default=n,xn}var Un={},ac;function jf(){if(ac)return Un;ac=1,Object.defineProperty(Un,"__esModule",{value:!0});const t=fe(),e={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:s}){n.if===void 0&&(0,t.checkStrictMode)(s,`"${r}" without "if" is ignored`)}};return Un.default=e,Un}var ic;function zf(){if(ic)return Cn;ic=1,Object.defineProperty(Cn,"__esModule",{value:!0});const t=Uo(),e=Sf(),r=Fo(),n=kf(),s=$f(),a=Ef(),i=Rf(),o=Yo(),c=Tf(),u=Pf(),l=Cf(),p=If(),g=Of(),_=Nf(),h=Af(),w=jf();function f(v=!1){const d=[l.default,p.default,g.default,_.default,h.default,w.default,i.default,o.default,a.default,c.default,u.default];return v?d.push(e.default,n.default):d.push(t.default,r.default),d.push(s.default),d}return Cn.default=f,Cn}var Vn={},Fn={},oc;function Mf(){if(oc)return Fn;oc=1,Object.defineProperty(Fn,"__esModule",{value:!0});const t=ae(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,t._)`{format: ${n}}`},code(n,s){const{gen:a,data:i,$data:o,schema:c,schemaCode:u,it:l}=n,{opts:p,errSchemaPath:g,schemaEnv:_,self:h}=l;if(!p.validateFormats)return;o?w():f();function w(){const v=a.scopeValue("formats",{ref:h.formats,code:p.code.formats}),d=a.const("fDef",(0,t._)`${v}[${u}]`),m=a.let("fType"),b=a.let("format");a.if((0,t._)`typeof ${d} == "object" && !(${d} instanceof RegExp)`,()=>a.assign(m,(0,t._)`${d}.type || "string"`).assign(b,(0,t._)`${d}.validate`),()=>a.assign(m,(0,t._)`"string"`).assign(b,d)),n.fail$data((0,t.or)(y(),$()));function y(){return p.strictSchema===!1?t.nil:(0,t._)`${u} && !${b}`}function $(){const E=_.$async?(0,t._)`(${d}.async ? await ${b}(${i}) : ${b}(${i}))`:(0,t._)`${b}(${i})`,N=(0,t._)`(typeof ${b} == "function" ? ${E} : ${b}.test(${i}))`;return(0,t._)`${b} && ${b} !== true && ${m} === ${s} && !${N}`}}function f(){const v=h.formats[c];if(!v){y();return}if(v===!0)return;const[d,m,b]=$(v);d===s&&n.pass(E());function y(){if(p.strictSchema===!1){h.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${c}" ignored in schema at path "${g}"`}}function $(N){const L=N instanceof RegExp?(0,t.regexpCode)(N):p.code.formats?(0,t._)`${p.code.formats}${(0,t.getProperty)(c)}`:void 0,K=a.scopeValue("formats",{key:c,ref:N,code:L});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,t._)`${K}.validate`]:["string",N,K]}function E(){if(typeof v=="object"&&!(v instanceof RegExp)&&v.async){if(!_.$async)throw new Error("async format in sync schema");return(0,t._)`await ${b}(${i})`}return typeof m=="function"?(0,t._)`${b}(${i})`:(0,t._)`${b}.test(${i})`}}}};return Fn.default=r,Fn}var cc;function qf(){if(cc)return Vn;cc=1,Object.defineProperty(Vn,"__esModule",{value:!0});const e=[Mf().default];return Vn.default=e,Vn}var Dt={},uc;function Zf(){return uc||(uc=1,Object.defineProperty(Dt,"__esModule",{value:!0}),Dt.contentVocabulary=Dt.metadataVocabulary=void 0,Dt.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Dt.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Dt}var lc;function Lf(){if(lc)return hn;lc=1,Object.defineProperty(hn,"__esModule",{value:!0});const t=uf(),e=bf(),r=zf(),n=qf(),s=Zf(),a=[t.default,e.default,(0,r.default)(),n.default,s.metadataVocabulary,s.contentVocabulary];return hn.default=a,hn}var Hn={},$r={},dc;function Df(){if(dc)return $r;dc=1,Object.defineProperty($r,"__esModule",{value:!0}),$r.DiscrError=void 0;var t;return(function(e){e.Tag="tag",e.Mapping="mapping"})(t||($r.DiscrError=t={})),$r}var fc;function xf(){if(fc)return Hn;fc=1,Object.defineProperty(Hn,"__esModule",{value:!0});const t=ae(),e=Df(),r=Ys(),n=dn(),s=fe(),i={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:o,tagName:c}})=>o===e.DiscrError.Tag?`tag "${c}" must be string`:`value of tag "${c}" must be in oneOf`,params:({params:{discrError:o,tag:c,tagName:u}})=>(0,t._)`{error: ${o}, tag: ${u}, tagValue: ${c}}`},code(o){const{gen:c,data:u,schema:l,parentSchema:p,it:g}=o,{oneOf:_}=p;if(!g.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=l.propertyName;if(typeof h!="string")throw new Error("discriminator: requires propertyName");if(l.mapping)throw new Error("discriminator: mapping is not supported");if(!_)throw new Error("discriminator: requires oneOf keyword");const w=c.let("valid",!1),f=c.const("tag",(0,t._)`${u}${(0,t.getProperty)(h)}`);c.if((0,t._)`typeof ${f} == "string"`,()=>v(),()=>o.error(!1,{discrError:e.DiscrError.Tag,tag:f,tagName:h})),o.ok(w);function v(){const b=m();c.if(!1);for(const y in b)c.elseIf((0,t._)`${f} === ${y}`),c.assign(w,d(b[y]));c.else(),o.error(!1,{discrError:e.DiscrError.Mapping,tag:f,tagName:h}),c.endIf()}function d(b){const y=c.name("valid"),$=o.subschema({keyword:"oneOf",schemaProp:b},y);return o.mergeEvaluated($,t.Name),y}function m(){var b;const y={},$=N(p);let E=!0;for(let z=0;z<_.length;z++){let F=_[z];if(F?.$ref&&!(0,s.schemaHasRulesButRef)(F,g.self.RULES)){const Y=F.$ref;if(F=r.resolveRef.call(g.self,g.schemaEnv.root,g.baseId,Y),F instanceof r.SchemaEnv&&(F=F.schema),F===void 0)throw new n.default(g.opts.uriResolver,g.baseId,Y)}const G=(b=F?.properties)===null||b===void 0?void 0:b[h];if(typeof G!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);E=E&&($||N(F)),L(G,z)}if(!E)throw new Error(`discriminator: "${h}" must be required`);return y;function N({required:z}){return Array.isArray(z)&&z.includes(h)}function L(z,F){if(z.const)K(z.const,F);else if(z.enum)for(const G of z.enum)K(G,F);else throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`)}function K(z,F){if(typeof z!="string"||z in y)throw new Error(`discriminator: "${h}" values must be unique strings`);y[z]=F}}}};return Hn.default=i,Hn}const Uf={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};var hc;function pc(){return hc||(hc=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const r=af(),n=Lf(),s=xf(),a=Uf,i=["/properties"],o="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(h=>this.addVocabulary(h)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const h=this.opts.$data?this.$dataMetaSchema(a,i):a;this.addMetaSchema(h,o,!1),this.refs["http://json-schema.org/schema"]=o}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(o)?o:void 0)}}e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var u=cn();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=ae();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var p=Bs();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return p.default}});var g=dn();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return g.default}})})(tn,tn.exports)),tn.exports}var Vf=pc();const mc=Qt(Vf),Ff=Object.freeze({status:"aborted"});function A(t,e,r){function n(o,c){var u;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(u=o._zod).traits??(u.traits=new Set),o._zod.traits.add(t),e(o,c);for(const l in i.prototype)l in o||Object.defineProperty(o,l,{value:i.prototype[l].bind(o)});o._zod.constr=i,o._zod.def=c}const s=r?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:t});function i(o){var c;const u=r?.Parent?new a:this;n(u,o),(c=u._zod).deferred??(c.deferred=[]);for(const l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>r?.Parent&&o instanceof r.Parent?!0:o?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}class Er extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const _c={};function Tt(t){return _c}function gc(t){const e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function Hf(t,e){return typeof e=="bigint"?e.toString():e}function ra(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function na(t){return t==null}function sa(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Wf(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,a=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}function Se(t,e,r){Object.defineProperty(t,e,{get(){{const n=r();return t[e]=n,n}},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function Rr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Tr(t){return JSON.stringify(t)}const yc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Wn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Kf=ra(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Kn(t){if(Wn(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(Wn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const Jf=new Set(["string","number","symbol"]);function Pr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pt(t,e,r){const n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function Q(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Gf(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const Bf={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Yf(t,e){const r={},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return Pt(t,{...t._zod.def,shape:r,checks:[]})}function Qf(t,e){const r={...t._zod.def.shape},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return Pt(t,{...t._zod.def,shape:r,checks:[]})}function Xf(t,e){if(!Kn(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const n={...t._zod.def.shape,...e};return Rr(this,"shape",n),n},checks:[]};return Pt(t,r)}function eh(t,e){return Pt(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return Rr(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function th(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const a in r){if(!(a in n))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(s[a]=t?new t({type:"optional",innerType:n[a]}):n[a])}else for(const a in n)s[a]=t?new t({type:"optional",innerType:n[a]}):n[a];return Pt(e,{...e._zod.def,shape:s,checks:[]})}function rh(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const a in r){if(!(a in s))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(s[a]=new t({type:"nonoptional",innerType:n[a]}))}else for(const a in n)s[a]=new t({type:"nonoptional",innerType:n[a]});return Pt(e,{...e._zod.def,shape:s,checks:[]})}function Cr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function xt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Jn(t){return typeof t=="string"?t:t?.message}function Ct(t,e,r){const n={...t,path:t.path??[]};if(!t.message){const s=Jn(t.inst?._zod.def?.error?.(t))??Jn(e?.error?.(t))??Jn(r.customError?.(t))??Jn(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function aa(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ir(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const vc=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Hf,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},wc=A("$ZodError",vc),Gn=A("$ZodError",vc,{Parent:Error});function nh(t,e=r=>r.message){const r={},n=[];for(const s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function sh(t,e){const r=e||function(a){return a.message},n={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(o=>s({issues:o}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(t),n}const bc=t=>(e,r,n,s)=>{const a=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Er;if(i.issues.length){const o=new(s?.Err??t)(i.issues.map(c=>Ct(c,a,Tt())));throw yc(o,s?.callee),o}return i.value},ah=bc(Gn),Sc=t=>async(e,r,n,s)=>{const a=n?Object.assign(n,{async:!0}):{async:!0};let i=e._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const o=new(s?.Err??t)(i.issues.map(c=>Ct(c,a,Tt())));throw yc(o,s?.callee),o}return i.value},ih=Sc(Gn),kc=t=>(e,r,n)=>{const s=n?{...n,async:!1}:{async:!1},a=e._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Er;return a.issues.length?{success:!1,error:new(t??wc)(a.issues.map(i=>Ct(i,s,Tt())))}:{success:!0,data:a.value}},ia=kc(Gn),$c=t=>async(e,r,n)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=e._zod.run({value:r,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(i=>Ct(i,s,Tt())))}:{success:!0,data:a.value}},oa=$c(Gn),oh=/^[cC][^\s-]{8,}$/,ch=/^[0-9a-z]+$/,uh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lh=/^[0-9a-vA-V]{20}$/,dh=/^[A-Za-z0-9]{27}$/,fh=/^[a-zA-Z0-9_-]{21}$/,hh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ph=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ec=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,mh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_h="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function gh(){return new RegExp(_h,"u")}const yh=/^(?:(?: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])$/,vh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,wh=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Sh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Rc=/^[A-Za-z0-9_-]*$/,kh=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,$h=/^\+(?:[0-9]){6,14}[0-9]$/,Tc="(?:(?:\\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])))",Eh=new RegExp(`^${Tc}$`);function Pc(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Rh(t){return new RegExp(`^${Pc(t)}$`)}function Th(t){const e=Pc({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Tc}T(?:${n})$`)}const Ph=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Ch=/^\d+$/,Ih=/^-?\d+(?:\.\d+)?/i,Oh=/true|false/i,Nh=/null/i,Ah=/^[^A-Z]*$/,jh=/^[^a-z]*$/,Je=A("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Cc={number:"number",bigint:"bigint",object:"date"},Ic=A("$ZodCheckLessThan",(t,e)=>{Je.init(t,e);const r=Cc[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,a=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<a&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Oc=A("$ZodCheckGreaterThan",(t,e)=>{Je.init(t,e);const r=Cc[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,a=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),zh=A("$ZodCheckMultipleOf",(t,e)=>{Je.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Wf(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Mh=A("$ZodCheckNumberFormat",(t,e)=>{Je.init(t,e),e.format=e.format||"float64";const r=e.format?.includes("int"),n=r?"int":"number",[s,a]=Bf[e.format];t._zod.onattach.push(i=>{const o=i._zod.bag;o.format=e.format,o.minimum=s,o.maximum=a,r&&(o.pattern=Ch)}),t._zod.check=i=>{const o=i.value;if(r){if(!Number.isInteger(o)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:o,inst:t});return}if(!Number.isSafeInteger(o)){o>0?i.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}o<s&&i.issues.push({origin:"number",input:o,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),o>a&&i.issues.push({origin:"number",input:o,code:"too_big",maximum:a,inst:t})}}),qh=A("$ZodCheckMaxLength",(t,e)=>{var r;Je.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!na(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{const s=n.value;if(s.length<=e.maximum)return;const i=aa(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Zh=A("$ZodCheckMinLength",(t,e)=>{var r;Je.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!na(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{const s=n.value;if(s.length>=e.minimum)return;const i=aa(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Lh=A("$ZodCheckLengthEquals",(t,e)=>{var r;Je.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!na(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{const s=n.value,a=s.length;if(a===e.length)return;const i=aa(s),o=a>e.length;n.issues.push({origin:i,...o?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Bn=A("$ZodCheckStringFormat",(t,e)=>{var r,n;Je.init(t,e),t._zod.onattach.push(s=>{const a=s._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Dh=A("$ZodCheckRegex",(t,e)=>{Bn.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),xh=A("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ah),Bn.init(t,e)}),Uh=A("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=jh),Bn.init(t,e)}),Vh=A("$ZodCheckIncludes",(t,e)=>{Je.init(t,e);const r=Pr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),Fh=A("$ZodCheckStartsWith",(t,e)=>{Je.init(t,e);const r=new RegExp(`^${Pr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Hh=A("$ZodCheckEndsWith",(t,e)=>{Je.init(t,e);const r=new RegExp(`.*${Pr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Wh=A("$ZodCheckOverwrite",(t,e)=>{Je.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class Kh{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const n=e.split(`
9
+ `).filter(i=>i),s=Math.min(...n.map(i=>i.length-i.trimStart().length)),a=n.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const e=Function,r=this?.args,s=[...(this?.content??[""]).map(a=>` ${a}`)];return new e(...r,s.join(`
10
+ `))}}const Jh={major:4,minor:0,patch:0},be=A("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Jh;const n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(const s of n)for(const a of s._zod.onattach)a(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(a,i,o)=>{let c=Cr(a),u;for(const l of i){if(l._zod.def.when){if(!l._zod.def.when(a))continue}else if(c)continue;const p=a.issues.length,g=l._zod.check(a);if(g instanceof Promise&&o?.async===!1)throw new Er;if(u||g instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await g,a.issues.length!==p&&(c||(c=Cr(a,p)))});else{if(a.issues.length===p)continue;c||(c=Cr(a,p))}}return u?u.then(()=>a):a};t._zod.run=(a,i)=>{const o=t._zod.parse(a,i);if(o instanceof Promise){if(i.async===!1)throw new Er;return o.then(c=>s(c,n,i))}return s(o,n,i)}}t["~standard"]={validate:s=>{try{const a=ia(t,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return oa(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ca=A("$ZodString",(t,e)=>{be.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ph(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Ee=A("$ZodStringFormat",(t,e)=>{Bn.init(t,e),ca.init(t,e)}),Gh=A("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=ph),Ee.init(t,e)}),Bh=A("$ZodUUID",(t,e)=>{if(e.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Ec(n))}else e.pattern??(e.pattern=Ec());Ee.init(t,e)}),Yh=A("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=mh),Ee.init(t,e)}),Qh=A("$ZodURL",(t,e)=>{Ee.init(t,e),t._zod.check=r=>{try{const n=r.value,s=new URL(n),a=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:kh.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&a.endsWith("/")?r.value=a.slice(0,-1):r.value=a;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Xh=A("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=gh()),Ee.init(t,e)}),ep=A("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=fh),Ee.init(t,e)}),tp=A("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=oh),Ee.init(t,e)}),rp=A("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ch),Ee.init(t,e)}),np=A("$ZodULID",(t,e)=>{e.pattern??(e.pattern=uh),Ee.init(t,e)}),sp=A("$ZodXID",(t,e)=>{e.pattern??(e.pattern=lh),Ee.init(t,e)}),ap=A("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=dh),Ee.init(t,e)}),ip=A("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Th(e)),Ee.init(t,e)}),op=A("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Eh),Ee.init(t,e)}),cp=A("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Rh(e)),Ee.init(t,e)}),up=A("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=hh),Ee.init(t,e)}),lp=A("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=yh),Ee.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),dp=A("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=vh),Ee.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),fp=A("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=wh),Ee.init(t,e)}),hp=A("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=bh),Ee.init(t,e),t._zod.check=r=>{const[n,s]=r.value.split("/");try{if(!s)throw new Error;const a=Number(s);if(`${a}`!==s)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Nc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const pp=A("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Sh),Ee.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Nc(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function mp(t){if(!Rc.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Nc(r)}const _p=A("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Rc),Ee.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{mp(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),gp=A("$ZodE164",(t,e)=>{e.pattern??(e.pattern=$h),Ee.init(t,e)});function yp(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const s=JSON.parse(atob(n));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const vp=A("$ZodJWT",(t,e)=>{Ee.init(t,e),t._zod.check=r=>{yp(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ac=A("$ZodNumber",(t,e)=>{be.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ih,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;const a=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...a?{received:a}:{}}),r}}),wp=A("$ZodNumber",(t,e)=>{Mh.init(t,e),Ac.init(t,e)}),bp=A("$ZodBoolean",(t,e)=>{be.init(t,e),t._zod.pattern=Oh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}const s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}}),Sp=A("$ZodNull",(t,e)=>{be.init(t,e),t._zod.pattern=Nh,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{const s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}}),kp=A("$ZodAny",(t,e)=>{be.init(t,e),t._zod.parse=r=>r}),$p=A("$ZodUnknown",(t,e)=>{be.init(t,e),t._zod.parse=r=>r}),Ep=A("$ZodNever",(t,e)=>{be.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function jc(t,e,r){t.issues.length&&e.issues.push(...xt(r,t.issues)),e.value[r]=t.value}const Rp=A("$ZodArray",(t,e)=>{be.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);const a=[];for(let i=0;i<s.length;i++){const o=s[i],c=e.element._zod.run({value:o,issues:[]},n);c instanceof Promise?a.push(c.then(u=>jc(u,r,i))):jc(c,r,i)}return a.length?Promise.all(a).then(()=>r):r}});function Yn(t,e,r){t.issues.length&&e.issues.push(...xt(r,t.issues)),e.value[r]=t.value}function zc(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...xt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}const Mc=A("$ZodObject",(t,e)=>{be.init(t,e);const r=ra(()=>{const p=Object.keys(e.shape);for(const _ of p)if(!(e.shape[_]instanceof be))throw new Error(`Invalid element at key "${_}": expected a Zod schema`);const g=Gf(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(g)}});Se(t._zod,"propValues",()=>{const p=e.shape,g={};for(const _ in p){const h=p[_]._zod;if(h.values){g[_]??(g[_]=new Set);for(const w of h.values)g[_].add(w)}}return g});const n=p=>{const g=new Kh(["shape","payload","ctx"]),_=r.value,h=d=>{const m=Tr(d);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};g.write("const input = payload.value;");const w=Object.create(null);let f=0;for(const d of _.keys)w[d]=`key_${f++}`;g.write("const newResult = {}");for(const d of _.keys)if(_.optionalKeys.has(d)){const m=w[d];g.write(`const ${m} = ${h(d)};`);const b=Tr(d);g.write(`
11
+ if (${m}.issues.length) {
12
+ if (input[${b}] === undefined) {
13
+ if (${b} in input) {
14
+ newResult[${b}] = undefined;
15
+ }
16
+ } else {
17
+ payload.issues = payload.issues.concat(
18
+ ${m}.issues.map((iss) => ({
19
+ ...iss,
20
+ path: iss.path ? [${b}, ...iss.path] : [${b}],
21
+ }))
22
+ );
23
+ }
24
+ } else if (${m}.value === undefined) {
25
+ if (${b} in input) newResult[${b}] = undefined;
26
+ } else {
27
+ newResult[${b}] = ${m}.value;
28
+ }
29
+ `)}else{const m=w[d];g.write(`const ${m} = ${h(d)};`),g.write(`
30
+ if (${m}.issues.length) payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
31
+ ...iss,
32
+ path: iss.path ? [${Tr(d)}, ...iss.path] : [${Tr(d)}]
33
+ })));`),g.write(`newResult[${Tr(d)}] = ${m}.value`)}g.write("payload.value = newResult;"),g.write("return payload;");const v=g.compile();return(d,m)=>v(p,d,m)};let s;const a=Wn,i=!_c.jitless,c=i&&Kf.value,u=e.catchall;let l;t._zod.parse=(p,g)=>{l??(l=r.value);const _=p.value;if(!a(_))return p.issues.push({expected:"object",code:"invalid_type",input:_,inst:t}),p;const h=[];if(i&&c&&g?.async===!1&&g.jitless!==!0)s||(s=n(e.shape)),p=s(p,g);else{p.value={};const m=l.shape;for(const b of l.keys){const y=m[b],$=y._zod.run({value:_[b],issues:[]},g),E=y._zod.optin==="optional"&&y._zod.optout==="optional";$ instanceof Promise?h.push($.then(N=>E?zc(N,p,b,_):Yn(N,p,b))):E?zc($,p,b,_):Yn($,p,b)}}if(!u)return h.length?Promise.all(h).then(()=>p):p;const w=[],f=l.keySet,v=u._zod,d=v.def.type;for(const m of Object.keys(_)){if(f.has(m))continue;if(d==="never"){w.push(m);continue}const b=v.run({value:_[m],issues:[]},g);b instanceof Promise?h.push(b.then(y=>Yn(y,p,m))):Yn(b,p,m)}return w.length&&p.issues.push({code:"unrecognized_keys",keys:w,input:_,inst:t}),h.length?Promise.all(h).then(()=>p):p}});function qc(t,e,r,n){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(a=>Ct(a,n,Tt())))}),e}const Zc=A("$ZodUnion",(t,e)=>{be.init(t,e),Se(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Se(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Se(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Se(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>sa(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1;const a=[];for(const i of e.options){const o=i._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)a.push(o),s=!0;else{if(o.issues.length===0)return o;a.push(o)}}return s?Promise.all(a).then(i=>qc(i,r,t,n)):qc(a,r,t,n)}}),Tp=A("$ZodDiscriminatedUnion",(t,e)=>{Zc.init(t,e);const r=t._zod.parse;Se(t._zod,"propValues",()=>{const s={};for(const a of e.options){const i=a._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(const[o,c]of Object.entries(i)){s[o]||(s[o]=new Set);for(const u of c)s[o].add(u)}}return s});const n=ra(()=>{const s=e.options,a=new Map;for(const i of s){const o=i._zod.propValues[e.discriminator];if(!o||o.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(const c of o){if(a.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);a.set(c,i)}}return a});t._zod.parse=(s,a)=>{const i=s.value;if(!Wn(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;const o=n.value.get(i?.[e.discriminator]);return o?o._zod.run(s,a):e.unionFallback?r(s,a):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),Pp=A("$ZodIntersection",(t,e)=>{be.init(t,e),t._zod.parse=(r,n)=>{const s=r.value,a=e.left._zod.run({value:s,issues:[]},n),i=e.right._zod.run({value:s,issues:[]},n);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([c,u])=>Lc(r,c,u)):Lc(r,a,i)}});function ua(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Kn(t)&&Kn(e)){const r=Object.keys(e),n=Object.keys(t).filter(a=>r.indexOf(a)!==-1),s={...t,...e};for(const a of n){const i=ua(t[a],e[a]);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};s[a]=i.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<t.length;n++){const s=t[n],a=e[n],i=ua(s,a);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Lc(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Cr(t))return t;const n=ua(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}const Cp=A("$ZodRecord",(t,e)=>{be.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!Kn(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;const a=[];if(e.keyType._zod.values){const i=e.keyType._zod.values;r.value={};for(const c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){const u=e.valueType._zod.run({value:s[c],issues:[]},n);u instanceof Promise?a.push(u.then(l=>{l.issues.length&&r.issues.push(...xt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...xt(c,u.issues)),r.value[c]=u.value)}let o;for(const c in s)i.has(c)||(o=o??[],o.push(c));o&&o.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:o})}else{r.value={};for(const i of Reflect.ownKeys(s)){if(i==="__proto__")continue;const o=e.keyType._zod.run({value:i,issues:[]},n);if(o instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(o.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:o.issues.map(u=>Ct(u,n,Tt())),input:i,path:[i],inst:t}),r.value[o.value]=o.value;continue}const c=e.valueType._zod.run({value:s[i],issues:[]},n);c instanceof Promise?a.push(c.then(u=>{u.issues.length&&r.issues.push(...xt(i,u.issues)),r.value[o.value]=u.value})):(c.issues.length&&r.issues.push(...xt(i,c.issues)),r.value[o.value]=c.value)}}return a.length?Promise.all(a).then(()=>r):r}}),Ip=A("$ZodEnum",(t,e)=>{be.init(t,e);const r=gc(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Jf.has(typeof n)).map(n=>typeof n=="string"?Pr(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{const a=n.value;return t._zod.values.has(a)||n.issues.push({code:"invalid_value",values:r,input:a,inst:t}),n}}),Op=A("$ZodLiteral",(t,e)=>{be.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Pr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{const s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),Np=A("$ZodTransform",(t,e)=>{be.init(t,e),t._zod.parse=(r,n)=>{const s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(r.value=i,r));if(s instanceof Promise)throw new Er;return r.value=s,r}}),Ap=A("$ZodOptional",(t,e)=>{be.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Se(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Se(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${sa(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),jp=A("$ZodNullable",(t,e)=>{be.init(t,e),Se(t._zod,"optin",()=>e.innerType._zod.optin),Se(t._zod,"optout",()=>e.innerType._zod.optout),Se(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${sa(r.source)}|null)$`):void 0}),Se(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),zp=A("$ZodDefault",(t,e)=>{be.init(t,e),t._zod.optin="optional",Se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(a=>Dc(a,e)):Dc(s,e)}});function Dc(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const Mp=A("$ZodPrefault",(t,e)=>{be.init(t,e),t._zod.optin="optional",Se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),qp=A("$ZodNonOptional",(t,e)=>{be.init(t,e),Se(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(a=>xc(a,t)):xc(s,t)}});function xc(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const Zp=A("$ZodCatch",(t,e)=>{be.init(t,e),t._zod.optin="optional",Se(t._zod,"optout",()=>e.innerType._zod.optout),Se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(a=>(r.value=a.value,a.issues.length&&(r.value=e.catchValue({...r,error:{issues:a.issues.map(i=>Ct(i,n,Tt()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(a=>Ct(a,n,Tt()))},input:r.value}),r.issues=[]),r)}}),Lp=A("$ZodPipe",(t,e)=>{be.init(t,e),Se(t._zod,"values",()=>e.in._zod.values),Se(t._zod,"optin",()=>e.in._zod.optin),Se(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{const s=e.in._zod.run(r,n);return s instanceof Promise?s.then(a=>Uc(a,e,n)):Uc(s,e,n)}});function Uc(t,e,r){return Cr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const Dp=A("$ZodReadonly",(t,e)=>{be.init(t,e),Se(t._zod,"propValues",()=>e.innerType._zod.propValues),Se(t._zod,"values",()=>e.innerType._zod.values),Se(t._zod,"optin",()=>e.innerType._zod.optin),Se(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Vc):Vc(s)}});function Vc(t){return t.value=Object.freeze(t.value),t}const xp=A("$ZodCustom",(t,e)=>{Je.init(t,e),be.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{const n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(a=>Fc(a,r,n,t));Fc(s,r,n,t)}});function Fc(t,e,r,n){if(!t){const s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(Ir(s))}}class Hc{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function Up(){return new Hc}const Or=Up();function Vp(t,e){return new t({type:"string",...Q(e)})}function Fp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Q(e)})}function Wc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Q(e)})}function Hp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Q(e)})}function Wp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Q(e)})}function Kp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Q(e)})}function Jp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Q(e)})}function Kc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Q(e)})}function Gp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Q(e)})}function Bp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Q(e)})}function Yp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Q(e)})}function Qp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Q(e)})}function Xp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Q(e)})}function em(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Q(e)})}function tm(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Q(e)})}function rm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Q(e)})}function nm(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Q(e)})}function sm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Q(e)})}function am(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Q(e)})}function im(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Q(e)})}function om(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Q(e)})}function cm(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Q(e)})}function um(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Q(e)})}function lm(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Q(e)})}function dm(t,e){return new t({type:"string",format:"date",check:"string_format",...Q(e)})}function fm(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Q(e)})}function hm(t,e){return new t({type:"string",format:"duration",check:"string_format",...Q(e)})}function pm(t,e){return new t({type:"number",checks:[],...Q(e)})}function mm(t,e){return new t({type:"number",coerce:!0,checks:[],...Q(e)})}function _m(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Q(e)})}function gm(t,e){return new t({type:"boolean",...Q(e)})}function ym(t,e){return new t({type:"null",...Q(e)})}function vm(t){return new t({type:"any"})}function wm(t){return new t({type:"unknown"})}function bm(t,e){return new t({type:"never",...Q(e)})}function Jc(t,e){return new Ic({check:"less_than",...Q(e),value:t,inclusive:!1})}function la(t,e){return new Ic({check:"less_than",...Q(e),value:t,inclusive:!0})}function Gc(t,e){return new Oc({check:"greater_than",...Q(e),value:t,inclusive:!1})}function da(t,e){return new Oc({check:"greater_than",...Q(e),value:t,inclusive:!0})}function Bc(t,e){return new zh({check:"multiple_of",...Q(e),value:t})}function Yc(t,e){return new qh({check:"max_length",...Q(e),maximum:t})}function Qn(t,e){return new Zh({check:"min_length",...Q(e),minimum:t})}function Qc(t,e){return new Lh({check:"length_equals",...Q(e),length:t})}function Sm(t,e){return new Dh({check:"string_format",format:"regex",...Q(e),pattern:t})}function km(t){return new xh({check:"string_format",format:"lowercase",...Q(t)})}function $m(t){return new Uh({check:"string_format",format:"uppercase",...Q(t)})}function Em(t,e){return new Vh({check:"string_format",format:"includes",...Q(e),includes:t})}function Rm(t,e){return new Fh({check:"string_format",format:"starts_with",...Q(e),prefix:t})}function Tm(t,e){return new Hh({check:"string_format",format:"ends_with",...Q(e),suffix:t})}function Nr(t){return new Wh({check:"overwrite",tx:t})}function Pm(t){return Nr(e=>e.normalize(t))}function Cm(){return Nr(t=>t.trim())}function Im(){return Nr(t=>t.toLowerCase())}function Om(){return Nr(t=>t.toUpperCase())}function Nm(t,e,r){return new t({type:"array",element:e,...Q(r)})}function Am(t,e,r){const n=Q(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function jm(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Q(r)})}class Xc{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Or,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,o);const c=e._zod.toJSONSchema?.();if(c)o.schema=c;else{const p={...r,schemaPath:[...r.schemaPath,e],path:r.path},g=e._zod.parent;if(g)o.ref=g,this.process(g,p),this.seen.get(g).isParent=!0;else{const _=o.schema;switch(s.type){case"string":{const h=_;h.type="string";const{minimum:w,maximum:f,format:v,patterns:d,contentEncoding:m}=e._zod.bag;if(typeof w=="number"&&(h.minLength=w),typeof f=="number"&&(h.maxLength=f),v&&(h.format=a[v]??v,h.format===""&&delete h.format),m&&(h.contentEncoding=m),d&&d.size>0){const b=[...d];b.length===1?h.pattern=b[0].source:b.length>1&&(o.schema.allOf=[...b.map(y=>({...this.target==="draft-7"?{type:"string"}:{},pattern:y.source}))])}break}case"number":{const h=_,{minimum:w,maximum:f,format:v,multipleOf:d,exclusiveMaximum:m,exclusiveMinimum:b}=e._zod.bag;typeof v=="string"&&v.includes("int")?h.type="integer":h.type="number",typeof b=="number"&&(h.exclusiveMinimum=b),typeof w=="number"&&(h.minimum=w,typeof b=="number"&&(b>=w?delete h.minimum:delete h.exclusiveMinimum)),typeof m=="number"&&(h.exclusiveMaximum=m),typeof f=="number"&&(h.maximum=f,typeof m=="number"&&(m<=f?delete h.maximum:delete h.exclusiveMaximum)),typeof d=="number"&&(h.multipleOf=d);break}case"boolean":{const h=_;h.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{_.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{_.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const h=_,{minimum:w,maximum:f}=e._zod.bag;typeof w=="number"&&(h.minItems=w),typeof f=="number"&&(h.maxItems=f),h.type="array",h.items=this.process(s.element,{...p,path:[...p.path,"items"]});break}case"object":{const h=_;h.type="object",h.properties={};const w=s.shape;for(const d in w)h.properties[d]=this.process(w[d],{...p,path:[...p.path,"properties",d]});const f=new Set(Object.keys(w)),v=new Set([...f].filter(d=>{const m=s.shape[d]._zod;return this.io==="input"?m.optin===void 0:m.optout===void 0}));v.size>0&&(h.required=Array.from(v)),s.catchall?._zod.def.type==="never"?h.additionalProperties=!1:s.catchall?s.catchall&&(h.additionalProperties=this.process(s.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{const h=_;h.anyOf=s.options.map((w,f)=>this.process(w,{...p,path:[...p.path,"anyOf",f]}));break}case"intersection":{const h=_,w=this.process(s.left,{...p,path:[...p.path,"allOf",0]}),f=this.process(s.right,{...p,path:[...p.path,"allOf",1]}),v=m=>"allOf"in m&&Object.keys(m).length===1,d=[...v(w)?w.allOf:[w],...v(f)?f.allOf:[f]];h.allOf=d;break}case"tuple":{const h=_;h.type="array";const w=s.items.map((d,m)=>this.process(d,{...p,path:[...p.path,"prefixItems",m]}));if(this.target==="draft-2020-12"?h.prefixItems=w:h.items=w,s.rest){const d=this.process(s.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?h.items=d:h.additionalItems=d}s.rest&&(h.items=this.process(s.rest,{...p,path:[...p.path,"items"]}));const{minimum:f,maximum:v}=e._zod.bag;typeof f=="number"&&(h.minItems=f),typeof v=="number"&&(h.maxItems=v);break}case"record":{const h=_;h.type="object",h.propertyNames=this.process(s.keyType,{...p,path:[...p.path,"propertyNames"]}),h.additionalProperties=this.process(s.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const h=_,w=gc(s.entries);w.every(f=>typeof f=="number")&&(h.type="number"),w.every(f=>typeof f=="string")&&(h.type="string"),h.enum=w;break}case"literal":{const h=_,w=[];for(const f of s.values)if(f===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof f=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(f))}else w.push(f);if(w.length!==0)if(w.length===1){const f=w[0];h.type=f===null?"null":typeof f,h.const=f}else w.every(f=>typeof f=="number")&&(h.type="number"),w.every(f=>typeof f=="string")&&(h.type="string"),w.every(f=>typeof f=="boolean")&&(h.type="string"),w.every(f=>f===null)&&(h.type="null"),h.enum=w;break}case"file":{const h=_,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:f,maximum:v,mime:d}=e._zod.bag;f!==void 0&&(w.minLength=f),v!==void 0&&(w.maxLength=v),d?d.length===1?(w.contentMediaType=d[0],Object.assign(h,w)):h.anyOf=d.map(m=>({...w,contentMediaType:m})):Object.assign(h,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const h=this.process(s.innerType,p);_.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,p),o.ref=s.innerType;break}case"success":{const h=_;h.type="boolean";break}case"default":{this.process(s.innerType,p),o.ref=s.innerType,_.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,p),o.ref=s.innerType,this.io==="input"&&(_._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,p),o.ref=s.innerType;let h;try{h=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}_.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const h=_,w=e._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=w.source;break}case"pipe":{const h=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(h,p),o.ref=h;break}case"readonly":{this.process(s.innerType,p),o.ref=s.innerType,_.readOnly=!0;break}case"promise":{this.process(s.innerType,p),o.ref=s.innerType;break}case"optional":{this.process(s.innerType,p),o.ref=s.innerType;break}case"lazy":{const h=e._zod.innerType;this.process(h,p),o.ref=h;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(e);return u&&Object.assign(o.schema,u),this.io==="input"&&Ae(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const w=n.external.registry.get(l[0])?.id,f=n.external.uri??(d=>d);if(w)return{ref:f(w)};const v=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=v,{defId:v,ref:`${f("__shared")}#/${p}/${v}`}}if(l[1]===s)return{ref:"#"};const _=`#/${p}/`,h=l[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:_+h}},i=l=>{if(l[1].schema.$ref)return;const p=l[1],{ref:g,defId:_}=a(l);p.def={...p.schema},_&&(p.defId=_);const h=p.schema;for(const w in h)delete h[w];h.$ref=g};if(n.cycles==="throw")for(const l of this.seen.entries()){const p=l[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
34
+
35
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const l of this.seen.entries()){const p=l[1];if(e===l[0]){i(l);continue}if(n.external){const _=n.external.registry.get(l[0])?.id;if(e!==l[0]&&_){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(p.cycle){i(l);continue}if(p.count>1&&n.reused==="ref"){i(l);continue}}const o=(l,p)=>{const g=this.seen.get(l),_=g.def??g.schema,h={..._};if(g.ref===null)return;const w=g.ref;if(g.ref=null,w){o(w,p);const f=this.seen.get(w).schema;f.$ref&&p.target==="draft-7"?(_.allOf=_.allOf??[],_.allOf.push(f)):(Object.assign(_,f),Object.assign(_,h))}g.isParent||this.override({zodSchema:l,jsonSchema:_,path:g.path??[]})};for(const l of[...this.seen.entries()].reverse())o(l[0],{target:this.target});const c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,s.def);const u=n.external?.defs??{};for(const l of this.seen.entries()){const p=l[1];p.def&&p.defId&&(u[p.defId]=p.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function zm(t,e){if(t instanceof Hc){const n=new Xc(e),s={};for(const o of t._idmap.entries()){const[c,u]=o;n.process(u)}const a={},i={registry:t,uri:e?.uri,defs:s};for(const o of t._idmap.entries()){const[c,u]=o;a[c]=n.emit(u,{...e,external:i})}if(Object.keys(s).length>0){const o=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[o]:s}}return{schemas:a}}const r=new Xc(e);return r.process(t),r.emit(t,e)}function Ae(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const s=t._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ae(s.element,r);case"object":{for(const a in s.shape)if(Ae(s.shape[a],r))return!0;return!1}case"union":{for(const a of s.options)if(Ae(a,r))return!0;return!1}case"intersection":return Ae(s.left,r)||Ae(s.right,r);case"tuple":{for(const a of s.items)if(Ae(a,r))return!0;return!!(s.rest&&Ae(s.rest,r))}case"record":return Ae(s.keyType,r)||Ae(s.valueType,r);case"map":return Ae(s.keyType,r)||Ae(s.valueType,r);case"set":return Ae(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ae(s.innerType,r);case"lazy":return Ae(s.getter(),r);case"default":return Ae(s.innerType,r);case"prefault":return Ae(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ae(s.in,r)||Ae(s.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}const Mm=A("ZodISODateTime",(t,e)=>{ip.init(t,e),Pe.init(t,e)});function eu(t){return lm(Mm,t)}const qm=A("ZodISODate",(t,e)=>{op.init(t,e),Pe.init(t,e)});function Zm(t){return dm(qm,t)}const Lm=A("ZodISOTime",(t,e)=>{cp.init(t,e),Pe.init(t,e)});function Dm(t){return fm(Lm,t)}const xm=A("ZodISODuration",(t,e)=>{up.init(t,e),Pe.init(t,e)});function Um(t){return hm(xm,t)}const Xn=A("ZodError",(t,e)=>{wc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>sh(t,r)},flatten:{value:r=>nh(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),Vm=bc(Xn),Fm=Sc(Xn),Hm=kc(Xn),Wm=$c(Xn),Re=A("ZodType",(t,e)=>(be.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Pt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Vm(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Hm(t,r,n),t.parseAsync=async(r,n)=>Fm(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Wm(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(Z_(r,n)),t.superRefine=r=>t.check(L_(r)),t.overwrite=r=>t.check(Nr(r)),t.optional=()=>Oe(t),t.nullable=()=>du(t),t.nullish=()=>Oe(du(t)),t.nonoptional=r=>I_(t,r),t.array=()=>V(t),t.or=r=>$e([t,r]),t.and=r=>ha(t,r),t.transform=r=>ma(t,uu(r)),t.default=r=>T_(t,r),t.prefault=r=>C_(t,r),t.catch=r=>N_(t,r),t.pipe=r=>ma(t,r),t.readonly=()=>z_(t),t.describe=r=>{const n=t.clone();return Or.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Or.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Or.get(t);const n=t.clone();return Or.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),tu=A("_ZodString",(t,e)=>{ca.init(t,e),Re.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Sm(...n)),t.includes=(...n)=>t.check(Em(...n)),t.startsWith=(...n)=>t.check(Rm(...n)),t.endsWith=(...n)=>t.check(Tm(...n)),t.min=(...n)=>t.check(Qn(...n)),t.max=(...n)=>t.check(Yc(...n)),t.length=(...n)=>t.check(Qc(...n)),t.nonempty=(...n)=>t.check(Qn(1,...n)),t.lowercase=n=>t.check(km(n)),t.uppercase=n=>t.check($m(n)),t.trim=()=>t.check(Cm()),t.normalize=(...n)=>t.check(Pm(...n)),t.toLowerCase=()=>t.check(Im()),t.toUpperCase=()=>t.check(Om())}),Km=A("ZodString",(t,e)=>{ca.init(t,e),tu.init(t,e),t.email=r=>t.check(Fp(Jm,r)),t.url=r=>t.check(Kc(nu,r)),t.jwt=r=>t.check(um(l_,r)),t.emoji=r=>t.check(Gp(Bm,r)),t.guid=r=>t.check(Wc(ru,r)),t.uuid=r=>t.check(Hp(es,r)),t.uuidv4=r=>t.check(Wp(es,r)),t.uuidv6=r=>t.check(Kp(es,r)),t.uuidv7=r=>t.check(Jp(es,r)),t.nanoid=r=>t.check(Bp(Ym,r)),t.guid=r=>t.check(Wc(ru,r)),t.cuid=r=>t.check(Yp(Qm,r)),t.cuid2=r=>t.check(Qp(Xm,r)),t.ulid=r=>t.check(Xp(e_,r)),t.base64=r=>t.check(im(o_,r)),t.base64url=r=>t.check(om(c_,r)),t.xid=r=>t.check(em(t_,r)),t.ksuid=r=>t.check(tm(r_,r)),t.ipv4=r=>t.check(rm(n_,r)),t.ipv6=r=>t.check(nm(s_,r)),t.cidrv4=r=>t.check(sm(a_,r)),t.cidrv6=r=>t.check(am(i_,r)),t.e164=r=>t.check(cm(u_,r)),t.datetime=r=>t.check(eu(r)),t.date=r=>t.check(Zm(r)),t.time=r=>t.check(Dm(r)),t.duration=r=>t.check(Um(r))});function R(t){return Vp(Km,t)}const Pe=A("ZodStringFormat",(t,e)=>{Ee.init(t,e),tu.init(t,e)}),Jm=A("ZodEmail",(t,e)=>{Yh.init(t,e),Pe.init(t,e)}),ru=A("ZodGUID",(t,e)=>{Gh.init(t,e),Pe.init(t,e)}),es=A("ZodUUID",(t,e)=>{Bh.init(t,e),Pe.init(t,e)}),nu=A("ZodURL",(t,e)=>{Qh.init(t,e),Pe.init(t,e)});function Gm(t){return Kc(nu,t)}const Bm=A("ZodEmoji",(t,e)=>{Xh.init(t,e),Pe.init(t,e)}),Ym=A("ZodNanoID",(t,e)=>{ep.init(t,e),Pe.init(t,e)}),Qm=A("ZodCUID",(t,e)=>{tp.init(t,e),Pe.init(t,e)}),Xm=A("ZodCUID2",(t,e)=>{rp.init(t,e),Pe.init(t,e)}),e_=A("ZodULID",(t,e)=>{np.init(t,e),Pe.init(t,e)}),t_=A("ZodXID",(t,e)=>{sp.init(t,e),Pe.init(t,e)}),r_=A("ZodKSUID",(t,e)=>{ap.init(t,e),Pe.init(t,e)}),n_=A("ZodIPv4",(t,e)=>{lp.init(t,e),Pe.init(t,e)}),s_=A("ZodIPv6",(t,e)=>{dp.init(t,e),Pe.init(t,e)}),a_=A("ZodCIDRv4",(t,e)=>{fp.init(t,e),Pe.init(t,e)}),i_=A("ZodCIDRv6",(t,e)=>{hp.init(t,e),Pe.init(t,e)}),o_=A("ZodBase64",(t,e)=>{pp.init(t,e),Pe.init(t,e)}),c_=A("ZodBase64URL",(t,e)=>{_p.init(t,e),Pe.init(t,e)}),u_=A("ZodE164",(t,e)=>{gp.init(t,e),Pe.init(t,e)}),l_=A("ZodJWT",(t,e)=>{vp.init(t,e),Pe.init(t,e)}),fa=A("ZodNumber",(t,e)=>{Ac.init(t,e),Re.init(t,e),t.gt=(n,s)=>t.check(Gc(n,s)),t.gte=(n,s)=>t.check(da(n,s)),t.min=(n,s)=>t.check(da(n,s)),t.lt=(n,s)=>t.check(Jc(n,s)),t.lte=(n,s)=>t.check(la(n,s)),t.max=(n,s)=>t.check(la(n,s)),t.int=n=>t.check(su(n)),t.safe=n=>t.check(su(n)),t.positive=n=>t.check(Gc(0,n)),t.nonnegative=n=>t.check(da(0,n)),t.negative=n=>t.check(Jc(0,n)),t.nonpositive=n=>t.check(la(0,n)),t.multipleOf=(n,s)=>t.check(Bc(n,s)),t.step=(n,s)=>t.check(Bc(n,s)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function _e(t){return pm(fa,t)}const d_=A("ZodNumberFormat",(t,e)=>{wp.init(t,e),fa.init(t,e)});function su(t){return _m(d_,t)}const f_=A("ZodBoolean",(t,e)=>{bp.init(t,e),Re.init(t,e)});function ke(t){return gm(f_,t)}const h_=A("ZodNull",(t,e)=>{Sp.init(t,e),Re.init(t,e)});function au(t){return ym(h_,t)}const p_=A("ZodAny",(t,e)=>{kp.init(t,e),Re.init(t,e)});function m_(){return vm(p_)}const __=A("ZodUnknown",(t,e)=>{$p.init(t,e),Re.init(t,e)});function Ce(){return wm(__)}const g_=A("ZodNever",(t,e)=>{Ep.init(t,e),Re.init(t,e)});function y_(t){return bm(g_,t)}const v_=A("ZodArray",(t,e)=>{Rp.init(t,e),Re.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Qn(r,n)),t.nonempty=r=>t.check(Qn(1,r)),t.max=(r,n)=>t.check(Yc(r,n)),t.length=(r,n)=>t.check(Qc(r,n)),t.unwrap=()=>t.element});function V(t,e){return Nm(v_,t,e)}const iu=A("ZodObject",(t,e)=>{Mc.init(t,e),Re.init(t,e),Se(t,"shape",()=>e.shape),t.keyof=()=>et(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ce()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ce()}),t.strict=()=>t.clone({...t._zod.def,catchall:y_()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>Xf(t,r),t.merge=r=>eh(t,r),t.pick=r=>Yf(t,r),t.omit=r=>Qf(t,r),t.partial=(...r)=>th(lu,t,r[0]),t.required=(...r)=>rh(fu,t,r[0])});function H(t,e){const r={type:"object",get shape(){return Rr(this,"shape",{...t}),this.shape},...Q(e)};return new iu(r)}function Le(t,e){return new iu({type:"object",get shape(){return Rr(this,"shape",{...t}),this.shape},catchall:Ce(),...Q(e)})}const ou=A("ZodUnion",(t,e)=>{Zc.init(t,e),Re.init(t,e),t.options=e.options});function $e(t,e){return new ou({type:"union",options:t,...Q(e)})}const w_=A("ZodDiscriminatedUnion",(t,e)=>{ou.init(t,e),Tp.init(t,e)});function cu(t,e,r){return new w_({type:"union",options:e,discriminator:t,...Q(r)})}const b_=A("ZodIntersection",(t,e)=>{Pp.init(t,e),Re.init(t,e)});function ha(t,e){return new b_({type:"intersection",left:t,right:e})}const S_=A("ZodRecord",(t,e)=>{Cp.init(t,e),Re.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Ie(t,e,r){return new S_({type:"record",keyType:t,valueType:e,...Q(r)})}const pa=A("ZodEnum",(t,e)=>{Ip.init(t,e),Re.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{const a={};for(const i of n)if(r.has(i))a[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new pa({...e,checks:[],...Q(s),entries:a})},t.exclude=(n,s)=>{const a={...e.entries};for(const i of n)if(r.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new pa({...e,checks:[],...Q(s),entries:a})}});function et(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new pa({type:"enum",entries:r,...Q(e)})}const k_=A("ZodLiteral",(t,e)=>{Op.init(t,e),Re.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function te(t,e){return new k_({type:"literal",values:Array.isArray(t)?t:[t],...Q(e)})}const $_=A("ZodTransform",(t,e)=>{Np.init(t,e),Re.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=a=>{if(typeof a=="string")r.issues.push(Ir(a,r.value,e));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(Ir(i))}};const s=e.transform(r.value,r);return s instanceof Promise?s.then(a=>(r.value=a,r)):(r.value=s,r)}});function uu(t){return new $_({type:"transform",transform:t})}const lu=A("ZodOptional",(t,e)=>{Ap.init(t,e),Re.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Oe(t){return new lu({type:"optional",innerType:t})}const E_=A("ZodNullable",(t,e)=>{jp.init(t,e),Re.init(t,e),t.unwrap=()=>t._zod.def.innerType});function du(t){return new E_({type:"nullable",innerType:t})}const R_=A("ZodDefault",(t,e)=>{zp.init(t,e),Re.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function T_(t,e){return new R_({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const P_=A("ZodPrefault",(t,e)=>{Mp.init(t,e),Re.init(t,e),t.unwrap=()=>t._zod.def.innerType});function C_(t,e){return new P_({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const fu=A("ZodNonOptional",(t,e)=>{qp.init(t,e),Re.init(t,e),t.unwrap=()=>t._zod.def.innerType});function I_(t,e){return new fu({type:"nonoptional",innerType:t,...Q(e)})}const O_=A("ZodCatch",(t,e)=>{Zp.init(t,e),Re.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function N_(t,e){return new O_({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const A_=A("ZodPipe",(t,e)=>{Lp.init(t,e),Re.init(t,e),t.in=e.in,t.out=e.out});function ma(t,e){return new A_({type:"pipe",in:t,out:e})}const j_=A("ZodReadonly",(t,e)=>{Dp.init(t,e),Re.init(t,e)});function z_(t){return new j_({type:"readonly",innerType:t})}const hu=A("ZodCustom",(t,e)=>{xp.init(t,e),Re.init(t,e)});function M_(t){const e=new Je({check:"custom"});return e._zod.check=t,e}function q_(t,e){return Am(hu,t??(()=>!0),e)}function Z_(t,e={}){return jm(hu,t,e)}function L_(t){const e=M_(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Ir(n,r.value,e._zod.def));else{const s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(Ir(s))}},t(r.value,r)));return e}function pu(t,e){return ma(uu(t),e)}const D_={custom:"custom"};function x_(t){return mm(fa,t)}const Ut="2025-11-25",U_="2025-03-26",_a=[Ut,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],It="io.modelcontextprotocol/related-task",Ar="2.0",De=q_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ga=$e([R(),_e().int()]),ya=R(),V_=Le({ttl:$e([_e(),au()]).optional(),pollInterval:_e().optional()}),mu=H({ttl:_e().optional()}),_u=H({taskId:R()}),va=Le({progressToken:ga.optional(),[It]:_u.optional()}),tt=H({_meta:va.optional()}),tr=tt.extend({task:mu.optional()}),gu=t=>tr.safeParse(t).success,ze=H({method:R(),params:tt.loose().optional()}),st=H({_meta:va.optional()}),rt=H({method:R(),params:st.loose().optional()}),Me=Le({_meta:va.optional()}),jr=$e([R(),_e().int()]),wa=H({jsonrpc:te(Ar),id:jr,...ze.shape}).strict(),ts=t=>wa.safeParse(t).success,ba=H({jsonrpc:te(Ar),...rt.shape}).strict(),yu=t=>ba.safeParse(t).success,rs=H({jsonrpc:te(Ar),id:jr,result:Me}).strict(),Vt=t=>rs.safeParse(t).success,F_=Vt;S.ErrorCode=void 0,(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(S.ErrorCode||(S.ErrorCode={}));const zr=H({jsonrpc:te(Ar),id:jr.optional(),error:H({code:_e().int(),message:R(),data:Ce().optional()})}).strict(),H_=zr,Sa=t=>zr.safeParse(t).success,W_=Sa,Mr=$e([wa,ba,rs,zr]),K_=$e([rs,zr]),Ot=Me.strict(),vu=st.extend({requestId:jr.optional(),reason:R().optional()}),ns=rt.extend({method:te("notifications/cancelled"),params:vu}),wu=H({src:R(),mimeType:R().optional(),sizes:V(R()).optional(),theme:et(["light","dark"]).optional()}),rr=H({icons:V(wu).optional()}),Ft=H({name:R(),title:R().optional()}),ka=Ft.extend({...Ft.shape,...rr.shape,version:R(),websiteUrl:R().optional(),description:R().optional()}),J_=ha(H({applyDefaults:ke().optional()}),Ie(R(),Ce())),G_=pu(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ha(H({form:J_.optional(),url:De.optional()}),Ie(R(),Ce()).optional())),bu=Le({list:De.optional(),cancel:De.optional(),requests:Le({sampling:Le({createMessage:De.optional()}).optional(),elicitation:Le({create:De.optional()}).optional()}).optional()}),Su=Le({list:De.optional(),cancel:De.optional(),requests:Le({tools:Le({call:De.optional()}).optional()}).optional()}),ku=H({experimental:Ie(R(),De).optional(),sampling:H({context:De.optional(),tools:De.optional()}).optional(),elicitation:G_.optional(),roots:H({listChanged:ke().optional()}).optional(),tasks:bu.optional()}),$u=tt.extend({protocolVersion:R(),capabilities:ku,clientInfo:ka}),ss=ze.extend({method:te("initialize"),params:$u}),B_=t=>ss.safeParse(t).success,Eu=H({experimental:Ie(R(),De).optional(),logging:De.optional(),completions:De.optional(),prompts:H({listChanged:ke().optional()}).optional(),resources:H({subscribe:ke().optional(),listChanged:ke().optional()}).optional(),tools:H({listChanged:ke().optional()}).optional(),tasks:Su.optional()}),$a=Me.extend({protocolVersion:R(),capabilities:Eu,serverInfo:ka,instructions:R().optional()}),as=rt.extend({method:te("notifications/initialized"),params:st.optional()}),Ru=t=>as.safeParse(t).success,is=ze.extend({method:te("ping"),params:tt.optional()}),Tu=H({progress:_e(),total:Oe(_e()),message:Oe(R())}),Pu=H({...st.shape,...Tu.shape,progressToken:ga}),os=rt.extend({method:te("notifications/progress"),params:Pu}),Cu=tt.extend({cursor:ya.optional()}),nr=ze.extend({params:Cu.optional()}),sr=Me.extend({nextCursor:ya.optional()}),Iu=et(["working","input_required","completed","failed","cancelled"]),ar=H({taskId:R(),status:Iu,ttl:$e([_e(),au()]),createdAt:R(),lastUpdatedAt:R(),pollInterval:Oe(_e()),statusMessage:Oe(R())}),Ht=Me.extend({task:ar}),Ou=st.merge(ar),qr=rt.extend({method:te("notifications/tasks/status"),params:Ou}),cs=ze.extend({method:te("tasks/get"),params:tt.extend({taskId:R()})}),us=Me.merge(ar),ls=ze.extend({method:te("tasks/result"),params:tt.extend({taskId:R()})}),Y_=Me.loose(),ds=nr.extend({method:te("tasks/list")}),fs=sr.extend({tasks:V(ar)}),hs=ze.extend({method:te("tasks/cancel"),params:tt.extend({taskId:R()})}),Nu=Me.merge(ar),Ea=H({uri:R(),mimeType:Oe(R()),_meta:Ie(R(),Ce()).optional()}),Ra=Ea.extend({text:R()}),Ta=R().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Pa=Ea.extend({blob:Ta}),ir=et(["user","assistant"]),Wt=H({audience:V(ir).optional(),priority:_e().min(0).max(1).optional(),lastModified:eu({offset:!0}).optional()}),Ca=H({...Ft.shape,...rr.shape,uri:R(),description:Oe(R()),mimeType:Oe(R()),annotations:Wt.optional(),_meta:Oe(Le({}))}),Au=H({...Ft.shape,...rr.shape,uriTemplate:R(),description:Oe(R()),mimeType:Oe(R()),annotations:Wt.optional(),_meta:Oe(Le({}))}),ps=nr.extend({method:te("resources/list")}),Ia=sr.extend({resources:V(Ca)}),ms=nr.extend({method:te("resources/templates/list")}),Oa=sr.extend({resourceTemplates:V(Au)}),_s=tt.extend({uri:R()}),ju=_s,gs=ze.extend({method:te("resources/read"),params:ju}),Na=Me.extend({contents:V($e([Ra,Pa]))}),Aa=rt.extend({method:te("notifications/resources/list_changed"),params:st.optional()}),zu=_s,Mu=ze.extend({method:te("resources/subscribe"),params:zu}),qu=_s,Zu=ze.extend({method:te("resources/unsubscribe"),params:qu}),Lu=st.extend({uri:R()}),Du=rt.extend({method:te("notifications/resources/updated"),params:Lu}),xu=H({name:R(),description:Oe(R()),required:Oe(ke())}),Uu=H({...Ft.shape,...rr.shape,description:Oe(R()),arguments:Oe(V(xu)),_meta:Oe(Le({}))}),ys=nr.extend({method:te("prompts/list")}),ja=sr.extend({prompts:V(Uu)}),Vu=tt.extend({name:R(),arguments:Ie(R(),R()).optional()}),vs=ze.extend({method:te("prompts/get"),params:Vu}),ws=H({type:te("text"),text:R(),annotations:Wt.optional(),_meta:Ie(R(),Ce()).optional()}),bs=H({type:te("image"),data:Ta,mimeType:R(),annotations:Wt.optional(),_meta:Ie(R(),Ce()).optional()}),Ss=H({type:te("audio"),data:Ta,mimeType:R(),annotations:Wt.optional(),_meta:Ie(R(),Ce()).optional()}),Fu=H({type:te("tool_use"),name:R(),id:R(),input:Ie(R(),Ce()),_meta:Ie(R(),Ce()).optional()}),Hu=H({type:te("resource"),resource:$e([Ra,Pa]),annotations:Wt.optional(),_meta:Ie(R(),Ce()).optional()}),Wu=Ca.extend({type:te("resource_link")}),ks=$e([ws,bs,Ss,Wu,Hu]),Ku=H({role:ir,content:ks}),za=Me.extend({description:R().optional(),messages:V(Ku)}),Ma=rt.extend({method:te("notifications/prompts/list_changed"),params:st.optional()}),Ju=H({title:R().optional(),readOnlyHint:ke().optional(),destructiveHint:ke().optional(),idempotentHint:ke().optional(),openWorldHint:ke().optional()}),Gu=H({taskSupport:et(["required","optional","forbidden"]).optional()}),qa=H({...Ft.shape,...rr.shape,description:R().optional(),inputSchema:H({type:te("object"),properties:Ie(R(),De).optional(),required:V(R()).optional()}).catchall(Ce()),outputSchema:H({type:te("object"),properties:Ie(R(),De).optional(),required:V(R()).optional()}).catchall(Ce()).optional(),annotations:Ju.optional(),execution:Gu.optional(),_meta:Ie(R(),Ce()).optional()}),$s=nr.extend({method:te("tools/list")}),Za=sr.extend({tools:V(qa)}),or=Me.extend({content:V(ks).default([]),structuredContent:Ie(R(),Ce()).optional(),isError:ke().optional()}),Q_=or.or(Me.extend({toolResult:Ce()})),Bu=tr.extend({name:R(),arguments:Ie(R(),Ce()).optional()}),Zr=ze.extend({method:te("tools/call"),params:Bu}),La=rt.extend({method:te("notifications/tools/list_changed"),params:st.optional()}),Yu=H({autoRefresh:ke().default(!0),debounceMs:_e().int().nonnegative().default(300)}),Lr=et(["debug","info","notice","warning","error","critical","alert","emergency"]),Qu=tt.extend({level:Lr}),Da=ze.extend({method:te("logging/setLevel"),params:Qu}),Xu=st.extend({level:Lr,logger:R().optional(),data:Ce()}),el=rt.extend({method:te("notifications/message"),params:Xu}),tl=H({name:R().optional()}),rl=H({hints:V(tl).optional(),costPriority:_e().min(0).max(1).optional(),speedPriority:_e().min(0).max(1).optional(),intelligencePriority:_e().min(0).max(1).optional()}),nl=H({mode:et(["auto","required","none"]).optional()}),sl=H({type:te("tool_result"),toolUseId:R().describe("The unique identifier for the corresponding tool call."),content:V(ks).default([]),structuredContent:H({}).loose().optional(),isError:ke().optional(),_meta:Ie(R(),Ce()).optional()}),al=cu("type",[ws,bs,Ss]),Dr=cu("type",[ws,bs,Ss,Fu,sl]),il=H({role:ir,content:$e([Dr,V(Dr)]),_meta:Ie(R(),Ce()).optional()}),ol=tr.extend({messages:V(il),modelPreferences:rl.optional(),systemPrompt:R().optional(),includeContext:et(["none","thisServer","allServers"]).optional(),temperature:_e().optional(),maxTokens:_e().int(),stopSequences:V(R()).optional(),metadata:De.optional(),tools:V(qa).optional(),toolChoice:nl.optional()}),xa=ze.extend({method:te("sampling/createMessage"),params:ol}),Es=Me.extend({model:R(),stopReason:Oe(et(["endTurn","stopSequence","maxTokens"]).or(R())),role:ir,content:al}),Ua=Me.extend({model:R(),stopReason:Oe(et(["endTurn","stopSequence","maxTokens","toolUse"]).or(R())),role:ir,content:$e([Dr,V(Dr)])}),cl=H({type:te("boolean"),title:R().optional(),description:R().optional(),default:ke().optional()}),ul=H({type:te("string"),title:R().optional(),description:R().optional(),minLength:_e().optional(),maxLength:_e().optional(),format:et(["email","uri","date","date-time"]).optional(),default:R().optional()}),ll=H({type:et(["number","integer"]),title:R().optional(),description:R().optional(),minimum:_e().optional(),maximum:_e().optional(),default:_e().optional()}),dl=H({type:te("string"),title:R().optional(),description:R().optional(),enum:V(R()),default:R().optional()}),fl=H({type:te("string"),title:R().optional(),description:R().optional(),oneOf:V(H({const:R(),title:R()})),default:R().optional()}),hl=H({type:te("string"),title:R().optional(),description:R().optional(),enum:V(R()),enumNames:V(R()).optional(),default:R().optional()}),pl=$e([dl,fl]),ml=H({type:te("array"),title:R().optional(),description:R().optional(),minItems:_e().optional(),maxItems:_e().optional(),items:H({type:te("string"),enum:V(R())}),default:V(R()).optional()}),_l=H({type:te("array"),title:R().optional(),description:R().optional(),minItems:_e().optional(),maxItems:_e().optional(),items:H({anyOf:V(H({const:R(),title:R()}))}),default:V(R()).optional()}),gl=$e([ml,_l]),yl=$e([hl,pl,gl]),vl=$e([yl,cl,ul,ll]),wl=tr.extend({mode:te("form").optional(),message:R(),requestedSchema:H({type:te("object"),properties:Ie(R(),vl),required:V(R()).optional()})}),bl=tr.extend({mode:te("url"),message:R(),elicitationId:R(),url:R().url()}),Sl=$e([wl,bl]),Va=ze.extend({method:te("elicitation/create"),params:Sl}),kl=st.extend({elicitationId:R()}),$l=rt.extend({method:te("notifications/elicitation/complete"),params:kl}),xr=Me.extend({action:et(["accept","decline","cancel"]),content:pu(t=>t===null?void 0:t,Ie(R(),$e([R(),_e(),ke(),V(R())])).optional())}),Fa=H({type:te("ref/resource"),uri:R()}),X_=Fa,El=H({type:te("ref/prompt"),name:R()}),Rl=tt.extend({ref:$e([El,Fa]),argument:H({name:R(),value:R()}),context:H({arguments:Ie(R(),R()).optional()}).optional()}),Rs=ze.extend({method:te("completion/complete"),params:Rl});function Tl(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Pl(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}const Ha=Me.extend({completion:Le({values:V(R()).max(100),total:Oe(_e().int()),hasMore:Oe(ke())})}),Cl=H({uri:R().startsWith("file://"),name:R().optional(),_meta:Ie(R(),Ce()).optional()}),Il=ze.extend({method:te("roots/list"),params:tt.optional()}),Wa=Me.extend({roots:V(Cl)}),Ol=rt.extend({method:te("notifications/roots/list_changed"),params:st.optional()}),eg=$e([is,ss,Rs,Da,vs,ys,ps,ms,gs,Mu,Zu,Zr,$s,cs,ls,ds,hs]),tg=$e([ns,os,as,Ol,qr]),rg=$e([Ot,Es,Ua,xr,Wa,us,fs,Ht]),ng=$e([is,xa,Va,Il,cs,ls,ds,hs]),sg=$e([ns,os,el,Du,Aa,La,Ma,qr,$l]),ag=$e([Ot,$a,Ha,za,ja,Ia,Oa,Na,or,Za,us,fs,Ht]);class W extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===S.ErrorCode.UrlElicitationRequired&&n){const s=n;if(s.elicitations)return new Nl(s.elicitations,r)}return new W(e,r,n)}}class Nl extends W{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(S.ErrorCode.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}const Al=1e6,Ka=1e6,jl=1e4,ig=1e6;class bt{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){bt.validateLength(e,Al,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const r=[];let n="",s=0,a=0;for(;s<e.length;)if(e[s]==="{"){n&&(r.push(n),n="");const i=e.indexOf("}",s);if(i===-1)throw new Error("Unclosed template expression");if(a++,a>jl)throw new Error(`Template contains too many expressions (max ${jl})`);const o=e.slice(s+1,i),c=this.getOperator(o),u=o.includes("*"),l=this.getNames(o),p=l[0];for(const g of l)bt.validateLength(g,Ka,"Variable name");r.push({name:p,operator:c,names:l,exploded:u}),s=i+1}else n+=e[s],s++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){const r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return bt.validateLength(e,Ka,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){const i=e.names.map(c=>{const u=r[c];if(u===void 0)return"";const l=Array.isArray(u)?u.map(p=>this.encodeValue(p,e.operator)).join(","):this.encodeValue(u.toString(),e.operator);return`${c}=${l}`}).filter(c=>c.length>0);return i.length===0?"":(e.operator==="?"?"?":"&")+i.join("&")}if(e.names.length>1){const i=e.names.map(o=>r[o]).filter(o=>o!==void 0);return i.length===0?"":i.map(o=>Array.isArray(o)?o[0]:o).join(",")}const n=r[e.name];if(n===void 0)return"";const a=(Array.isArray(n)?n:[n]).map(i=>this.encodeValue(i,e.operator));switch(e.operator){case"":return a.join(",");case"+":return a.join(",");case"#":return"#"+a.join(",");case".":return"."+a.join(".");case"/":return"/"+a.join("/");default:return a.join(",")}}expand(e){let r="",n=!1;for(const s of this.parts){if(typeof s=="string"){r+=s;continue}const a=this.expandPart(s,e);a&&((s.operator==="?"||s.operator==="&")&&n?r+=a.replace("?","&"):r+=a,(s.operator==="?"||s.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const r=[];for(const a of e.names)bt.validateLength(a,Ka,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let a=0;a<e.names.length;a++){const i=e.names[a],o=a===0?"\\"+e.operator:"&";r.push({pattern:o+this.escapeRegExp(i)+"=([^&]+)",name:i})}return r}let n;const s=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:s}),r}match(e){bt.validateLength(e,Al,"URI");let r="^";const n=[];for(const o of this.parts)if(typeof o=="string")r+=this.escapeRegExp(o);else{const c=this.partToRegExp(o);for(const{pattern:u,name:l}of c)r+=u,n.push({name:l,exploded:o.exploded})}r+="$",bt.validateLength(r,ig,"Generated regex pattern");const s=new RegExp(r),a=e.match(s);if(!a)return null;const i={};for(let o=0;o<n.length;o++){const{name:c,exploded:u}=n[o],l=a[o+1],p=c.replace("*","");u&&l.includes(",")?i[p]=l.split(","):i[p]=l}return i}}const Ts=Symbol.for("mcp.completable");function og(t,e){return Object.defineProperty(t,Ts,{value:{complete:e},enumerable:!1,writable:!1,configurable:!1}),t}function Ja(t){return!!t&&typeof t=="object"&&Ts in t}function zl(t){return t[Ts]?.complete}function cg(t){return t}S.McpZodTypeKind=void 0,(function(t){t.Completable="McpCompletable"})(S.McpZodTypeKind||(S.McpZodTypeKind={}));function ug(t){return t.title!==void 0&&t.title!==""?t.title:"annotations"in t&&t.annotations?.title?t.annotations.title:t.name}var he;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const a={};for(const i of s)a[i]=i;return a},t.getValidEnumValues=s=>{const a=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(const o of a)i[o]=s[o];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(a){return s[a]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},t.find=(s,a)=>{for(const i of s)if(a(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(he||(he={}));var Ml;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ml||(Ml={}));const B=he.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Nt=t=>{switch(typeof t){case"undefined":return B.undefined;case"string":return B.string;case"number":return Number.isNaN(t)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":return Array.isArray(t)?B.array:t===null?B.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?B.promise:typeof Map<"u"&&t instanceof Map?B.map:typeof Set<"u"&&t instanceof Set?B.set:typeof Date<"u"&&t instanceof Date?B.date:B.object;default:return B.unknown}},Z=he.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"]);class St extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(a){return a.message},n={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof St))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,he.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];r[a]=r[a]||[],r[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}St.create=t=>new St(t);const Ga=(t,e)=>{let r;switch(t.code){case Z.invalid_type:t.received===B.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Z.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,he.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:r=`Unrecognized key(s) in object: ${he.joinValues(t.keys,", ")}`;break;case Z.invalid_union:r="Invalid input";break;case Z.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${he.joinValues(t.options)}`;break;case Z.invalid_enum_value:r=`Invalid enum value. Expected ${he.joinValues(t.options)}, received '${t.received}'`;break;case Z.invalid_arguments:r="Invalid function arguments";break;case Z.invalid_return_type:r="Invalid function return type";break;case Z.invalid_date:r="Invalid date";break;case Z.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:he.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Z.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Z.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Z.custom:r="Invalid input";break;case Z.invalid_intersection_types:r="Intersection results could not be merged";break;case Z.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Z.not_finite:r="Number must be finite";break;default:r=e.defaultError,he.assertNever(t)}return{message:r}};let lg=Ga;function dg(){return lg}const fg=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,a=[...r,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}};function J(t,e){const r=dg(),n=fg({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ga?void 0:Ga].filter(s=>!!s)});t.common.issues.push(n)}class nt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return se;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const a=await s.key,i=await s.value;n.push({key:a,value:i})}return nt.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return se;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}}const se=Object.freeze({status:"aborted"}),Ur=t=>({status:"dirty",value:t}),at=t=>({status:"valid",value:t}),ql=t=>t.status==="aborted",Zl=t=>t.status==="dirty",cr=t=>t.status==="valid",Ps=t=>typeof Promise<"u"&&t instanceof Promise;var X;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(X||(X={}));class At{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}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}}const Ll=(t,e)=>{if(cr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new St(t.common.issues);return this._error=r,this._error}}};function oe(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{const{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:s}}class de{get description(){return this._def.description}_getType(e){return Nt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Nt(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:Nt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Ps(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nt(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Ll(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nt(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return cr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>cr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nt(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Ps(s)?s:Promise.resolve(s));return Ll(n,a)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,a)=>{const i=e(s),o=()=>a.addIssue({code:Z.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new dr({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return kt.create(this,this._def)}nullable(){return fr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gt.create(this)}promise(){return Ns.create(this,this._def)}or(e){return Is.create([this,e],this._def)}and(e){return Os.create(this,e,this._def)}transform(e){return new dr({...oe(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Qa({...oe(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new zg({typeName:D.ZodBranded,type:this,...oe(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Xa({...oe(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ei.create(this,e)}readonly(){return ti.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const hg=/^c[^\s-]{8,}$/i,pg=/^[0-9a-z]+$/,mg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_g=/^[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,gg=/^[a-z0-9_-]{21}$/i,yg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vg=/^[-+]?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)?)??$/,wg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,bg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ba;const Sg=/^(?:(?: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])$/,kg=/^(?:(?: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])$/,$g=/^(([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]))$/,Eg=/^(([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])$/,Rg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Tg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Dl="((\\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])))",Pg=new RegExp(`^${Dl}$`);function xl(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Cg(t){return new RegExp(`^${xl(t)}$`)}function Ig(t){let e=`${Dl}T${xl(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Og(t,e){return!!((e==="v4"||!e)&&Sg.test(t)||(e==="v6"||!e)&&$g.test(t))}function Ng(t,e){if(!yg.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Ag(t,e){return!!((e==="v4"||!e)&&kg.test(t)||(e==="v6"||!e)&&Eg.test(t))}class Kt extends de{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==B.string){const a=this._getOrReturnCtx(e);return J(a,{code:Z.invalid_type,expected:B.string,received:a.parsedType}),se}const n=new nt;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),J(s,{code:Z.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),J(s,{code:Z.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?J(s,{code:Z.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&J(s,{code:Z.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")wg.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"email",code:Z.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Ba||(Ba=new RegExp(bg,"u")),Ba.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"emoji",code:Z.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")_g.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"uuid",code:Z.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")gg.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"nanoid",code:Z.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")hg.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"cuid",code:Z.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")pg.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"cuid2",code:Z.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")mg.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"ulid",code:Z.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),J(s,{validation:"url",code:Z.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"regex",code:Z.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),J(s,{code:Z.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),J(s,{code:Z.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),J(s,{code:Z.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?Ig(a).test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{code:Z.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?Pg.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{code:Z.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?Cg(a).test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{code:Z.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?vg.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"duration",code:Z.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?Og(e.data,a.version)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"ip",code:Z.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?Ng(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"jwt",code:Z.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Ag(e.data,a.version)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"cidr",code:Z.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?Rg.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"base64",code:Z.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?Tg.test(e.data)||(s=this._getOrReturnCtx(e,s),J(s,{validation:"base64url",code:Z.invalid_string,message:a.message}),n.dirty()):he.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:Z.invalid_string,...X.errToObj(n)})}_addCheck(e){return new Kt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...X.errToObj(e)})}url(e){return this._addCheck({kind:"url",...X.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...X.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...X.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...X.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...X.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...X.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...X.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...X.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...X.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...X.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...X.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...X.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,...X.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,...X.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...X.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...X.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...X.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...X.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...X.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...X.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...X.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...X.errToObj(r)})}nonempty(e){return this.min(1,X.errToObj(e))}trim(){return new Kt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Kt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Kt({...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(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Kt.create=t=>new Kt({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...oe(t)});function jg(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,a=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}class Vr extends de{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)!==B.number){const a=this._getOrReturnCtx(e);return J(a,{code:Z.invalid_type,expected:B.number,received:a.parsedType}),se}let n;const s=new nt;for(const a of this._def.checks)a.kind==="int"?he.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),J(n,{code:Z.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),J(n,{code:Z.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),J(n,{code:Z.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?jg(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),J(n,{code:Z.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),J(n,{code:Z.not_finite,message:a.message}),s.dirty()):he.assertNever(a);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,X.toString(r))}gt(e,r){return this.setLimit("min",e,!1,X.toString(r))}lte(e,r){return this.setLimit("max",e,!0,X.toString(r))}lt(e,r){return this.setLimit("max",e,!1,X.toString(r))}setLimit(e,r,n,s){return new Vr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:X.toString(s)}]})}_addCheck(e){return new Vr({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:X.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:X.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&he.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}Vr.create=t=>new Vr({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...oe(t)});class Fr extends de{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)!==B.bigint)return this._getInvalidInput(e);let n;const s=new nt;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),J(n,{code:Z.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),J(n,{code:Z.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),J(n,{code:Z.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):he.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return J(r,{code:Z.invalid_type,expected:B.bigint,received:r.parsedType}),se}gte(e,r){return this.setLimit("min",e,!0,X.toString(r))}gt(e,r){return this.setLimit("min",e,!1,X.toString(r))}lte(e,r){return this.setLimit("max",e,!0,X.toString(r))}lt(e,r){return this.setLimit("max",e,!1,X.toString(r))}setLimit(e,r,n,s){return new Fr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:X.toString(s)}]})}_addCheck(e){return new Fr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Fr.create=t=>new Fr({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...oe(t)});class Ul extends de{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==B.boolean){const n=this._getOrReturnCtx(e);return J(n,{code:Z.invalid_type,expected:B.boolean,received:n.parsedType}),se}return at(e.data)}}Ul.create=t=>new Ul({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...oe(t)});class Cs extends de{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==B.date){const a=this._getOrReturnCtx(e);return J(a,{code:Z.invalid_type,expected:B.date,received:a.parsedType}),se}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return J(a,{code:Z.invalid_date}),se}const n=new nt;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),J(s,{code:Z.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),J(s,{code:Z.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):he.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Cs({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:X.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:X.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}Cs.create=t=>new Cs({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...oe(t)});class Vl extends de{_parse(e){if(this._getType(e)!==B.symbol){const n=this._getOrReturnCtx(e);return J(n,{code:Z.invalid_type,expected:B.symbol,received:n.parsedType}),se}return at(e.data)}}Vl.create=t=>new Vl({typeName:D.ZodSymbol,...oe(t)});class Fl extends de{_parse(e){if(this._getType(e)!==B.undefined){const n=this._getOrReturnCtx(e);return J(n,{code:Z.invalid_type,expected:B.undefined,received:n.parsedType}),se}return at(e.data)}}Fl.create=t=>new Fl({typeName:D.ZodUndefined,...oe(t)});class Hl extends de{_parse(e){if(this._getType(e)!==B.null){const n=this._getOrReturnCtx(e);return J(n,{code:Z.invalid_type,expected:B.null,received:n.parsedType}),se}return at(e.data)}}Hl.create=t=>new Hl({typeName:D.ZodNull,...oe(t)});class Wl extends de{constructor(){super(...arguments),this._any=!0}_parse(e){return at(e.data)}}Wl.create=t=>new Wl({typeName:D.ZodAny,...oe(t)});class Kl extends de{constructor(){super(...arguments),this._unknown=!0}_parse(e){return at(e.data)}}Kl.create=t=>new Kl({typeName:D.ZodUnknown,...oe(t)});class jt extends de{_parse(e){const r=this._getOrReturnCtx(e);return J(r,{code:Z.invalid_type,expected:B.never,received:r.parsedType}),se}}jt.create=t=>new jt({typeName:D.ZodNever,...oe(t)});class Jl extends de{_parse(e){if(this._getType(e)!==B.undefined){const n=this._getOrReturnCtx(e);return J(n,{code:Z.invalid_type,expected:B.void,received:n.parsedType}),se}return at(e.data)}}Jl.create=t=>new Jl({typeName:D.ZodVoid,...oe(t)});class gt extends de{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==B.array)return J(r,{code:Z.invalid_type,expected:B.array,received:r.parsedType}),se;if(s.exactLength!==null){const i=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(i||o)&&(J(r,{code:i?Z.too_big:Z.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(J(r,{code:Z.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(J(r,{code:Z.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>s.type._parseAsync(new At(r,i,r.path,o)))).then(i=>nt.mergeArray(n,i));const a=[...r.data].map((i,o)=>s.type._parseSync(new At(r,i,r.path,o)));return nt.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new gt({...this._def,minLength:{value:e,message:X.toString(r)}})}max(e,r){return new gt({...this._def,maxLength:{value:e,message:X.toString(r)}})}length(e,r){return new gt({...this._def,exactLength:{value:e,message:X.toString(r)}})}nonempty(e){return this.min(1,e)}}gt.create=(t,e)=>new gt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...oe(e)});function ur(t){if(t instanceof Ne){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=kt.create(ur(n))}return new Ne({...t._def,shape:()=>e})}else return t instanceof gt?new gt({...t._def,type:ur(t.element)}):t instanceof kt?kt.create(ur(t.unwrap())):t instanceof fr?fr.create(ur(t.unwrap())):t instanceof Jt?Jt.create(t.items.map(e=>ur(e))):t}class Ne extends de{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=he.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==B.object){const u=this._getOrReturnCtx(e);return J(u,{code:Z.invalid_type,expected:B.object,received:u.parsedType}),se}const{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof jt&&this._def.unknownKeys==="strip"))for(const u in s.data)i.includes(u)||o.push(u);const c=[];for(const u of i){const l=a[u],p=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new At(s,p,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof jt){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")o.length>0&&(J(s,{code:Z.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of o){const p=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new At(s,p,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const p=await l.key,g=await l.value;u.push({key:p,value:g,alwaysSet:l.alwaysSet})}return u}).then(u=>nt.mergeObjectSync(n,u)):nt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return X.errToObj,new Ne({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:X.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Ne({...this._def,unknownKeys:"strip"})}passthrough(){return new Ne({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ne({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ne({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new Ne({...this._def,catchall:e})}pick(e){const r={};for(const n of he.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new Ne({...this._def,shape:()=>r})}omit(e){const r={};for(const n of he.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new Ne({...this._def,shape:()=>r})}deepPartial(){return ur(this)}partial(e){const r={};for(const n of he.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new Ne({...this._def,shape:()=>r})}required(e){const r={};for(const n of he.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof kt;)a=a._def.innerType;r[n]=a}return new Ne({...this._def,shape:()=>r})}keyof(){return Ql(he.objectKeys(this.shape))}}Ne.create=(t,e)=>new Ne({shape:()=>t,unknownKeys:"strip",catchall:jt.create(),typeName:D.ZodObject,...oe(e)}),Ne.strictCreate=(t,e)=>new Ne({shape:()=>t,unknownKeys:"strict",catchall:jt.create(),typeName:D.ZodObject,...oe(e)}),Ne.lazycreate=(t,e)=>new Ne({shape:t,unknownKeys:"strip",catchall:jt.create(),typeName:D.ZodObject,...oe(e)});class Is extends de{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new St(o.ctx.common.issues));return J(r,{code:Z.invalid_union,unionErrors:i}),se}if(r.common.async)return Promise.all(n.map(async a=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let a;const i=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!a&&(a={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(c=>new St(c));return J(r,{code:Z.invalid_union,unionErrors:o}),se}}get options(){return this._def.options}}Is.create=(t,e)=>new Is({options:t,typeName:D.ZodUnion,...oe(e)});function Ya(t,e){const r=Nt(t),n=Nt(e);if(t===e)return{valid:!0,data:t};if(r===B.object&&n===B.object){const s=he.objectKeys(e),a=he.objectKeys(t).filter(o=>s.indexOf(o)!==-1),i={...t,...e};for(const o of a){const c=Ya(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===B.array&&n===B.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<t.length;a++){const i=t[a],o=e[a],c=Ya(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===B.date&&n===B.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Os extends de{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(ql(a)||ql(i))return se;const o=Ya(a.value,i.value);return o.valid?((Zl(a)||Zl(i))&&r.dirty(),{status:r.value,value:o.data}):(J(n,{code:Z.invalid_intersection_types}),se)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Os.create=(t,e,r)=>new Os({left:t,right:e,typeName:D.ZodIntersection,...oe(r)});class Jt extends de{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==B.array)return J(n,{code:Z.invalid_type,expected:B.array,received:n.parsedType}),se;if(n.data.length<this._def.items.length)return J(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),se;!this._def.rest&&n.data.length>this._def.items.length&&(J(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const a=[...n.data].map((i,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new At(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>nt.mergeArray(r,i)):nt.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new Jt({...this._def,rest:e})}}Jt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Jt({items:t,typeName:D.ZodTuple,rest:null,...oe(e)})};class Gl extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==B.map)return J(n,{code:Z.invalid_type,expected:B.map,received:n.parsedType}),se;const s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new At(n,o,n.path,[u,"key"])),value:a._parse(new At(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of i){const u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return se;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of i){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return se;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}}}}Gl.create=(t,e,r)=>new Gl({valueType:e,keyType:t,typeName:D.ZodMap,...oe(r)});class Hr extends de{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==B.set)return J(n,{code:Z.invalid_type,expected:B.set,received:n.parsedType}),se;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(J(n,{code:Z.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(J(n,{code:Z.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const a=this._def.valueType;function i(c){const u=new Set;for(const l of c){if(l.status==="aborted")return se;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>a._parse(new At(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new Hr({...this._def,minSize:{value:e,message:X.toString(r)}})}max(e,r){return new Hr({...this._def,maxSize:{value:e,message:X.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Hr.create=(t,e)=>new Hr({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...oe(e)});class Bl extends de{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Bl.create=(t,e)=>new Bl({getter:t,typeName:D.ZodLazy,...oe(e)});class Yl extends de{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return J(r,{received:r.data,code:Z.invalid_literal,expected:this._def.value}),se}return{status:"valid",value:e.data}}get value(){return this._def.value}}Yl.create=(t,e)=>new Yl({value:t,typeName:D.ZodLiteral,...oe(e)});function Ql(t,e){return new lr({values:t,typeName:D.ZodEnum,...oe(e)})}class lr extends de{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return J(r,{expected:he.joinValues(n),received:r.parsedType,code:Z.invalid_type}),se}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return J(r,{received:r.data,code:Z.invalid_enum_value,options:n}),se}return at(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return lr.create(e,{...this._def,...r})}exclude(e,r=this._def){return lr.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}lr.create=Ql;class Xl extends de{_parse(e){const r=he.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==B.string&&n.parsedType!==B.number){const s=he.objectValues(r);return J(n,{expected:he.joinValues(s),received:n.parsedType,code:Z.invalid_type}),se}if(this._cache||(this._cache=new Set(he.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=he.objectValues(r);return J(n,{received:n.data,code:Z.invalid_enum_value,options:s}),se}return at(e.data)}get enum(){return this._def.values}}Xl.create=(t,e)=>new Xl({values:t,typeName:D.ZodNativeEnum,...oe(e)});class Ns extends de{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==B.promise&&r.common.async===!1)return J(r,{code:Z.invalid_type,expected:B.promise,received:r.parsedType}),se;const n=r.parsedType===B.promise?r.data:Promise.resolve(r.data);return at(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Ns.create=(t,e)=>new Ns({type:t,typeName:D.ZodPromise,...oe(e)});class dr extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{J(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return se;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?se:c.status==="dirty"||r.value==="dirty"?Ur(c.value):c});{if(r.value==="aborted")return se;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?se:o.status==="dirty"||r.value==="dirty"?Ur(o.value):o}}if(s.type==="refinement"){const i=o=>{const c=s.refinement(o,a);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?se:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?se:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!cr(i))return se;const o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>cr(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:r.value,value:o})):se);he.assertNever(s)}}dr.create=(t,e,r)=>new dr({schema:t,typeName:D.ZodEffects,effect:e,...oe(r)}),dr.createWithPreprocess=(t,e,r)=>new dr({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...oe(r)});class kt extends de{_parse(e){return this._getType(e)===B.undefined?at(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}kt.create=(t,e)=>new kt({innerType:t,typeName:D.ZodOptional,...oe(e)});class fr extends de{_parse(e){return this._getType(e)===B.null?at(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fr.create=(t,e)=>new fr({innerType:t,typeName:D.ZodNullable,...oe(e)});class Qa extends de{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===B.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}Qa.create=(t,e)=>new Qa({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...oe(e)});class Xa extends de{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ps(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new St(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new St(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Xa.create=(t,e)=>new Xa({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...oe(e)});class ed extends de{_parse(e){if(this._getType(e)!==B.nan){const n=this._getOrReturnCtx(e);return J(n,{code:Z.invalid_type,expected:B.nan,received:n.parsedType}),se}return{status:"valid",value:e.data}}}ed.create=t=>new ed({typeName:D.ZodNaN,...oe(t)});class zg extends de{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class ei extends de{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?se:a.status==="dirty"?(r.dirty(),Ur(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?se:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new ei({in:e,out:r,typeName:D.ZodPipeline})}}class ti extends de{_parse(e){const r=this._def.innerType._parse(e),n=s=>(cr(s)&&(s.value=Object.freeze(s.value)),s);return Ps(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}ti.create=(t,e)=>new ti({innerType:t,typeName:D.ZodReadonly,...oe(e)});var D;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(D||(D={})),jt.create,gt.create;const Mg=Ne.create;Is.create,Os.create,Jt.create,lr.create,Ns.create,kt.create,fr.create;const qg=A("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");be.init(t,e),t.def=e,t.parse=(r,n)=>ah(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>ia(t,r,n),t.parseAsync=async(r,n)=>ih(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>oa(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Pt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),Zg=A("ZodMiniObject",(t,e)=>{Mc.init(t,e),qg.init(t,e),Se(t,"shape",()=>e.shape)});function td(t,e){const r={type:"object",get shape(){return Rr(this,"shape",{...t}),this.shape},...Q(e)};return new Zg(r)}function lt(t){return!!t._zod}function hr(t){const e=Object.values(t);if(e.length===0)return td({});const r=e.every(lt),n=e.every(s=>!lt(s));if(r)return td(t);if(n)return Mg(t);throw new Error("Mixed Zod versions detected in object shape.")}function dt(t,e){return lt(t)?ia(t,e):t.safeParse(e)}async function ri(t,e){return lt(t)?await oa(t,e):await t.safeParseAsync(e)}function pr(t){if(!t)return;let e;if(lt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Wr(t){if(t){if(typeof t=="object"){const e=t,r=t;if(!e._def&&!r._zod){const n=Object.values(t);if(n.length>0&&n.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return hr(t)}}if(lt(t)){const r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function ni(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){const e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Lg(t){return t.description}function Dg(t){if(lt(t))return t._zod?.def?.type==="optional";const e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function rd(t){if(lt(t)){const a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}const r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=t.value;if(n!==void 0)return n}function Gt(t){return t==="completed"||t==="failed"||t==="cancelled"}const xg=Symbol("Let zodToJsonSchema decide on which parser to use"),nd={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Ug=t=>typeof t=="string"?{...nd,name:t}:{...nd,...t},Vg=t=>{const e=Ug(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function sd(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ve(t,e,r,n,s){t[e]=r,sd(t,e,n,s)}const ad=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Ge(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ad(e,t.currentPath):e.join("/")}}function Fg(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=pe(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ve(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ve(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ve(r,"minItems",t.exactLength.value,t.exactLength.message,e),ve(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Hg(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ve(r,"minimum",n.value,n.message,e):ve(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ve(r,"maximum",n.value,n.message,e):ve(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",n.value,n.message,e));break;case"multipleOf":ve(r,"multipleOf",n.value,n.message,e);break}return r}function Wg(){return{type:"boolean"}}function id(t,e){return pe(t.type._def,e)}const Kg=(t,e)=>pe(t.innerType._def,e);function od(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,a)=>od(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Jg(t,e)}}const Jg=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":ve(r,"minimum",n.value,n.message,e);break;case"max":ve(r,"maximum",n.value,n.message,e);break}return r};function Gg(t,e){return{...pe(t.innerType._def,e),default:t.defaultValue()}}function Bg(t,e){return e.effectStrategy==="input"?pe(t.schema._def,e):Ge(e)}function Yg(t){return{type:"string",enum:Array.from(t.values)}}const Qg=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Xg(t,e){const r=[pe(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),pe(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach(a=>{if(Qg(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}function ey(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let si;const ft={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(si===void 0&&(si=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),si),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function cd(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":ve(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ve(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":ht(r,"email",n.message,e);break;case"format:idn-email":ht(r,"idn-email",n.message,e);break;case"pattern:zod":He(r,ft.email,n.message,e);break}break;case"url":ht(r,"uri",n.message,e);break;case"uuid":ht(r,"uuid",n.message,e);break;case"regex":He(r,n.regex,n.message,e);break;case"cuid":He(r,ft.cuid,n.message,e);break;case"cuid2":He(r,ft.cuid2,n.message,e);break;case"startsWith":He(r,RegExp(`^${ai(n.value,e)}`),n.message,e);break;case"endsWith":He(r,RegExp(`${ai(n.value,e)}$`),n.message,e);break;case"datetime":ht(r,"date-time",n.message,e);break;case"date":ht(r,"date",n.message,e);break;case"time":ht(r,"time",n.message,e);break;case"duration":ht(r,"duration",n.message,e);break;case"length":ve(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ve(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{He(r,RegExp(ai(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&ht(r,"ipv4",n.message,e),n.version!=="v4"&&ht(r,"ipv6",n.message,e);break}case"base64url":He(r,ft.base64url,n.message,e);break;case"jwt":He(r,ft.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&He(r,ft.ipv4Cidr,n.message,e),n.version!=="v4"&&He(r,ft.ipv6Cidr,n.message,e);break}case"emoji":He(r,ft.emoji(),n.message,e);break;case"ulid":{He(r,ft.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ht(r,"binary",n.message,e);break}case"contentEncoding:base64":{ve(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{He(r,ft.base64,n.message,e);break}}break}case"nanoid":He(r,ft.nanoid,n.message,e)}return r}function ai(t,e){return e.patternStrategy==="escape"?ry(t):t}const ty=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ry(t){let e="";for(let r=0;r<t.length;r++)ty.has(t[r])||(e+="\\"),e+=t[r];return e}function ht(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ve(t,"format",e,r,n)}function He(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:ud(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ve(t,"pattern",ud(e,n),r,n)}function ud(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let s="",a=!1,i=!1,o=!1;for(let c=0;c<n.length;c++){if(a){s+=n[c],a=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){o?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],o=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
36
+ ]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
37
+ ]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
38
+ `:`[${n[c]}\r
39
+ ]`;continue}s+=n[c],n[c]==="\\"?a=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function ld(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:pe(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??Ge(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:pe(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){const{type:n,...s}=cd(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...s}=id(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function ny(t,e){if(e.mapStrategy==="record")return ld(t,e);const r=pe(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ge(e),n=pe(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ge(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function sy(t){const e=t.values,n=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(n.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function ay(t){return t.target==="openAi"?void 0:{not:Ge({...t,currentPath:[...t.currentPath,"not"]})}}function iy(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const As={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function oy(t,e){if(e.target==="openApi3")return dd(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in As&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,a)=>{const i=As[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:r.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(a=>!n.includes(a))],[])};return dd(t,e)}const dd=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>pe(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function cy(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:As[t.innerType._def.typeName],nullable:!0}:{type:[As[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=pe(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=pe(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function uy(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",sd(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ve(r,"minimum",n.value,n.message,e):ve(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ve(r,"maximum",n.value,n.message,e):ve(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",n.value,n.message,e));break;case"multipleOf":ve(r,"multipleOf",n.value,n.message,e);break}return r}function ly(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},s=[],a=t.shape();for(const o in a){let c=a[o];if(c===void 0||c._def===void 0)continue;let u=fy(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=pe(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(n.properties[o]=l,u||s.push(o))}s.length&&(n.required=s);const i=dy(t,e);return i!==void 0&&(n.additionalProperties=i),n}function dy(t,e){if(t.catchall._def.typeName!=="ZodNever")return pe(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function fy(t){try{return t.isOptional()}catch{return!0}}const hy=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return pe(t.innerType._def,e);const r=pe(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ge(e)},r]}:Ge(e)},py=(t,e)=>{if(e.pipeStrategy==="input")return pe(t.in._def,e);if(e.pipeStrategy==="output")return pe(t.out._def,e);const r=pe(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=pe(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function my(t,e){return pe(t.type._def,e)}function _y(t,e){const n={type:"array",uniqueItems:!0,items:pe(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ve(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ve(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function gy(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>pe(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:pe(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>pe(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function yy(t){return{not:Ge(t)}}function vy(t){return Ge(t)}const wy=(t,e)=>pe(t.innerType._def,e),by=(t,e,r)=>{switch(e){case D.ZodString:return cd(t,r);case D.ZodNumber:return uy(t,r);case D.ZodObject:return ly(t,r);case D.ZodBigInt:return Hg(t,r);case D.ZodBoolean:return Wg();case D.ZodDate:return od(t,r);case D.ZodUndefined:return yy(r);case D.ZodNull:return iy(r);case D.ZodArray:return Fg(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return oy(t,r);case D.ZodIntersection:return Xg(t,r);case D.ZodTuple:return gy(t,r);case D.ZodRecord:return ld(t,r);case D.ZodLiteral:return ey(t,r);case D.ZodEnum:return Yg(t);case D.ZodNativeEnum:return sy(t);case D.ZodNullable:return cy(t,r);case D.ZodOptional:return hy(t,r);case D.ZodMap:return ny(t,r);case D.ZodSet:return _y(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return my(t,r);case D.ZodNaN:case D.ZodNever:return ay(r);case D.ZodEffects:return Bg(t,r);case D.ZodAny:return Ge(r);case D.ZodUnknown:return vy(r);case D.ZodDefault:return Gg(t,r);case D.ZodBranded:return id(t,r);case D.ZodReadonly:return wy(t,r);case D.ZodCatch:return Kg(t,r);case D.ZodPipeline:return py(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})()}};function pe(t,e,r=!1){const n=e.seen.get(t);if(e.override){const o=e.override?.(t,e,n,r);if(o!==xg)return o}if(n&&!r){const o=Sy(n,e);if(o!==void 0)return o}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const a=by(t,t.typeName,e),i=typeof a=="function"?pe(a(),e):a;if(i&&ky(t,e,i),e.postProcess){const o=e.postProcess(i,t,e);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const Sy=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ad(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ge(e)):e.$refStrategy==="seen"?Ge(e):void 0}},ky=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),$y=(t,e)=>{const r=Vg(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:pe(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ge(r)}),{}):void 0;const s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=pe(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??Ge(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const o=s===void 0?n?{...a,[r.definitionPath]:n}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:a}};return r.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};function Ey(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function fd(t,e){return lt(t)?zm(t,{target:Ey(e?.target),io:e?.pipeStrategy??"input"}):$y(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function hd(t){const r=pr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=rd(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function pd(t,e){const r=dt(t,e);if(!r.success)throw r.error;return r.data}const md=6e4;class ii{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ns,r=>{this._oncancel(r)}),this.setNotificationHandler(os,r=>{this._onprogress(r)}),this.setRequestHandler(is,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(cs,async(r,n)=>{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new W(S.ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(ls,async(r,n)=>{const s=async()=>{const a=r.params.taskId;if(this._taskMessageQueue){let o;for(;o=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(o.type==="response"||o.type==="error"){const c=o.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),o.type==="response")l(c);else{const p=c,g=new W(p.error.code,p.error.message,p.error.data);l(g)}else{const p=o.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${u}`))}continue}await this._transport?.send(o.message,{relatedRequestId:n.requestId})}}const i=await this._taskStore.getTask(a,n.sessionId);if(!i)throw new W(S.ErrorCode.InvalidParams,`Task not found: ${a}`);if(!Gt(i.status))return await this._waitForTaskUpdate(a,n.signal),await s();if(Gt(i.status)){const o=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...o,_meta:{...o._meta,[It]:{taskId:a}}}}return await s()};return await s()}),this.setRequestHandler(ds,async(r,n)=>{try{const{tasks:s,nextCursor:a}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:a,_meta:{}}}catch(s){throw new W(S.ErrorCode.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(hs,async(r,n)=>{try{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new W(S.ErrorCode.InvalidParams,`Task not found: ${r.params.taskId}`);if(Gt(s.status))throw new W(S.ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new W(S.ErrorCode.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(s){throw s instanceof W?s:new W(S.ErrorCode.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:s})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),W.fromError(S.ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=a=>{n?.(a),this._onerror(a)};const s=this._transport?.onmessage;this._transport.onmessage=(a,i)=>{s?.(a,i),Vt(a)||Sa(a)?this._onresponse(a):ts(a)?this._onrequest(a,i):yu(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=W.fromError(S.ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){const r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){const n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,a=e.params?._meta?.[It]?.taskId;if(n===void 0){const l={jsonrpc:"2.0",id:e.id,error:{code:S.ErrorCode.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:l,timestamp:Date.now()},s?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):s?.send(l).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const o=gu(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{const p={relatedRequestId:e.id};a&&(p.relatedTask={taskId:a}),await this.notification(l,p)},sendRequest:async(l,p,g)=>{const _={...g,relatedRequestId:e.id};a&&!_.relatedTask&&(_.relatedTask={taskId:a});const h=_.relatedTask?.taskId??a;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,p,_)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:a,taskStore:c,taskRequestedTtl:o?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;const p={result:l,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:p,timestamp:Date.now()},s?.sessionId):await s?.send(p)},async l=>{if(i.signal.aborted)return;const p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:S.ErrorCode.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:p,timestamp:Date.now()},s?.sessionId):await s?.send(p)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...n}=e.params,s=Number(r),a=this._progressHandlers.get(s);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const i=this._responseHandlers.get(s),o=this._timeoutInfo.get(s);if(o&&i&&o.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}a(n)}_onresponse(e){const r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Vt(e))n(e);else{const i=new W(e.error.code,e.error.message,e.error.data);n(i)}return}const s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let a=!1;if(Vt(e)&&e.result&&typeof e.result=="object"){const i=e.result;if(i.task&&typeof i.task=="object"){const o=i.task;typeof o.taskId=="string"&&(a=!0,this._taskProgressTokens.set(o.taskId,r))}}if(a||this._progressHandlers.delete(r),Vt(e))s(e);else{const i=W.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){const{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof W?i:new W(S.ErrorCode.InternalError,String(i))}}return}let a;try{const i=await this.request(e,Ht,n);if(i.task)a=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new W(S.ErrorCode.InternalError,"Task creation did not return a task");for(;;){const o=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:o},Gt(o.status)){o.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:o.status==="failed"?yield{type:"error",error:new W(S.ErrorCode.InternalError,`Task ${a} failed`)}:o.status==="cancelled"&&(yield{type:"error",error:new W(S.ErrorCode.InternalError,`Task ${a} was cancelled`)});return}if(o.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}const c=o.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof W?i:new W(S.ErrorCode.InternalError,String(i))}}}request(e,r,n){const{relatedRequestId:s,resumptionToken:a,onresumptiontoken:i,task:o,relatedTask:c}=n??{};return new Promise((u,l)=>{const p=d=>{l(d)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(d){p(d);return}n?.signal?.throwIfAborted();const g=this._requestMessageId++,_={...e,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),_.params={...e.params,_meta:{...e.params?._meta||{},progressToken:g}}),o&&(_.params={..._.params,task:o}),c&&(_.params={..._.params,_meta:{..._.params?._meta||{},[It]:c}});const h=d=>{this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(d)}},{relatedRequestId:s,resumptionToken:a,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));const m=d instanceof W?d:new W(S.ErrorCode.RequestTimeout,String(d));l(m)};this._responseHandlers.set(g,d=>{if(!n?.signal?.aborted){if(d instanceof Error)return l(d);try{const m=dt(r,d.result);m.success?u(m.data):l(m.error)}catch(m){l(m)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});const w=n?.timeout??md,f=()=>h(W.fromError(S.ErrorCode.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(g,w,n?.maxTotalTimeout,f,n?.resetTimeoutOnProgress??!1);const v=c?.taskId;if(v){const d=m=>{const b=this._responseHandlers.get(g);b?b(m):this._onerror(new Error(`Response handler missing for side-channeled request ${g}`))};this._requestResolvers.set(g,d),this._enqueueTaskMessage(v,{type:"request",message:_,timestamp:Date.now()}).catch(m=>{this._cleanupTimeout(g),l(m)})}else this._transport.send(_,{relatedRequestId:s,resumptionToken:a,onresumptiontoken:i}).catch(d=>{this._cleanupTimeout(g),l(d)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},us,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},fs,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Nu,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const n=r?.relatedTask?.taskId;if(n){const o={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[It]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:o,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[It]:r.relatedTask}}}),this._transport?.send(o,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[It]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){const n=hd(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,a)=>{const i=pd(e,s);return Promise.resolve(r(i,a))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){const n=hd(e);this._notificationHandlers.set(n,s=>{const a=pd(e,s);return Promise.resolve(r(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,r);for(const s of n)if(s.type==="request"&&ts(s.message)){const a=s.message.id,i=this._requestResolvers.get(a);i?(i(new W(S.ErrorCode.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,a)=>{if(r.aborted){a(new W(S.ErrorCode.InvalidRequest,"Request cancelled"));return}const i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),a(new W(S.ErrorCode.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{const a=await n.getTask(s,r);if(!a)throw new W(S.ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(s,a,i)=>{await n.storeTaskResult(s,a,i,r);const o=await n.getTask(s,r);if(o){const c=qr.parse({method:"notifications/tasks/status",params:o});await this.notification(c),Gt(o.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,a,i)=>{const o=await n.getTask(s,r);if(!o)throw new W(S.ErrorCode.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Gt(o.status))throw new W(S.ErrorCode.InvalidParams,`Cannot update task "${s}" from terminal status "${o.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,a,i,r);const c=await n.getTask(s,r);if(c){const u=qr.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Gt(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}function _d(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function oi(t,e){const r={...t};for(const n in e){const s=n,a=e[s];if(a===void 0)continue;const i=r[s];_d(i)&&_d(a)?r[s]={...i,...a}:r[s]=a}return r}var js={exports:{}},ci={},gd;function Ry(){return gd||(gd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(z,F){return{validate:z,compare:F}}t.fullFormats={date:e(a,i),time:e(c(!0),u),"date-time":e(g(!0),_),"iso-time":e(c(),l),"iso-date-time":e(g(),h),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:v,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:K,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:m,int32:{type:"number",validate:$},int64:{type:"number",validate:E},float:{type:"number",validate:N},double:{type:"number",validate:N},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,i),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,_),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,h),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);function r(z){return z%4===0&&(z%100!==0||z%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(z){const F=n.exec(z);if(!F)return!1;const G=+F[1],Y=+F[2],ge=+F[3];return Y>=1&&Y<=12&&ge>=1&&ge<=(Y===2&&r(G)?29:s[Y])}function i(z,F){if(z&&F)return z>F?1:z<F?-1:0}const o=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(z){return function(G){const Y=o.exec(G);if(!Y)return!1;const ge=+Y[1],We=+Y[2],Ke=+Y[3],we=Y[4],mt=Y[5]==="-"?-1:1,x=+(Y[6]||0),C=+(Y[7]||0);if(x>23||C>59||z&&!we)return!1;if(ge<=23&&We<=59&&Ke<60)return!0;const q=We-C*mt,O=ge-x*mt-(q<0?1:0);return(O===23||O===-1)&&(q===59||q===-1)&&Ke<61}}function u(z,F){if(!(z&&F))return;const G=new Date("2020-01-01T"+z).valueOf(),Y=new Date("2020-01-01T"+F).valueOf();if(G&&Y)return G-Y}function l(z,F){if(!(z&&F))return;const G=o.exec(z),Y=o.exec(F);if(G&&Y)return z=G[1]+G[2]+G[3],F=Y[1]+Y[2]+Y[3],z>F?1:z<F?-1:0}const p=/t|\s/i;function g(z){const F=c(z);return function(Y){const ge=Y.split(p);return ge.length===2&&a(ge[0])&&F(ge[1])}}function _(z,F){if(!(z&&F))return;const G=new Date(z).valueOf(),Y=new Date(F).valueOf();if(G&&Y)return G-Y}function h(z,F){if(!(z&&F))return;const[G,Y]=z.split(p),[ge,We]=F.split(p),Ke=i(G,ge);if(Ke!==void 0)return Ke||u(Y,We)}const w=/\/|:/,f=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function v(z){return w.test(z)&&f.test(z)}const d=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function m(z){return d.lastIndex=0,d.test(z)}const b=-2147483648,y=2**31-1;function $(z){return Number.isInteger(z)&&z<=y&&z>=b}function E(z){return Number.isInteger(z)}function N(){return!0}const L=/[^\\]\\Z/;function K(z){if(L.test(z))return!1;try{return new RegExp(z),!0}catch{return!1}}})(ci)),ci}var ui={},yd;function Ty(){return yd||(yd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const e=pc(),r=ae(),n=r.operators,s={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},a={message:({keyword:o,schemaCode:c})=>(0,r.str)`should be ${s[o].okStr} ${c}`,params:({keyword:o,schemaCode:c})=>(0,r._)`{comparison: ${s[o].okStr}, limit: ${c}}`};t.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:a,code(o){const{gen:c,data:u,schemaCode:l,keyword:p,it:g}=o,{opts:_,self:h}=g;if(!_.validateFormats)return;const w=new e.KeywordCxt(g,h.RULES.all.format.definition,"format");w.$data?f():v();function f(){const m=c.scopeValue("formats",{ref:h.formats,code:_.code.formats}),b=c.const("fmt",(0,r._)`${m}[${w.schemaCode}]`);o.fail$data((0,r.or)((0,r._)`typeof ${b} != "object"`,(0,r._)`${b} instanceof RegExp`,(0,r._)`typeof ${b}.compare != "function"`,d(b)))}function v(){const m=w.schema,b=h.formats[m];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${p}": format "${m}" does not define "compare" function`);const y=c.scopeValue("formats",{key:m,ref:b,code:_.code.formats?(0,r._)`${_.code.formats}${(0,r.getProperty)(m)}`:void 0});o.fail$data(d(y))}function d(m){return(0,r._)`${m}.compare(${u}, ${l}) ${s[p].fail} 0`}},dependencies:["format"]};const i=o=>(o.addKeyword(t.formatLimitDefinition),o);t.default=i})(ui)),ui}var vd;function Py(){return vd||(vd=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});const r=Ry(),n=Ty(),s=ae(),a=new s.Name("fullFormats"),i=new s.Name("fastFormats"),o=(u,l={keywords:!0})=>{if(Array.isArray(l))return c(u,l,r.fullFormats,a),u;const[p,g]=l.mode==="fast"?[r.fastFormats,i]:[r.fullFormats,a],_=l.formats||r.formatNames;return c(u,_,p,g),l.keywords&&(0,n.default)(u),u};o.get=(u,l="full")=>{const g=(l==="fast"?r.fastFormats:r.fullFormats)[u];if(!g)throw new Error(`Unknown format "${u}"`);return g};function c(u,l,p,g){var _,h;(_=(h=u.opts.code).formats)!==null&&_!==void 0||(h.formats=(0,s._)`require("ajv-formats/dist/formats").${g}`);for(const w of l)u.addFormat(w,p[w])}t.exports=e=o,Object.defineProperty(e,"__esModule",{value:!0}),e.default=o})(js,js.exports)),js.exports}var Cy=Py();const Iy=Qt(Cy);function Oy(){const t=new mc({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Iy(t),t}class wd{constructor(e){this._ajv=e??Oy()}getValidator(e){const r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}class Ny{constructor(e){this._client=e}async*callToolStream(e,r=or,n){const s=this._client,a={...n,task:n?.task??(s.isToolTask(e.name)?{}:void 0)},i=s.requestStream({method:"tools/call",params:e},r,a),o=s.getToolOutputValidator(e.name);for await(const c of i){if(c.type==="result"&&o){const u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new W(S.ErrorCode.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{const l=o(u.structuredContent);if(!l.valid){yield{type:"error",error:new W(S.ErrorCode.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof W){yield{type:"error",error:l};return}yield{type:"error",error:new W(S.ErrorCode.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}}function bd(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break}}function Sd(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break}}function zs(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){const r=e,n=t.properties;for(const s of Object.keys(n)){const a=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(a,"default")&&(r[s]=a.default),r[s]!==void 0&&zs(a,r[s])}}if(Array.isArray(t.anyOf))for(const r of t.anyOf)typeof r!="boolean"&&zs(r,e);if(Array.isArray(t.oneOf))for(const r of t.oneOf)typeof r!="boolean"&&zs(r,e)}}function kd(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};const e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}class Ay extends ii{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new wd,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",La,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ma,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Aa,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Ny(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=oi(this._capabilities,e)}setRequestHandler(e,r){const s=pr(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let a;if(lt(s)){const o=s;a=o._zod?.def?.value??o.value}else{const o=s;a=o._def?.value??o.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");const i=a;if(i==="elicitation/create"){const o=async(c,u)=>{const l=dt(Va,c);if(!l.success){const d=l.error instanceof Error?l.error.message:String(l.error);throw new W(S.ErrorCode.InvalidParams,`Invalid elicitation request: ${d}`)}const{params:p}=l.data;p.mode=p.mode??"form";const{supportsFormMode:g,supportsUrlMode:_}=kd(this._capabilities.elicitation);if(p.mode==="form"&&!g)throw new W(S.ErrorCode.InvalidParams,"Client does not support form-mode elicitation requests");if(p.mode==="url"&&!_)throw new W(S.ErrorCode.InvalidParams,"Client does not support URL-mode elicitation requests");const h=await Promise.resolve(r(c,u));if(p.task){const d=dt(Ht,h);if(!d.success){const m=d.error instanceof Error?d.error.message:String(d.error);throw new W(S.ErrorCode.InvalidParams,`Invalid task creation result: ${m}`)}return d.data}const w=dt(xr,h);if(!w.success){const d=w.error instanceof Error?w.error.message:String(w.error);throw new W(S.ErrorCode.InvalidParams,`Invalid elicitation result: ${d}`)}const f=w.data,v=p.mode==="form"?p.requestedSchema:void 0;if(p.mode==="form"&&f.action==="accept"&&f.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{zs(v,f.content)}catch{}return f};return super.setRequestHandler(e,o)}if(i==="sampling/createMessage"){const o=async(c,u)=>{const l=dt(xa,c);if(!l.success){const h=l.error instanceof Error?l.error.message:String(l.error);throw new W(S.ErrorCode.InvalidParams,`Invalid sampling request: ${h}`)}const{params:p}=l.data,g=await Promise.resolve(r(c,u));if(p.task){const h=dt(Ht,g);if(!h.success){const w=h.error instanceof Error?h.error.message:String(h.error);throw new W(S.ErrorCode.InvalidParams,`Invalid task creation result: ${w}`)}return h.data}const _=dt(Es,g);if(!_.success){const h=_.error instanceof Error?_.error.message:String(_.error);throw new W(S.ErrorCode.InvalidParams,`Invalid sampling result: ${h}`)}return _.data};return super.setRequestHandler(e,o)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:Ut,capabilities:this._capabilities,clientInfo:this._clientInfo}},$a,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!_a.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.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(!this._serverCapabilities?.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(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation 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"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break}}assertTaskCapability(e){bd(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&Sd(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Ot,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Ha,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Ot,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},za,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},ja,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Ia,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Oa,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Na,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Ot,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Ot,r)}async callTool(e,r=or,n){if(this.isToolTaskRequired(e.name))throw new W(S.ErrorCode.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const s=await this.request({method:"tools/call",params:e},r,n),a=this.getToolOutputValidator(e.name);if(a){if(!s.structuredContent&&!s.isError)throw new W(S.ErrorCode.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{const i=a(s.structuredContent);if(!i.valid)throw new W(S.ErrorCode.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof W?i:new W(S.ErrorCode.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return s}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of e){if(r.outputSchema){const s=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,s)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const n=await this.request({method:"tools/list",params:e},Za,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,s){const a=Yu.safeParse(n);if(!a.success)throw new Error(`Invalid ${e} listChanged options: ${a.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:o}=a.data,{onChanged:c}=n,u=async()=>{if(!i){c(null,null);return}try{const p=await s();c(null,p)}catch(p){const g=p instanceof Error?p:new Error(String(p));c(g,null)}},l=()=>{if(o){const p=this._listChangedDebounceTimers.get(e);p&&clearTimeout(p);const g=setTimeout(u,o);this._listChangedDebounceTimers.set(e,g)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}let li;li=globalThis.crypto;async function jy(t){return(await li).getRandomValues(new Uint8Array(t))}async function zy(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length;let n="";for(;n.length<t;){const s=await jy(t-n.length);for(const a of s)a<r&&(n+=e[a%e.length])}return n}async function My(t){return await zy(t)}async function qy(t){const e=await(await li).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Zy(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await My(t),r=await qy(e);return{code_verifier:e,code_challenge:r}}const xe=Gm().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:D_.custom,message:"URL must be parseable",fatal:!0}),Ff}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Ly=Le({resource:R().url(),authorization_servers:V(xe).optional(),jwks_uri:R().url().optional(),scopes_supported:V(R()).optional(),bearer_methods_supported:V(R()).optional(),resource_signing_alg_values_supported:V(R()).optional(),resource_name:R().optional(),resource_documentation:R().optional(),resource_policy_uri:R().url().optional(),resource_tos_uri:R().url().optional(),tls_client_certificate_bound_access_tokens:ke().optional(),authorization_details_types_supported:V(R()).optional(),dpop_signing_alg_values_supported:V(R()).optional(),dpop_bound_access_tokens_required:ke().optional()}),di=Le({issuer:R(),authorization_endpoint:xe,token_endpoint:xe,registration_endpoint:xe.optional(),scopes_supported:V(R()).optional(),response_types_supported:V(R()),response_modes_supported:V(R()).optional(),grant_types_supported:V(R()).optional(),token_endpoint_auth_methods_supported:V(R()).optional(),token_endpoint_auth_signing_alg_values_supported:V(R()).optional(),service_documentation:xe.optional(),revocation_endpoint:xe.optional(),revocation_endpoint_auth_methods_supported:V(R()).optional(),revocation_endpoint_auth_signing_alg_values_supported:V(R()).optional(),introspection_endpoint:R().optional(),introspection_endpoint_auth_methods_supported:V(R()).optional(),introspection_endpoint_auth_signing_alg_values_supported:V(R()).optional(),code_challenge_methods_supported:V(R()).optional(),client_id_metadata_document_supported:ke().optional()}),Dy=Le({issuer:R(),authorization_endpoint:xe,token_endpoint:xe,userinfo_endpoint:xe.optional(),jwks_uri:xe,registration_endpoint:xe.optional(),scopes_supported:V(R()).optional(),response_types_supported:V(R()),response_modes_supported:V(R()).optional(),grant_types_supported:V(R()).optional(),acr_values_supported:V(R()).optional(),subject_types_supported:V(R()),id_token_signing_alg_values_supported:V(R()),id_token_encryption_alg_values_supported:V(R()).optional(),id_token_encryption_enc_values_supported:V(R()).optional(),userinfo_signing_alg_values_supported:V(R()).optional(),userinfo_encryption_alg_values_supported:V(R()).optional(),userinfo_encryption_enc_values_supported:V(R()).optional(),request_object_signing_alg_values_supported:V(R()).optional(),request_object_encryption_alg_values_supported:V(R()).optional(),request_object_encryption_enc_values_supported:V(R()).optional(),token_endpoint_auth_methods_supported:V(R()).optional(),token_endpoint_auth_signing_alg_values_supported:V(R()).optional(),display_values_supported:V(R()).optional(),claim_types_supported:V(R()).optional(),claims_supported:V(R()).optional(),service_documentation:R().optional(),claims_locales_supported:V(R()).optional(),ui_locales_supported:V(R()).optional(),claims_parameter_supported:ke().optional(),request_parameter_supported:ke().optional(),request_uri_parameter_supported:ke().optional(),require_request_uri_registration:ke().optional(),op_policy_uri:xe.optional(),op_tos_uri:xe.optional(),client_id_metadata_document_supported:ke().optional()}),xy=H({...Dy.shape,...di.pick({code_challenge_methods_supported:!0}).shape}),Uy=H({access_token:R(),id_token:R().optional(),token_type:R(),expires_in:x_().optional(),scope:R().optional(),refresh_token:R().optional()}).strip(),Vy=H({error:R(),error_description:R().optional(),error_uri:R().optional()}),$d=xe.optional().or(te("").transform(()=>{})),Fy=H({redirect_uris:V(xe),token_endpoint_auth_method:R().optional(),grant_types:V(R()).optional(),response_types:V(R()).optional(),client_name:R().optional(),client_uri:xe.optional(),logo_uri:$d,scope:R().optional(),contacts:V(R()).optional(),tos_uri:$d,policy_uri:R().optional(),jwks_uri:xe.optional(),jwks:m_().optional(),software_id:R().optional(),software_version:R().optional(),software_statement:R().optional()}).strip(),Hy=H({client_id:R(),client_secret:R().optional(),client_id_issued_at:_e().optional(),client_secret_expires_at:_e().optional()}).strip(),Wy=Fy.merge(Hy);H({error:R(),error_description:R().optional()}).strip(),H({token:R(),token_type_hint:R().optional()}).strip();function Ky(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Jy({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",a=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(a)}class qe extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class fi extends qe{}fi.errorCode="invalid_request";class Ms extends qe{}Ms.errorCode="invalid_client";class qs extends qe{}qs.errorCode="invalid_grant";class Zs extends qe{}Zs.errorCode="unauthorized_client";class hi extends qe{}hi.errorCode="unsupported_grant_type";class pi extends qe{}pi.errorCode="invalid_scope";class mi extends qe{}mi.errorCode="access_denied";class mr extends qe{}mr.errorCode="server_error";class _i extends qe{}_i.errorCode="temporarily_unavailable";class gi extends qe{}gi.errorCode="unsupported_response_type";class yi extends qe{}yi.errorCode="unsupported_token_type";class vi extends qe{}vi.errorCode="invalid_token";class wi extends qe{}wi.errorCode="method_not_allowed";class bi extends qe{}bi.errorCode="too_many_requests";class Ls extends qe{}Ls.errorCode="invalid_client_metadata";class Si extends qe{}Si.errorCode="insufficient_scope";class ki extends qe{}ki.errorCode="invalid_target";const Gy={[fi.errorCode]:fi,[Ms.errorCode]:Ms,[qs.errorCode]:qs,[Zs.errorCode]:Zs,[hi.errorCode]:hi,[pi.errorCode]:pi,[mi.errorCode]:mi,[mr.errorCode]:mr,[_i.errorCode]:_i,[gi.errorCode]:gi,[yi.errorCode]:yi,[vi.errorCode]:vi,[wi.errorCode]:wi,[bi.errorCode]:bi,[Ls.errorCode]:Ls,[Si.errorCode]:Si,[ki.errorCode]:ki};class it extends Error{constructor(e){super(e??"Unauthorized")}}function By(t){return["client_secret_basic","client_secret_post","none"].includes(t)}const $i="code",Ei="S256";function Ed(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&By(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Yy(t,e,r,n){const{client_id:s,client_secret:a}=e;switch(t){case"client_secret_basic":Qy(s,a,r);return;case"client_secret_post":Xy(s,a,n);return;case"none":ev(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Qy(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function Xy(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function ev(t,e){e.set("client_id",t)}async function Ri(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=Vy.parse(JSON.parse(r)),{error:s,error_description:a,error_uri:i}=n,o=Gy[s]||mr;return new o(a||"",i)}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new mr(s)}}async function zt(t,e){try{return await Ti(t,e)}catch(r){if(r instanceof Ms||r instanceof Zs)return await t.invalidateCredentials?.("all"),await Ti(t,e);if(r instanceof qs)return await t.invalidateCredentials?.("tokens"),await Ti(t,e);throw r}}async function Ti(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:a}){let i,o;try{i=await Pd(e,{resourceMetadataUrl:s},a),i.authorization_servers&&i.authorization_servers.length>0&&(o=i.authorization_servers[0])}catch{}o||(o=new URL("/",e));const c=await Td(e,t,i),u=await Nd(o,{fetchFn:a});let l=await Promise.resolve(t.clientInformation());if(!l){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const f=u?.client_id_metadata_document_supported===!0,v=t.clientMetadataUrl;if(v&&!Rd(v))throw new Ls(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${v}`);if(f&&v)l={client_id:v},await t.saveClientInformation?.(l);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const m=await Md(o,{metadata:u,clientMetadata:t.clientMetadata,fetchFn:a});await t.saveClientInformation(m),l=m}}const p=!t.redirectUrl;if(r!==void 0||p){const f=await zd(t,o,{metadata:u,resource:c,authorizationCode:r,fetchFn:a});return await t.saveTokens(f),"AUTHORIZED"}const g=await t.tokens();if(g?.refresh_token)try{const f=await jd(o,{metadata:u,clientInformation:l,refreshToken:g.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:a});return await t.saveTokens(f),"AUTHORIZED"}catch(f){if(!(!(f instanceof qe)||f instanceof mr))throw f}const _=t.state?await t.state():void 0,{authorizationUrl:h,codeVerifier:w}=await Ad(o,{metadata:u,clientInformation:l,state:_,redirectUrl:t.redirectUrl,scope:n||i?.scopes_supported?.join(" ")||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(w),await t.redirectToAuthorization(h),"REDIRECT"}function Rd(t){if(!t)return!1;try{const e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function Td(t,e,r){const n=Ky(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!Jy({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Kr(t){const e=t.headers.get("WWW-Authenticate");if(!e)return{};const[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const s=Pi(t,"resource_metadata")||void 0;let a;if(s)try{a=new URL(s)}catch{}const i=Pi(t,"scope")||void 0,o=Pi(t,"error")||void 0;return{resourceMetadataUrl:a,scope:i,error:o}}function Pi(t,e){const r=t.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),s=r.match(n);return s?s[1]||s[2]:null}function tv(t){const e=t.headers.get("WWW-Authenticate");if(!e)return;const[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return;const a=/resource_metadata="([^"]*)"/.exec(e);if(a)try{return new URL(a[1])}catch{return}}async function Pd(t,e,r=fetch){const n=await Id(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Ly.parse(await n.json())}async function Ci(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Ci(t,void 0,r):void 0;throw n}}function rv(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Cd(t,e,r=fetch){return await Ci(t,{"MCP-Protocol-Version":e},r)}function nv(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function Id(t,e,r,n){const s=new URL(t),a=n?.protocolVersion??Ut;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const c=rv(e,s.pathname);i=new URL(c,n?.metadataServerUrl??s),i.search=s.search}let o=await Cd(i,a,r);if(!n?.metadataUrl&&nv(o,s.pathname)){const c=new URL(`/.well-known/${e}`,s);o=await Cd(c,a,r)}return o}async function sv(t,{authorizationServerUrl:e,protocolVersion:r}={},n=fetch){typeof t=="string"&&(t=new URL(t)),e||(e=t),typeof e=="string"&&(e=new URL(e)),r??(r=Ut);const s=await Id(e,"oauth-authorization-server",n,{protocolVersion:r,metadataServerUrl:e});if(!s||s.status===404){await s?.body?.cancel();return}if(!s.ok)throw await s.body?.cancel(),new Error(`HTTP ${s.status} trying to load well-known OAuth metadata`);return di.parse(await s.json())}function Od(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function Nd(t,{fetchFn:e=fetch,protocolVersion:r=Ut}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},s=Od(t);for(const{url:a,type:i}of s){const o=await Ci(a,n,e);if(o){if(!o.ok){if(await o.body?.cancel(),o.status>=400&&o.status<500)continue;throw new Error(`HTTP ${o.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return i==="oauth"?di.parse(await o.json()):xy.parse(await o.json())}}}async function Ad(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:a,resource:i}){let o;if(e){if(o=new URL(e.authorization_endpoint),!e.response_types_supported.includes($i))throw new Error(`Incompatible auth server: does not support response type ${$i}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Ei))throw new Error(`Incompatible auth server: does not support code challenge method ${Ei}`)}else o=new URL("/authorize",t);const c=await Zy(),u=c.code_verifier,l=c.code_challenge;return o.searchParams.set("response_type",$i),o.searchParams.set("client_id",r.client_id),o.searchParams.set("code_challenge",l),o.searchParams.set("code_challenge_method",Ei),o.searchParams.set("redirect_uri",String(n)),a&&o.searchParams.set("state",a),s&&o.searchParams.set("scope",s),s?.includes("offline_access")&&o.searchParams.append("prompt","consent"),i&&o.searchParams.set("resource",i.href),{authorizationUrl:o,codeVerifier:u}}function Ii(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function Oi(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:a,fetchFn:i}){const o=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(a&&r.set("resource",a.href),s)await s(c,r,o,e);else if(n){const l=e?.token_endpoint_auth_methods_supported??[],p=Ed(n,l);Yy(p,n,c,r)}const u=await(i??fetch)(o,{method:"POST",headers:c,body:r});if(!u.ok)throw await Ri(u);return Uy.parse(await u.json())}async function av(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:s,redirectUri:a,resource:i,addClientAuthentication:o,fetchFn:c}){const u=Ii(n,s,a);return Oi(t,{metadata:e,tokenRequestParams:u,clientInformation:r,addClientAuthentication:o,resource:i,fetchFn:c})}async function jd(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:a,fetchFn:i}){const o=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await Oi(t,{metadata:e,tokenRequestParams:o,clientInformation:r,addClientAuthentication:a,resource:s,fetchFn:i});return{refresh_token:n,...c}}async function zd(t,e,{metadata:r,resource:n,authorizationCode:s,fetchFn:a}={}){const i=t.clientMetadata.scope;let o;if(t.prepareTokenRequest&&(o=await t.prepareTokenRequest(i)),!o){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const u=await t.codeVerifier();o=Ii(s,u,t.redirectUrl)}const c=await t.clientInformation();return Oi(e,{metadata:r,tokenRequestParams:o,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:a})}async function Md(t,{metadata:e,clientMetadata:r,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const a=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok)throw await Ri(a);return Wy.parse(await a.json())}class qd extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Ni(t){}function Zd(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=Ni,onError:r=Ni,onRetry:n=Ni,onComment:s}=t;let a="",i=!0,o,c="",u="";function l(w){const f=i?w.replace(/^\xEF\xBB\xBF/,""):w,[v,d]=iv(`${a}${f}`);for(const m of v)p(m);a=d,i=!1}function p(w){if(w===""){_();return}if(w.startsWith(":")){s&&s(w.slice(w.startsWith(": ")?2:1));return}const f=w.indexOf(":");if(f!==-1){const v=w.slice(0,f),d=w[f+1]===" "?2:1,m=w.slice(f+d);g(v,m,w);return}g(w,"",w)}function g(w,f,v){switch(w){case"event":u=f;break;case"data":c=`${c}${f}
40
+ `;break;case"id":o=f.includes("\0")?void 0:f;break;case"retry":/^\d+$/.test(f)?n(parseInt(f,10)):r(new qd(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:v}));break;default:r(new qd(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:f,line:v}));break}}function _(){c.length>0&&e({id:o,event:u||void 0,data:c.endsWith(`
41
+ `)?c.slice(0,-1):c}),o=void 0,c="",u=""}function h(w={}){a&&w.consume&&p(a),i=!0,o=void 0,c="",u="",a=""}return{feed:l,reset:h}}function iv(t){const e=[];let r="",n=0;for(;n<t.length;){const s=t.indexOf("\r",n),a=t.indexOf(`
42
+ `,n);let i=-1;if(s!==-1&&a!==-1?i=Math.min(s,a):s!==-1?s===t.length-1?i=-1:i=s:a!==-1&&(i=a),i===-1){r=t.slice(n);break}else{const o=t.slice(n,i);e.push(o),n=i+1,t[n-1]==="\r"&&t[n]===`
43
+ `&&n++}}return[e,r]}class Ld extends Event{constructor(e,r){var n,s;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(s=r?.message)!=null?s:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(Dd(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(Dd(this),r)}}function ov(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Ai(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Ai).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Ai(t.cause)}`:t.message:`${t}`}function Dd(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var xd=t=>{throw TypeError(t)},ji=(t,e,r)=>e.has(t)||xd("Cannot "+r),ue=(t,e,r)=>(ji(t,e,"read from private field"),r?r.call(t):e.get(t)),je=(t,e,r)=>e.has(t)?xd("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Te=(t,e,r,n)=>(ji(t,e,"write to private field"),e.set(t,r),r),$t=(t,e,r)=>(ji(t,e,"access private method"),r),Be,Bt,_r,Ds,xs,Jr,gr,Gr,Mt,yr,vr,wr,Br,pt,zi,Mi,qi,Ud,Zi,Li,Yr,Di,xi;class Us extends EventTarget{constructor(e,r){var n,s;super(),je(this,pt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,je(this,Be),je(this,Bt),je(this,_r),je(this,Ds),je(this,xs),je(this,Jr),je(this,gr),je(this,Gr,null),je(this,Mt),je(this,yr),je(this,vr,null),je(this,wr,null),je(this,Br,null),je(this,Mi,async a=>{var i;ue(this,yr).reset();const{body:o,redirected:c,status:u,headers:l}=a;if(u===204){$t(this,pt,Yr).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?Te(this,_r,new URL(a.url)):Te(this,_r,void 0),u!==200){$t(this,pt,Yr).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){$t(this,pt,Yr).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(ue(this,Be)===this.CLOSED)return;Te(this,Be,this.OPEN);const p=new Event("open");if((i=ue(this,Br))==null||i.call(this,p),this.dispatchEvent(p),typeof o!="object"||!o||!("getReader"in o)){$t(this,pt,Yr).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}const g=new TextDecoder,_=o.getReader();let h=!0;do{const{done:w,value:f}=await _.read();f&&ue(this,yr).feed(g.decode(f,{stream:!w})),w&&(h=!1,ue(this,yr).reset(),$t(this,pt,Di).call(this))}while(h)}),je(this,qi,a=>{Te(this,Mt,void 0),!(a.name==="AbortError"||a.type==="aborted")&&$t(this,pt,Di).call(this,Ai(a))}),je(this,Zi,a=>{typeof a.id=="string"&&Te(this,Gr,a.id);const i=new MessageEvent(a.event||"message",{data:a.data,origin:ue(this,_r)?ue(this,_r).origin:ue(this,Bt).origin,lastEventId:a.id||""});ue(this,wr)&&(!a.event||a.event==="message")&&ue(this,wr).call(this,i),this.dispatchEvent(i)}),je(this,Li,a=>{Te(this,Jr,a)}),je(this,xi,()=>{Te(this,gr,void 0),ue(this,Be)===this.CONNECTING&&$t(this,pt,zi).call(this)});try{if(e instanceof URL)Te(this,Bt,e);else if(typeof e=="string")Te(this,Bt,new URL(e,cv()));else throw new Error("Invalid URL")}catch{throw ov("An invalid or illegal string was specified")}Te(this,yr,Zd({onEvent:ue(this,Zi),onRetry:ue(this,Li)})),Te(this,Be,this.CONNECTING),Te(this,Jr,3e3),Te(this,xs,(n=r?.fetch)!=null?n:globalThis.fetch),Te(this,Ds,(s=r?.withCredentials)!=null?s:!1),$t(this,pt,zi).call(this)}get readyState(){return ue(this,Be)}get url(){return ue(this,Bt).href}get withCredentials(){return ue(this,Ds)}get onerror(){return ue(this,vr)}set onerror(e){Te(this,vr,e)}get onmessage(){return ue(this,wr)}set onmessage(e){Te(this,wr,e)}get onopen(){return ue(this,Br)}set onopen(e){Te(this,Br,e)}addEventListener(e,r,n){const s=r;super.addEventListener(e,s,n)}removeEventListener(e,r,n){const s=r;super.removeEventListener(e,s,n)}close(){ue(this,gr)&&clearTimeout(ue(this,gr)),ue(this,Be)!==this.CLOSED&&(ue(this,Mt)&&ue(this,Mt).abort(),Te(this,Be,this.CLOSED),Te(this,Mt,void 0))}}Be=new WeakMap,Bt=new WeakMap,_r=new WeakMap,Ds=new WeakMap,xs=new WeakMap,Jr=new WeakMap,gr=new WeakMap,Gr=new WeakMap,Mt=new WeakMap,yr=new WeakMap,vr=new WeakMap,wr=new WeakMap,Br=new WeakMap,pt=new WeakSet,zi=function(){Te(this,Be,this.CONNECTING),Te(this,Mt,new AbortController),ue(this,xs)(ue(this,Bt),$t(this,pt,Ud).call(this)).then(ue(this,Mi)).catch(ue(this,qi))},Mi=new WeakMap,qi=new WeakMap,Ud=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...ue(this,Gr)?{"Last-Event-ID":ue(this,Gr)}:void 0},cache:"no-store",signal:(t=ue(this,Mt))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Zi=new WeakMap,Li=new WeakMap,Yr=function(t,e){var r;ue(this,Be)!==this.CLOSED&&Te(this,Be,this.CLOSED);const n=new Ld("error",{code:e,message:t});(r=ue(this,vr))==null||r.call(this,n),this.dispatchEvent(n)},Di=function(t,e){var r;if(ue(this,Be)===this.CLOSED)return;Te(this,Be,this.CONNECTING);const n=new Ld("error",{code:e,message:t});(r=ue(this,vr))==null||r.call(this,n),this.dispatchEvent(n),Te(this,gr,setTimeout(ue(this,xi),ue(this,Jr)))},xi=new WeakMap,Us.CONNECTING=0,Us.OPEN=1,Us.CLOSED=2;function cv(){const t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function Qr(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Ui(t=fetch,e){return e?async(r,n)=>{const s={...e,...n,headers:n?.headers?{...Qr(e.headers),...Qr(n.headers)}:e.headers};return t(r,s)}:t}class Vd extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}}class uv{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Ui(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new it("No auth provider");let e;try{e=await zt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new it;return await this._startOrAuth()}async _commonHeaders(){const e={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const r=Qr(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){const e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new Us(this._url.href,{...this._eventSourceInit,fetch:async(s,a)=>{const i=await this._commonHeaders();i.set("Accept","text/event-stream");const o=await e(s,{...a,headers:i});if(o.status===401&&o.headers.has("www-authenticate")){const{resourceMetadataUrl:c,scope:u}=Kr(o);this._resourceMetadataUrl=c,this._scope=u}return o}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{if(s.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const a=new Vd(s.code,s.message,s);n(a),this.onerror?.(a)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{const a=s;try{if(this._endpoint=new URL(a.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){n(i),this.onerror?.(i),this.close();return}r()}),this._eventSource.onmessage=s=>{const a=s;let i;try{i=Mr.parse(JSON.parse(a.data))}catch(o){this.onerror?.(o);return}this.onmessage?.(i)}})}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 it("No auth provider");if(await zt(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new it("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{const r=await this._commonHeaders();r.set("content-type","application/json");const n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._endpoint,n);if(!s.ok){const a=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){const{resourceMetadataUrl:i,scope:o}=Kr(s);if(this._resourceMetadataUrl=i,this._scope=o,await zt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new it;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${a}`)}await s.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}}class lv extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let s;super({start(a){s=Zd({onEvent:i=>{a.enqueue(i)},onError(i){e==="terminate"?a.error(i):typeof e=="function"&&e(i)},onRetry:r,onComment:n})},transform(a){s.feed(a)}})}}const dv={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Yt extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class fv{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Ui(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??dv}async _authThenStart(){if(!this._authProvider)throw new it("No auth provider");let e;try{e=await zt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new it;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const r=Qr(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){const{resumptionToken:r}=e;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);const s=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!s.ok){if(await s.body?.cancel(),s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Yt(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,s=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),s)}_scheduleReconnection(e,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,n){if(!e)return;const{onresumptiontoken:s,replayMessageId:a}=r;let i,o=!1,c=!1;(async()=>{try{const l=e.pipeThrough(new TextDecoderStream).pipeThrough(new lv({onRetry:_=>{this._serverRetryMs=_}})).getReader();for(;;){const{value:_,done:h}=await l.read();if(h)break;if(_.id&&(i=_.id,o=!0,s?.(_.id)),!!_.data&&(!_.event||_.event==="message"))try{const w=Mr.parse(JSON.parse(_.data));Vt(w)&&(c=!0,a!==void 0&&(w.id=a)),this.onmessage?.(w)}catch(w){this.onerror?.(w)}}(n||o)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:s,replayMessageId:a},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||o)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:s,replayMessageId:a},0)}catch(_){this.onerror?.(new Error(`Failed to reconnect: ${_ instanceof Error?_.message:String(_)}`))}}})()}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 it("No auth provider");if(await zt(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new it("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{const{resumptionToken:n,onresumptiontoken:s}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:ts(e)?e.id:void 0}).catch(g=>this.onerror?.(g));return}const a=await this._commonHeaders();a.set("content-type","application/json"),a.set("accept","application/json, text/event-stream");const i={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,i),c=o.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!o.ok){const g=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Yt(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:_,scope:h}=Kr(o);if(this._resourceMetadataUrl=_,this._scope=h,await zt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new it;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){const{resourceMetadataUrl:_,scope:h,error:w}=Kr(o);if(w==="insufficient_scope"){const f=o.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===f)throw new Yt(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),_&&(this._resourceMetadataUrl=_),this._lastUpscopingHeader=f??void 0,await zt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new it;return this.send(e)}}throw new Yt(o.status,`Error POSTing to endpoint: ${g}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Ru(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(g=>this.onerror?.(g));return}const l=(Array.isArray(e)?e:[e]).filter(g=>"method"in g&&"id"in g&&g.id!==void 0).length>0,p=o.headers.get("content-type");if(l)if(p?.includes("text/event-stream"))this._handleSseStream(o.body,{onresumptiontoken:s},!1);else if(p?.includes("application/json")){const g=await o.json(),_=Array.isArray(g)?g.map(h=>Mr.parse(h)):[Mr.parse(g)];for(const h of _)this.onmessage?.(h)}else throw await o.body?.cancel(),new Yt(-1,`Unexpected content type: ${p}`);else await o.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Yt(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}}class hv{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}class pv extends ii{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Lr.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{const a=this._loggingLevels.get(s);return a?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new wd,this.setRequestHandler(ss,n=>this._oninitialize(n)),this.setNotificationHandler(as,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Da,async(n,s)=>{const a=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,o=Lr.safeParse(i);return o.success&&this._loggingLevels.set(a,o.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new hv(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=oi(this._capabilities,e)}setRequestHandler(e,r){const s=pr(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let a;if(lt(s)){const o=s;a=o._zod?.def?.value??o.value}else{const o=s;a=o._def?.value??o.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){const o=async(c,u)=>{const l=dt(Zr,c);if(!l.success){const h=l.error instanceof Error?l.error.message:String(l.error);throw new W(S.ErrorCode.InvalidParams,`Invalid tools/call request: ${h}`)}const{params:p}=l.data,g=await Promise.resolve(r(c,u));if(p.task){const h=dt(Ht,g);if(!h.success){const w=h.error instanceof Error?h.error.message:String(h.error);throw new W(S.ErrorCode.InvalidParams,`Invalid task creation result: ${w}`)}return h.data}const _=dt(or,g);if(!_.success){const h=_.error instanceof Error?_.error.message:String(_.error);throw new W(S.ErrorCode.InvalidParams,`Invalid tools/call result: ${h}`)}return _.data};return super.setRequestHandler(e,o)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break}}assertTaskCapability(e){Sd(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&bd(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:_a.includes(r)?r:Ut,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ot)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],a=s.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,o=i?Array.isArray(i.content)?i.content:[i.content]:[],c=o.some(u=>u.type==="tool_use");if(a){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){const u=new Set(o.filter(p=>p.type==="tool_use").map(p=>p.id)),l=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(u.size!==l.size||![...u].every(p=>l.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Ua,r):this.request({method:"sampling/createMessage",params:e},Es,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const s=e;return this.request({method:"elicitation/create",params:s},xr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const s=e.mode==="form"?e:{...e,mode:"form"},a=await this.request({method:"elicitation/create",params:s},xr,r);if(a.action==="accept"&&a.content&&s.requestedSchema)try{const o=this._jsonSchemaValidator.getValidator(s.requestedSchema)(a.content);if(!o.valid)throw new W(S.ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${o.errorMessage}`)}catch(i){throw i instanceof W?i:new W(S.ErrorCode.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return a}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Wa,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const mv=/^[A-Za-z0-9._-]{1,128}$/;function _v(t){const e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!mv.test(t)){const r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,a)=>a.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function gv(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(const r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Fd(t){const e=_v(t);return gv(t,e.warnings),e.isValid}class yv{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){const s={taskSupport:"required",...r.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}}class vv{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new pv(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new yv(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(qt($s)),this.server.assertCanSetRequestHandler(qt(Zr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler($s,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{const n={name:e,title:r.title,description:r.description,inputSchema:(()=>{const s=Wr(r.inputSchema);return s?fd(s,{strictUnions:!0,pipeStrategy:"input"}):bv})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const s=Wr(r.outputSchema);s&&(n.outputSchema=fd(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Zr,async(e,r)=>{try{const n=this._registeredTools[e.params.name];if(!n)throw new W(S.ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new W(S.ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);const s=!!e.params.task,a=n.execution?.taskSupport,i="createTask"in n.handler;if((a==="required"||a==="optional")&&!i)throw new W(S.ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!s)throw new W(S.ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(n,e,r);const o=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,o,r);return s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof W&&n.code===S.ErrorCode.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;const a=Wr(e.inputSchema)??e.inputSchema,i=await ri(a,r);if(!i.success){const o="error"in i?i.error:"Unknown error",c=ni(o);throw new W(S.ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new W(S.ErrorCode.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const s=Wr(e.outputSchema),a=await ri(s,r.structuredContent);if(!a.success){const i="error"in a?a.error:"Unknown error",o=ni(i);throw new W(S.ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${o}`)}}async executeToolHandler(e,r,n){const s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");const i={...n,taskStore:n.taskStore};if(e.inputSchema){const o=s;return await Promise.resolve(o.createTask(r,i))}else{const o=s;return await Promise.resolve(o.createTask(i))}}if(e.inputSchema){const i=s;return await Promise.resolve(i(r,n))}else{const i=s;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const s=await this.validateToolInput(e,r.params.arguments,r.params.name),a=e.handler,i={...n,taskStore:n.taskStore},o=s?await Promise.resolve(a.createTask(s,i)):await Promise.resolve(a.createTask(i)),c=o.task.taskId;let u=o.task;const l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(g=>setTimeout(g,l));const p=await n.taskStore.getTask(c);if(!p)throw new W(S.ErrorCode.InternalError,`Task ${c} not found during polling`);u=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(qt(Rs)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Rs,async e=>{switch(e.params.ref.type){case"ref/prompt":return Tl(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Pl(e),this.handleResourceCompletion(e,e.params.ref);default:throw new W(S.ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){const n=this._registeredPrompts[r.name];if(!n)throw new W(S.ErrorCode.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new W(S.ErrorCode.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Xr;const a=pr(n.argsSchema)?.[e.params.argument.name];if(!Ja(a))return Xr;const i=zl(a);if(!i)return Xr;const o=await i(e.params.argument.value,e.params.context);return Kd(o)}async handleResourceCompletion(e,r){const n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Xr;throw new W(S.ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return Xr;const a=await s(e.params.argument.value,e.params.context);return Kd(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(qt(ps)),this.server.assertCanSetRequestHandler(qt(ms)),this.server.assertCanSetRequestHandler(qt(gs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ps,async(e,r)=>{const n=Object.entries(this._registeredResources).filter(([a,i])=>i.enabled).map(([a,i])=>({uri:a,name:i.name,...i.metadata})),s=[];for(const a of Object.values(this._registeredResourceTemplates)){if(!a.resourceTemplate.listCallback)continue;const i=await a.resourceTemplate.listCallback(r);for(const o of i.resources)s.push({...a.metadata,...o})}return{resources:[...n,...s]}}),this.server.setRequestHandler(ms,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(gs,async(e,r)=>{const n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new W(S.ErrorCode.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(const a of Object.values(this._registeredResourceTemplates)){const i=a.resourceTemplate.uriTemplate.match(n.toString());if(i)return a.readCallback(n,i,r)}throw new W(S.ErrorCode.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(qt(ys)),this.server.assertCanSetRequestHandler(qt(vs)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ys,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?kv(r.argsSchema):void 0}))})),this.server.setRequestHandler(vs,async(e,r)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new W(S.ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new W(S.ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const s=Wr(n.argsSchema),a=await ri(s,e.params.arguments);if(!a.success){const c="error"in a?a.error:"Unknown error",u=ni(c);throw new W(S.ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}const i=a.data,o=n.callback;return await Promise.resolve(o(i,r))}else{const s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());const a=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const i=this._createRegisteredResource(e,void 0,r,s,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const i=this._createRegisteredResourceTemplate(e,void 0,r,s,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const a=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,r,n,s,a){const i={name:e,title:r,metadata:s,readCallback:a,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:o=>{typeof o.uri<"u"&&o.uri!==n&&(delete this._registeredResources[n],o.uri&&(this._registeredResources[o.uri]=i)),typeof o.name<"u"&&(i.name=o.name),typeof o.title<"u"&&(i.title=o.title),typeof o.metadata<"u"&&(i.metadata=o.metadata),typeof o.callback<"u"&&(i.readCallback=o.callback),typeof o.enabled<"u"&&(i.enabled=o.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,s,a){const i={resourceTemplate:n,title:r,metadata:s,readCallback:a,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;const o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,s,a){const i={title:r,description:n,argsSchema:s===void 0?void 0:hr(s),callback:a,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:o=>{typeof o.name<"u"&&o.name!==e&&(delete this._registeredPrompts[e],o.name&&(this._registeredPrompts[o.name]=i)),typeof o.title<"u"&&(i.title=o.title),typeof o.description<"u"&&(i.description=o.description),typeof o.argsSchema<"u"&&(i.argsSchema=hr(o.argsSchema)),typeof o.callback<"u"&&(i.callback=o.callback),typeof o.enabled<"u"&&(i.enabled=o.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,s&&Object.values(s).some(c=>{const u=c instanceof kt?c._def?.innerType:c;return Ja(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,a,i,o,c,u){Fd(e);const l={title:r,description:n,inputSchema:Wd(s),outputSchema:Wd(a),annotations:i,execution:o,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&Fd(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=l)),typeof p.title<"u"&&(l.title=p.title),typeof p.description<"u"&&(l.description=p.description),typeof p.paramsSchema<"u"&&(l.inputSchema=hr(p.paramsSchema)),typeof p.outputSchema<"u"&&(l.outputSchema=hr(p.outputSchema)),typeof p.callback<"u"&&(l.handler=p.callback),typeof p.annotations<"u"&&(l.annotations=p.annotations),typeof p._meta<"u"&&(l._meta=p._meta),typeof p.enabled<"u"&&(l.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,a,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){const c=r[0];Vi(c)?(s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Vi(r[0])&&(i=r.shift())):typeof c=="object"&&c!==null&&(i=r.shift())}const o=r[0];return this._createRegisteredTool(e,void 0,n,s,a,i,{taskSupport:"forbidden"},void 0,o)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:s,description:a,inputSchema:i,outputSchema:o,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,s,a,i,o,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());const a=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:s,description:a,argsSchema:i}=r,o=this._createRegisteredPrompt(e,s,a,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class wv{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new bt(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}}const bv={type:"object",properties:{}};function Hd(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Sv(t){return"_def"in t||"_zod"in t||Hd(t)}function Vi(t){return typeof t!="object"||t===null||Sv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Hd)}function Wd(t){if(t)return Vi(t)?hr(t):t}function kv(t){const e=pr(t);return e?Object.entries(e).map(([r,n])=>{const s=Lg(n),a=Dg(n);return{name:r,description:s,required:!a}}):[]}function qt(t){const r=pr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=rd(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Kd(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}const Xr={completion:{values:[],hasMore:!1}};S.Ajv=mc,S.AnnotationsSchema=Wt,S.AudioContentSchema=Ss,S.BaseMetadataSchema=Ft,S.BlobResourceContentsSchema=Pa,S.BooleanSchemaSchema=cl,S.COMPLETABLE_SYMBOL=Ts,S.CallToolRequestParamsSchema=Bu,S.CallToolRequestSchema=Zr,S.CallToolResultSchema=or,S.CancelTaskRequestSchema=hs,S.CancelTaskResultSchema=Nu,S.CancelledNotificationParamsSchema=vu,S.CancelledNotificationSchema=ns,S.Client=Ay,S.ClientCapabilitiesSchema=ku,S.ClientNotificationSchema=tg,S.ClientRequestSchema=eg,S.ClientResultSchema=rg,S.ClientTasksCapabilitySchema=bu,S.CompatibilityCallToolResultSchema=Q_,S.CompleteRequestParamsSchema=Rl,S.CompleteRequestSchema=Rs,S.CompleteResultSchema=Ha,S.ContentBlockSchema=ks,S.CreateMessageRequestParamsSchema=ol,S.CreateMessageRequestSchema=xa,S.CreateMessageResultSchema=Es,S.CreateMessageResultWithToolsSchema=Ua,S.CreateTaskResultSchema=Ht,S.CursorSchema=ya,S.DEFAULT_NEGOTIATED_PROTOCOL_VERSION=U_,S.DEFAULT_REQUEST_TIMEOUT_MSEC=md,S.ElicitRequestFormParamsSchema=wl,S.ElicitRequestParamsSchema=Sl,S.ElicitRequestSchema=Va,S.ElicitRequestURLParamsSchema=bl,S.ElicitResultSchema=xr,S.ElicitationCompleteNotificationParamsSchema=kl,S.ElicitationCompleteNotificationSchema=$l,S.EmbeddedResourceSchema=Hu,S.EmptyResultSchema=Ot,S.EnumSchemaSchema=yl,S.GetPromptRequestParamsSchema=Vu,S.GetPromptRequestSchema=vs,S.GetPromptResultSchema=za,S.GetTaskPayloadRequestSchema=ls,S.GetTaskPayloadResultSchema=Y_,S.GetTaskRequestSchema=cs,S.GetTaskResultSchema=us,S.IconSchema=wu,S.IconsSchema=rr,S.ImageContentSchema=bs,S.ImplementationSchema=ka,S.InitializeRequestParamsSchema=$u,S.InitializeRequestSchema=ss,S.InitializeResultSchema=$a,S.InitializedNotificationSchema=as,S.JSONRPCErrorResponseSchema=zr,S.JSONRPCErrorSchema=H_,S.JSONRPCMessageSchema=Mr,S.JSONRPCNotificationSchema=ba,S.JSONRPCRequestSchema=wa,S.JSONRPCResponseSchema=K_,S.JSONRPCResultResponseSchema=rs,S.JSONRPC_VERSION=Ar,S.LATEST_PROTOCOL_VERSION=Ut,S.LegacyTitledEnumSchemaSchema=hl,S.ListChangedOptionsBaseSchema=Yu,S.ListPromptsRequestSchema=ys,S.ListPromptsResultSchema=ja,S.ListResourceTemplatesRequestSchema=ms,S.ListResourceTemplatesResultSchema=Oa,S.ListResourcesRequestSchema=ps,S.ListResourcesResultSchema=Ia,S.ListRootsRequestSchema=Il,S.ListRootsResultSchema=Wa,S.ListTasksRequestSchema=ds,S.ListTasksResultSchema=fs,S.ListToolsRequestSchema=$s,S.ListToolsResultSchema=Za,S.LoggingLevelSchema=Lr,S.LoggingMessageNotificationParamsSchema=Xu,S.LoggingMessageNotificationSchema=el,S.McpError=W,S.McpServer=vv,S.ModelHintSchema=tl,S.ModelPreferencesSchema=rl,S.MultiSelectEnumSchemaSchema=gl,S.NotificationSchema=rt,S.NumberSchemaSchema=ll,S.PaginatedRequestParamsSchema=Cu,S.PaginatedRequestSchema=nr,S.PaginatedResultSchema=sr,S.PingRequestSchema=is,S.PrimitiveSchemaDefinitionSchema=vl,S.ProgressNotificationParamsSchema=Pu,S.ProgressNotificationSchema=os,S.ProgressSchema=Tu,S.ProgressTokenSchema=ga,S.PromptArgumentSchema=xu,S.PromptListChangedNotificationSchema=Ma,S.PromptMessageSchema=Ku,S.PromptReferenceSchema=El,S.PromptSchema=Uu,S.Protocol=ii,S.RELATED_TASK_META_KEY=It,S.ReadResourceRequestParamsSchema=ju,S.ReadResourceRequestSchema=gs,S.ReadResourceResultSchema=Na,S.RelatedTaskMetadataSchema=_u,S.RequestIdSchema=jr,S.RequestSchema=ze,S.ResourceContentsSchema=Ea,S.ResourceLinkSchema=Wu,S.ResourceListChangedNotificationSchema=Aa,S.ResourceReferenceSchema=X_,S.ResourceRequestParamsSchema=_s,S.ResourceSchema=Ca,S.ResourceTemplate=wv,S.ResourceTemplateReferenceSchema=Fa,S.ResourceTemplateSchema=Au,S.ResourceUpdatedNotificationParamsSchema=Lu,S.ResourceUpdatedNotificationSchema=Du,S.ResultSchema=Me,S.RoleSchema=ir,S.RootSchema=Cl,S.RootsListChangedNotificationSchema=Ol,S.SSEClientTransport=uv,S.SUPPORTED_PROTOCOL_VERSIONS=_a,S.SamplingContentSchema=al,S.SamplingMessageContentBlockSchema=Dr,S.SamplingMessageSchema=il,S.ServerCapabilitiesSchema=Eu,S.ServerNotificationSchema=sg,S.ServerRequestSchema=ng,S.ServerResultSchema=ag,S.ServerTasksCapabilitySchema=Su,S.SetLevelRequestParamsSchema=Qu,S.SetLevelRequestSchema=Da,S.SingleSelectEnumSchemaSchema=pl,S.SseError=Vd,S.StreamableHTTPClientTransport=fv,S.StreamableHTTPError=Yt,S.StringSchemaSchema=ul,S.SubscribeRequestParamsSchema=zu,S.SubscribeRequestSchema=Mu,S.TaskAugmentedRequestParamsSchema=tr,S.TaskCreationParamsSchema=V_,S.TaskMetadataSchema=mu,S.TaskSchema=ar,S.TaskStatusNotificationParamsSchema=Ou,S.TaskStatusNotificationSchema=qr,S.TaskStatusSchema=Iu,S.TextContentSchema=ws,S.TextResourceContentsSchema=Ra,S.TitledMultiSelectEnumSchemaSchema=_l,S.TitledSingleSelectEnumSchemaSchema=fl,S.ToolAnnotationsSchema=Ju,S.ToolChoiceSchema=nl,S.ToolExecutionSchema=Gu,S.ToolListChangedNotificationSchema=La,S.ToolResultContentSchema=sl,S.ToolSchema=qa,S.ToolUseContentSchema=Fu,S.UnauthorizedError=it,S.UnsubscribeRequestParamsSchema=qu,S.UnsubscribeRequestSchema=Zu,S.UntitledMultiSelectEnumSchemaSchema=ml,S.UntitledSingleSelectEnumSchemaSchema=dl,S.UriTemplate=bt,S.UrlElicitationRequiredError=Nl,S.assertCompleteRequestPrompt=Tl,S.assertCompleteRequestResourceTemplate=Pl,S.auth=zt,S.buildDiscoveryUrls=Od,S.completable=og,S.createFetchWithInit=Ui,S.discoverAuthorizationServerMetadata=Nd,S.discoverOAuthMetadata=sv,S.discoverOAuthProtectedResourceMetadata=Pd,S.exchangeAuthorization=av,S.extractResourceMetadataUrl=tv,S.extractWWWAuthenticateParams=Kr,S.fetchToken=zd,S.getCompleter=zl,S.getDisplayName=ug,S.getSupportedElicitationModes=kd,S.isCompletable=Ja,S.isHttpsUrl=Rd,S.isInitializeRequest=B_,S.isInitializedNotification=Ru,S.isJSONRPCError=W_,S.isJSONRPCErrorResponse=Sa,S.isJSONRPCNotification=yu,S.isJSONRPCRequest=ts,S.isJSONRPCResponse=F_,S.isJSONRPCResultResponse=Vt,S.isTaskAugmentedRequestParams=gu,S.mergeCapabilities=oi,S.normalizeHeaders=Qr,S.parseErrorResponse=Ri,S.prepareAuthorizationCodeRequest=Ii,S.refreshAuthorization=jd,S.registerClient=Md,S.selectClientAuthMethod=Ed,S.selectResourceURL=Td,S.startAuthorization=Ad,S.unwrapCompletable=cg,Object.defineProperty(S,Symbol.toStringTag,{value:"Module"})}));